code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import numpy as np import random from sklearn.metrics import mean_squared_error from sklearn.neural_network import MLPClassifier def one_hot_generator(length): a = [] for i in range(0, length): i = random.randint(0, 7) a.append(i) output = np.eye(8)[a] return output n_train = 150 train = one_hot_generator(n_train) test = one_hot_generator(30) # --------------------------------------Multi-layer perceptron analysis---------------------------- # Training with a multi-layer perceptron with one hidden layer. iteration = 15000 mlp = MLPClassifier(hidden_layer_sizes=2, max_iter=iteration) mlp_result = mlp.fit(train, train) # Prediction train_out = mlp.predict(train) test_out = mlp.predict(test) print("train:\n", train[n_train-10:]) print("train out:\n", train_out[n_train-10:]) print("test:\n", test[:8]) print("test out:\n", test_out[:8]) error = mean_squared_error(test, test_out) print("mean_squared_error:", error) print("n_iter_:", mlp.n_iter_) print("weight:\n", mlp.coefs_) print("weight[0]:\n", mlp.coefs_[0]) print("weights[0][0]\n", mlp.coefs_[0][0]) print("sum of weights:", sum(mlp.coefs_[0][0]))
[ "numpy.eye", "random.randint", "sklearn.metrics.mean_squared_error", "sklearn.neural_network.MLPClassifier" ]
[((594, 649), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {'hidden_layer_sizes': '(2)', 'max_iter': 'iteration'}), '(hidden_layer_sizes=2, max_iter=iteration)\n', (607, 649), False, 'from sklearn.neural_network import MLPClassifier\n'), ((923, 957), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['test', 'test_out'], {}), '(test, test_out)\n', (941, 957), False, 'from sklearn.metrics import mean_squared_error\n'), ((225, 245), 'random.randint', 'random.randint', (['(0)', '(7)'], {}), '(0, 7)\n', (239, 245), False, 'import random\n'), ((281, 290), 'numpy.eye', 'np.eye', (['(8)'], {}), '(8)\n', (287, 290), True, 'import numpy as np\n')]
import pandas as pd; import numpy as np; x1 = pd.DataFrame(np.random.randint(0, 100, (3, 4)), columns = list('ABCD'), index = np.arange(3)); x2 = pd.DataFrame(np.random.randint(100, 200, (3, 4)), columns = list('ABCD'), index = np.arange(3)+3); x22 = pd.DataFrame(np.random.randint(100, 200, (3, 4)), columns = list('ABCD'), index = np.arange(3)); print(x1); print(x2); x3 = pd.concat([x1, x2],axis=0); print(x3); x4 = pd.concat([x1, x2],axis=1); print(x4); x5 = pd.concat([x1, x22],axis=1); print(x5);
[ "numpy.random.randint", "numpy.arange", "pandas.concat" ]
[((430, 457), 'pandas.concat', 'pd.concat', (['[x1, x2]'], {'axis': '(0)'}), '([x1, x2], axis=0)\n', (439, 457), True, 'import pandas as pd\n'), ((474, 501), 'pandas.concat', 'pd.concat', (['[x1, x2]'], {'axis': '(1)'}), '([x1, x2], axis=1)\n', (483, 501), True, 'import pandas as pd\n'), ((519, 547), 'pandas.concat', 'pd.concat', (['[x1, x22]'], {'axis': '(1)'}), '([x1, x22], axis=1)\n', (528, 547), True, 'import pandas as pd\n'), ((60, 93), 'numpy.random.randint', 'np.random.randint', (['(0)', '(100)', '(3, 4)'], {}), '(0, 100, (3, 4))\n', (77, 93), True, 'import numpy as np\n'), ((178, 213), 'numpy.random.randint', 'np.random.randint', (['(100)', '(200)', '(3, 4)'], {}), '(100, 200, (3, 4))\n', (195, 213), True, 'import numpy as np\n'), ((301, 336), 'numpy.random.randint', 'np.random.randint', (['(100)', '(200)', '(3, 4)'], {}), '(100, 200, (3, 4))\n', (318, 336), True, 'import numpy as np\n'), ((145, 157), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (154, 157), True, 'import numpy as np\n'), ((388, 400), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (397, 400), True, 'import numpy as np\n'), ((265, 277), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (274, 277), True, 'import numpy as np\n')]
# General imports import numpy as np import torch # DeepMoD stuff from deepymod import DeepMoD from deepymod.model.func_approx import NN from deepymod.model.library import Library1D from deepymod.model.constraint import LeastSquares from deepymod.model.sparse_estimators import Threshold from deepymod.training import train from deepymod.training.sparsity_scheduler import TrainTestPeriodic, Periodic, TrainTest from deepymod.data import Dataset from deepymod.data.burgers import BurgersDelta from deepymod.analysis import load_tensorboard if torch.cuda.is_available(): device = "cuda" else: device = "cpu" # Settings for reproducibility np.random.seed(42) torch.manual_seed(0) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Making dataset v = 0.1 A = 1.0 x = np.linspace(-3, 4, 100) t = np.linspace(0.5, 5.0, 50) x_grid, t_grid = np.meshgrid(x, t, indexing="ij") dataset = Dataset(BurgersDelta, v=v, A=A) X, y = dataset.create_dataset( x_grid.reshape(-1, 1), t_grid.reshape(-1, 1), n_samples=1000, noise=0.4, random=True, normalize=False, ) X, y = X.to(device), y.to(device) network = NN(2, [30, 30, 30, 30, 30], 1) library = Library1D(poly_order=2, diff_order=3) # Library function estimator = Threshold(0.1) # Sparse estimator constraint = LeastSquares() # How to constrain model = DeepMoD(network, library, estimator, constraint).to( device ) # Putting it all in the model # sparsity_scheduler = TrainTestPeriodic(periodicity=50, patience=200, delta=1e-5) # in terms of write iterations # sparsity_scheduler = Periodic(initial_iteration=1000, periodicity=25) sparsity_scheduler = TrainTest(patience=200, delta=1e-5) optimizer = torch.optim.Adam( model.parameters(), betas=(0.99, 0.999), amsgrad=True, lr=2e-3 ) # Defining optimizer train( model, X, y, optimizer, sparsity_scheduler, exp_ID="Test", split=0.8, write_iterations=25, max_iterations=20000, delta=0.001, patience=200, )
[ "numpy.meshgrid", "numpy.random.seed", "deepymod.training.train", "torch.manual_seed", "deepymod.model.library.Library1D", "deepymod.DeepMoD", "deepymod.model.func_approx.NN", "torch.cuda.is_available", "numpy.linspace", "deepymod.model.sparse_estimators.Threshold", "deepymod.training.sparsity_s...
[((547, 572), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (570, 572), False, 'import torch\n'), ((651, 669), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (665, 669), True, 'import numpy as np\n'), ((670, 690), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (687, 690), False, 'import torch\n'), ((811, 834), 'numpy.linspace', 'np.linspace', (['(-3)', '(4)', '(100)'], {}), '(-3, 4, 100)\n', (822, 834), True, 'import numpy as np\n'), ((839, 864), 'numpy.linspace', 'np.linspace', (['(0.5)', '(5.0)', '(50)'], {}), '(0.5, 5.0, 50)\n', (850, 864), True, 'import numpy as np\n'), ((882, 914), 'numpy.meshgrid', 'np.meshgrid', (['x', 't'], {'indexing': '"""ij"""'}), "(x, t, indexing='ij')\n", (893, 914), True, 'import numpy as np\n'), ((925, 956), 'deepymod.data.Dataset', 'Dataset', (['BurgersDelta'], {'v': 'v', 'A': 'A'}), '(BurgersDelta, v=v, A=A)\n', (932, 956), False, 'from deepymod.data import Dataset\n'), ((1162, 1192), 'deepymod.model.func_approx.NN', 'NN', (['(2)', '[30, 30, 30, 30, 30]', '(1)'], {}), '(2, [30, 30, 30, 30, 30], 1)\n', (1164, 1192), False, 'from deepymod.model.func_approx import NN\n'), ((1203, 1240), 'deepymod.model.library.Library1D', 'Library1D', ([], {'poly_order': '(2)', 'diff_order': '(3)'}), '(poly_order=2, diff_order=3)\n', (1212, 1240), False, 'from deepymod.model.library import Library1D\n'), ((1273, 1287), 'deepymod.model.sparse_estimators.Threshold', 'Threshold', (['(0.1)'], {}), '(0.1)\n', (1282, 1287), False, 'from deepymod.model.sparse_estimators import Threshold\n'), ((1321, 1335), 'deepymod.model.constraint.LeastSquares', 'LeastSquares', ([], {}), '()\n', (1333, 1335), False, 'from deepymod.model.constraint import LeastSquares\n'), ((1669, 1705), 'deepymod.training.sparsity_scheduler.TrainTest', 'TrainTest', ([], {'patience': '(200)', 'delta': '(1e-05)'}), '(patience=200, delta=1e-05)\n', (1678, 1705), False, 'from deepymod.training.sparsity_scheduler import TrainTestPeriodic, Periodic, TrainTest\n'), ((1828, 1977), 'deepymod.training.train', 'train', (['model', 'X', 'y', 'optimizer', 'sparsity_scheduler'], {'exp_ID': '"""Test"""', 'split': '(0.8)', 'write_iterations': '(25)', 'max_iterations': '(20000)', 'delta': '(0.001)', 'patience': '(200)'}), "(model, X, y, optimizer, sparsity_scheduler, exp_ID='Test', split=0.8,\n write_iterations=25, max_iterations=20000, delta=0.001, patience=200)\n", (1833, 1977), False, 'from deepymod.training import train\n'), ((1364, 1412), 'deepymod.DeepMoD', 'DeepMoD', (['network', 'library', 'estimator', 'constraint'], {}), '(network, library, estimator, constraint)\n', (1371, 1412), False, 'from deepymod import DeepMoD\n')]
from typing import Union, Optional, Dict import pandas as pd import numpy as np import sha_calc as sha_calc from gmhazard_calc import site from gmhazard_calc import utils from gmhazard_calc import shared from gmhazard_calc import hazard from gmhazard_calc import gm_data from gmhazard_calc import site_source from gmhazard_calc import rupture from gmhazard_calc import constants as const from gmhazard_calc.im import IM from .DisaggResult import BranchDisaggResult, EnsembleDisaggResult, DisaggGridData def run_ensemble_disagg( ensemble: gm_data.Ensemble, site_info: site.SiteInfo, im: IM, exceedance: Optional[float] = None, im_value: Optional[float] = None, calc_mean_values: Optional[bool] = False, hazard_result: Optional[hazard.EnsembleHazardResult] = None, ) -> EnsembleDisaggResult: """Computes the ensemble disagg, combining the different branches as per equations (9) and (10) from "Consideration and Propagation of Ground Motion Selection Epistemic Uncertainties to Seismic Performance Metrics (<NAME>, 2018)" Parameters ---------- ensemble: Ensemble site_info: SiteInfo im: IM exceedance : float, optional Compute disagg at this exceedance, either the exceedance or the im_value parameter has to be given im_value: float, optional Compute disagg at this im value Returns ------- BaseDisaggResult """ ensemble.check_im(im) # Select the IMEnsemble im_ensemble = ensemble.get_im_ensemble(im.im_type) # Get the IM value of interest im_value = _get_im_value_and_checks( ensemble, site_info, im, exceedance, im_value, hazard_result=hazard_result ) # Compute disagg for each branch branches_dict = run_branches_disagg(im_ensemble, site_info, im, None, im_value) fault_disagg_df = pd.DataFrame( { (branch_name, column): disagg_result.fault_disagg_id_ix[column] for branch_name, disagg_result in branches_dict.items() for column in ["contribution", "epsilon"] } ) ds_disagg_df = pd.DataFrame( { (branch_name, column): disagg_result.ds_disagg_id_ix[column] for branch_name, disagg_result in branches_dict.items() for column in ["contribution", "epsilon"] } ) del branches_dict # Fault disagg branches mean adj_branch_weights, _ = shared.compute_adj_branch_weights( ensemble, im, im_value, site_info ) fault_disagg_mean = ( fault_disagg_df.multiply(adj_branch_weights, axis=1, level=0) .groupby(axis=1, level=1) .sum() ) # DS disagg branches mean ds_disagg_mean = ( ds_disagg_df.multiply(adj_branch_weights, axis=1, level=0) .groupby(axis=1, level=1) .sum() ) mean_values = None if calc_mean_values: # Use rupture_ids (due to required location matching for rrup mean) full_disagg = pd.concat([fault_disagg_mean, ds_disagg_mean]) full_disagg.index = rupture.rupture_id_ix_to_rupture_id( ensemble, full_disagg.index.values ) # Compute mean magnitude mag_mean = shared.compute_contr_mean( im_ensemble.rupture_df_id.magnitude, full_disagg.contribution.to_frame(), ).values[0] mag_16th, mag_84th = shared.compute_contr_16_84( im_ensemble.rupture_df_id.magnitude, full_disagg.contribution.to_frame() ) # Epsilon mean, ignore entries with epsilon np.inf mask = np.abs(full_disagg.epsilon) != np.inf epsilon_mean = shared.compute_contr_mean( full_disagg.epsilon.loc[mask], full_disagg.contribution.loc[mask].to_frame(), ).values[0] # Rrrup mean # Convert to rupture_id for matching fault_rrup_disagg_df = fault_disagg_mean.contribution.copy() fault_rrup_disagg_df.index = rupture.rupture_id_ix_to_rupture_id( ensemble, fault_rrup_disagg_df.index.values.astype(str) ) ds_rrup_disagg_df = ds_disagg_mean.contribution.copy() ds_rrup_disagg_df.index = rupture.rupture_id_ix_to_rupture_id( ensemble, ds_rrup_disagg_df.index.values.astype(str) ) # Get distances fault_rrup_disagg_df = site_source.match_ruptures( site_source.get_distance_df(ensemble.flt_ssddb_ffp, site_info), fault_rrup_disagg_df, const.SourceType.fault, ) ds_rrup_disagg_df = site_source.match_ruptures( site_source.get_distance_df(ensemble.ds_ssddb_ffp, site_info), ds_rrup_disagg_df, const.SourceType.distributed, ) # Ignore nan entries (due to 200 km limit in SiteSourceDB) rrup_disagg_df = pd.concat([fault_rrup_disagg_df.rrup, ds_rrup_disagg_df.rrup]) mask = ~rrup_disagg_df.isna() rrup_mean = shared.compute_contr_mean( rrup_disagg_df.loc[mask], full_disagg.contribution.loc[mask].to_frame(), ).values[0] rrup_16th, rrup_84th = shared.compute_contr_16_84( rrup_disagg_df.loc[mask], full_disagg.contribution.loc[mask].to_frame() ) mean_values = pd.Series( index=[ "magnitude_16th", "magnitude", "magnitude_84th", "epsilon", "rrup_16th", "rrup", "rrup_84th", ], data=[ mag_16th, mag_mean, mag_84th, epsilon_mean, rrup_16th, rrup_mean, rrup_84th, ], ) return EnsembleDisaggResult( fault_disagg_mean, ds_disagg_mean, site_info, im, im_value, ensemble, im_ensemble, exceedance=exceedance, mean_values=mean_values, ) def run_branches_disagg( im_ensemble: gm_data.IMEnsemble, site_info: site.SiteInfo, im: IM, exceedance: Optional[float] = None, im_value: Optional[float] = None, ) -> Dict[str, BranchDisaggResult]: """Computes the disagg for every branch in the ensemble Parameters ---------- im_ensemble: IMEnsemble site_info: SiteInfo im: IM exceedance : float, optional Compute disagg at this exceedance, either the exceedance or the im_value parameter has to be given im_value: float, optional Compute disagg at this im value Returns ------- Dictionary Keys are the branch names """ # Consistency checks im_ensemble.check_im(im) im_value = _get_im_value_and_checks( im_ensemble.ensemble, site_info, im, exceedance=exceedance, im_level=im_value ) # Compute disagg for each branch branch_disagg_dict = {} for branch_name, branch in im_ensemble.branches_dict.items(): branch_disagg_dict[branch_name] = run_branch_disagg( im_ensemble, branch, site_info, im, None, im_value ) return branch_disagg_dict def run_branch_disagg( im_ensemble: gm_data.IMEnsemble, branch: gm_data.Branch, site_info: site.SiteInfo, im: IM, exceedance: Optional[float] = None, im_value: Optional[float] = None, ) -> BranchDisaggResult: """Computes the disagg a single branch of an ensemble Parameters ---------- im_ensemble: IMEnsemble branch: Branch site_info: SiteInfo im: IM exceedance : float, optional Compute disagg at this ensemble exceedance, either the exceedance or the im_value parameter has to be given Note: The IM value used to perform disagg is calculated using the mean ensemble hazard, not the branch hazard. im_value: float, optional Compute disagg at this im value """ # Consistency checks im_ensemble.check_im(im) im_value = _get_im_value_and_checks( im_ensemble.ensemble, site_info, im, exceedance=exceedance, im_level=im_value ) # Get the ground motion probabilities fault_gm_prob = shared.get_gm_prob( branch, site_info, im, im_value, const.SourceType.fault, ensemble=im_ensemble.ensemble, ) ds_gm_prob = shared.get_gm_prob( branch, site_info, im, im_value, const.SourceType.distributed, ensemble=im_ensemble.ensemble, ) # Get the recurrence probabilities rec_prob_df = branch.rupture_df_id_ix["annual_rec_prob"] # Compute the branch hazard for the specified IM value excd_prob = sha_calc.hazard_single( pd.concat([fault_gm_prob, ds_gm_prob]), rec_prob_df ) # Fault based disagg fault_disagg = sha_calc.disagg_exceedance( fault_gm_prob, rec_prob_df, excd_prob=excd_prob ) fault_disagg.name = "contribution" fault_epsilon = _compute_epsilon( branch, fault_gm_prob, site_info, im, const.SourceType.fault, ensemble=im_ensemble.ensemble, ) fault_disagg = pd.merge( fault_disagg, fault_epsilon, left_index=True, right_index=True ) # DS based disagg ds_disagg = sha_calc.disagg_exceedance(ds_gm_prob, rec_prob_df, excd_prob=excd_prob) ds_disagg.name = "contribution" ds_epsilon = _compute_epsilon( branch, ds_gm_prob, site_info, im, const.SourceType.distributed, ensemble=im_ensemble.ensemble, ) ds_disagg = pd.merge(ds_disagg, ds_epsilon, left_index=True, right_index=True) return BranchDisaggResult( fault_disagg, ds_disagg, site_info, im, im_value, branch, exceedance=exceedance ) def run_disagg_gridding( disagg_data: Union[BranchDisaggResult, EnsembleDisaggResult], mag_min: float = 5.0, mag_n_bins: int = 16, mag_bin_size: float = 0.25, rrup_min: float = 0.0, rrup_n_bins: int = 20, rrup_bin_size: float = 10, ) -> DisaggGridData: """Computes the 2d histogram using magnitude and rrup as x and y, with weights given by the contribution of each rupture Parameters ---------- disagg_data: BaseDisaggResult mag_min: float Minimum magnitude mag_n_bins: int Number of magnitude bins mag_bin_size: float Magnitude size of the bins rrup_min: float Minimum rrup rrup_n_bins: int Number of rrup bins rrup_bin_size: float Rrup size of the bins Returns ------- DisaggGridData """ ensemble = ( disagg_data.ensemble if isinstance(disagg_data, EnsembleDisaggResult) else disagg_data.im_ensemble.ensemble ) im_ensemble = disagg_data.im_ensemble # Get rupture details for the flt ruptures flt_ruptures = pd.merge( im_ensemble.rupture_df_id, disagg_data.fault_disagg_id, left_index=True, right_index=True, ) # Add distance data to fault rupture data dist_df = site_source.get_distance_df(ensemble.flt_ssddb_ffp, disagg_data.site_info) if dist_df is None: raise Exception( f"No distance data available for station {disagg_data.site_info.station_name}, " f"can't perform gridding without distance data!" ) flt_ruptures = site_source.match_ruptures( dist_df, flt_ruptures.copy(), const.SourceType.fault ) # Get rupture details for the ds ruptures ds_ruptures = pd.merge( im_ensemble.rupture_df_id, disagg_data.ds_disagg_id, left_index=True, right_index=True, ) # Add DS location name to DS rupture data ds_ruptures["loc_name"] = np.asarray( list(np.chararray.split(ds_ruptures.index.values.astype(str), "--")), dtype=str )[:, 0] ds_ruptures["rupture_id"] = ds_ruptures.index.values # Add distance data to DS rupture data dist_df = site_source.get_distance_df(ensemble.ds_ssddb_ffp, disagg_data.site_info) if dist_df is None: raise Exception( f"No distance data available for station {disagg_data.site_info.station_name}, " f"can't perform gridding without distance data!" ) ds_ruptures = site_source.match_ruptures( dist_df, ds_ruptures.copy(), const.SourceType.distributed ) # Drop nan values (ruptures for which rrup is not available, due to rrup > 200km) flt_ruptures.dropna(axis=0, how="any", subset=np.asarray(["rrup"]), inplace=True) ds_ruptures.dropna(axis=0, how="any", subset=np.asarray(["rrup"]), inplace=True) rupture_df = pd.concat([flt_ruptures, ds_ruptures], sort=True) mag_bins = np.arange( mag_min, mag_min + ((mag_n_bins + 1) * mag_bin_size), mag_bin_size ) rrup_bins = np.arange( rrup_min, rrup_min + ((rrup_n_bins + 1) * rrup_bin_size), rrup_bin_size ) # Bin by fault and distributed seismicity mask = rupture_df.rupture_type == const.SourceType.fault.value flt_bin_contr, mag_edges, rrup_edges = np.histogram2d( rupture_df.magnitude.loc[mask], rupture_df.rrup.loc[mask], bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.loc[mask].values, ) mask = rupture_df.rupture_type == const.SourceType.distributed.value ds_bin_contr, _, __ = np.histogram2d( rupture_df.magnitude.loc[mask], rupture_df.rrup.loc[mask], bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.loc[mask].values, ) # Epsilon bin definitions eps_bins = [ (-np.inf, -2), (-2, -1), (-1, -0.5), (-0.5, 0), (0, 0.5), (0.5, 1), (1, 2), (2, np.inf), ] eps_bin_contr = [] for ix, (cur_bin_min, cur_bin_max) in enumerate(eps_bins): cur_mask = (cur_bin_min <= rupture_df.epsilon.values) & ( rupture_df.epsilon.values < cur_bin_max ) cur_bin_contr, _, __ = np.histogram2d( rupture_df.magnitude.loc[cur_mask], rupture_df.rrup.loc[cur_mask], bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.loc[cur_mask].values, ) eps_bin_contr.append(cur_bin_contr) return DisaggGridData( disagg_data, flt_bin_contr, ds_bin_contr, eps_bins, eps_bin_contr, mag_edges, rrup_edges, mag_min, mag_n_bins, mag_bin_size, rrup_min, rrup_n_bins, rrup_bin_size, ) def _get_im_value_and_checks( ensemble: gm_data.Ensemble, site_info: site.SiteInfo, im: IM, exceedance: float = None, im_level: float = None, hazard_result: hazard.HazardResult = None, ) -> float: """Performs consistency checks and computes the IM level if not provided""" if exceedance is None and im_level is None: raise ValueError("Either the exceendance or the IM level has to be specified.") if exceedance is not None and im_level is not None: print( "Both the exceedance and the IM level have been specified, " "using the IM level for the calculation." ) # Retrieve the IM level from the ensemble hazard result if im_level is None: hazard_result = ( hazard.run_ensemble_hazard(ensemble, site_info, im) if hazard_result is None else hazard_result ) im_level = hazard_result.exceedance_to_im(exceedance) return im_level def _compute_epsilon( branch: gm_data.Branch, gm_prob_df: pd.Series, site_info: site.SiteInfo, im: IM, source_type: const.SourceType, ensemble: gm_data.Ensemble = None, ): """Computes epsilon for the specified branch using the provided rupture exceedance probabilities Parameters ---------- branch: Branch gm_prob_df: pd.DataFrame site_info: SiteInfo im: IM source_type: SourceType ensemble: Ensemble, optional If specified and the Ensemble has IM data caching enabled then IM data is retrieved from the cache if possible Returns ------- pd.Series Epsilon for each rupture """ im_data, im_data_type = shared.get_im_data( branch, ensemble, site_info, source_type, im_component=im.component, as_rupture_id_ix=True, ) if im_data_type is const.IMDataType.parametric: epsilon = sha_calc.epsilon_para(utils.to_mu_sigma(im_data, im), gm_prob_df) else: epsilon = sha_calc.epsilon_non_para(im_data[str(im)], gm_prob_df) epsilon.name = "epsilon" return epsilon
[ "numpy.abs", "gmhazard_calc.site_source.get_distance_df", "gmhazard_calc.hazard.run_ensemble_hazard", "gmhazard_calc.utils.to_mu_sigma", "sha_calc.disagg_exceedance", "numpy.histogram2d", "pandas.merge", "gmhazard_calc.shared.get_im_data", "gmhazard_calc.shared.get_gm_prob", "gmhazard_calc.rupture...
[((2430, 2498), 'gmhazard_calc.shared.compute_adj_branch_weights', 'shared.compute_adj_branch_weights', (['ensemble', 'im', 'im_value', 'site_info'], {}), '(ensemble, im, im_value, site_info)\n', (2463, 2498), False, 'from gmhazard_calc import shared\n'), ((8183, 8293), 'gmhazard_calc.shared.get_gm_prob', 'shared.get_gm_prob', (['branch', 'site_info', 'im', 'im_value', 'const.SourceType.fault'], {'ensemble': 'im_ensemble.ensemble'}), '(branch, site_info, im, im_value, const.SourceType.fault,\n ensemble=im_ensemble.ensemble)\n', (8201, 8293), False, 'from gmhazard_calc import shared\n'), ((8362, 8479), 'gmhazard_calc.shared.get_gm_prob', 'shared.get_gm_prob', (['branch', 'site_info', 'im', 'im_value', 'const.SourceType.distributed'], {'ensemble': 'im_ensemble.ensemble'}), '(branch, site_info, im, im_value, const.SourceType.\n distributed, ensemble=im_ensemble.ensemble)\n', (8380, 8479), False, 'from gmhazard_calc import shared\n'), ((8842, 8917), 'sha_calc.disagg_exceedance', 'sha_calc.disagg_exceedance', (['fault_gm_prob', 'rec_prob_df'], {'excd_prob': 'excd_prob'}), '(fault_gm_prob, rec_prob_df, excd_prob=excd_prob)\n', (8868, 8917), True, 'import sha_calc as sha_calc\n'), ((9175, 9247), 'pandas.merge', 'pd.merge', (['fault_disagg', 'fault_epsilon'], {'left_index': '(True)', 'right_index': '(True)'}), '(fault_disagg, fault_epsilon, left_index=True, right_index=True)\n', (9183, 9247), True, 'import pandas as pd\n'), ((9301, 9373), 'sha_calc.disagg_exceedance', 'sha_calc.disagg_exceedance', (['ds_gm_prob', 'rec_prob_df'], {'excd_prob': 'excd_prob'}), '(ds_gm_prob, rec_prob_df, excd_prob=excd_prob)\n', (9327, 9373), True, 'import sha_calc as sha_calc\n'), ((9611, 9677), 'pandas.merge', 'pd.merge', (['ds_disagg', 'ds_epsilon'], {'left_index': '(True)', 'right_index': '(True)'}), '(ds_disagg, ds_epsilon, left_index=True, right_index=True)\n', (9619, 9677), True, 'import pandas as pd\n'), ((10899, 11003), 'pandas.merge', 'pd.merge', (['im_ensemble.rupture_df_id', 'disagg_data.fault_disagg_id'], {'left_index': '(True)', 'right_index': '(True)'}), '(im_ensemble.rupture_df_id, disagg_data.fault_disagg_id, left_index\n =True, right_index=True)\n', (10907, 11003), True, 'import pandas as pd\n'), ((11099, 11173), 'gmhazard_calc.site_source.get_distance_df', 'site_source.get_distance_df', (['ensemble.flt_ssddb_ffp', 'disagg_data.site_info'], {}), '(ensemble.flt_ssddb_ffp, disagg_data.site_info)\n', (11126, 11173), False, 'from gmhazard_calc import site_source\n'), ((11566, 11667), 'pandas.merge', 'pd.merge', (['im_ensemble.rupture_df_id', 'disagg_data.ds_disagg_id'], {'left_index': '(True)', 'right_index': '(True)'}), '(im_ensemble.rupture_df_id, disagg_data.ds_disagg_id, left_index=\n True, right_index=True)\n', (11574, 11667), True, 'import pandas as pd\n'), ((12006, 12079), 'gmhazard_calc.site_source.get_distance_df', 'site_source.get_distance_df', (['ensemble.ds_ssddb_ffp', 'disagg_data.site_info'], {}), '(ensemble.ds_ssddb_ffp, disagg_data.site_info)\n', (12033, 12079), False, 'from gmhazard_calc import site_source\n'), ((12686, 12735), 'pandas.concat', 'pd.concat', (['[flt_ruptures, ds_ruptures]'], {'sort': '(True)'}), '([flt_ruptures, ds_ruptures], sort=True)\n', (12695, 12735), True, 'import pandas as pd\n'), ((12752, 12827), 'numpy.arange', 'np.arange', (['mag_min', '(mag_min + (mag_n_bins + 1) * mag_bin_size)', 'mag_bin_size'], {}), '(mag_min, mag_min + (mag_n_bins + 1) * mag_bin_size, mag_bin_size)\n', (12761, 12827), True, 'import numpy as np\n'), ((12860, 12945), 'numpy.arange', 'np.arange', (['rrup_min', '(rrup_min + (rrup_n_bins + 1) * rrup_bin_size)', 'rrup_bin_size'], {}), '(rrup_min, rrup_min + (rrup_n_bins + 1) * rrup_bin_size, rrup_bin_size\n )\n', (12869, 12945), True, 'import numpy as np\n'), ((13114, 13274), 'numpy.histogram2d', 'np.histogram2d', (['rupture_df.magnitude.loc[mask]', 'rupture_df.rrup.loc[mask]'], {'bins': '(mag_bins, rrup_bins)', 'weights': 'rupture_df.contribution.loc[mask].values'}), '(rupture_df.magnitude.loc[mask], rupture_df.rrup.loc[mask],\n bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.loc[mask].\n values)\n', (13128, 13274), True, 'import numpy as np\n'), ((13405, 13565), 'numpy.histogram2d', 'np.histogram2d', (['rupture_df.magnitude.loc[mask]', 'rupture_df.rrup.loc[mask]'], {'bins': '(mag_bins, rrup_bins)', 'weights': 'rupture_df.contribution.loc[mask].values'}), '(rupture_df.magnitude.loc[mask], rupture_df.rrup.loc[mask],\n bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.loc[mask].\n values)\n', (13419, 13565), True, 'import numpy as np\n'), ((16321, 16436), 'gmhazard_calc.shared.get_im_data', 'shared.get_im_data', (['branch', 'ensemble', 'site_info', 'source_type'], {'im_component': 'im.component', 'as_rupture_id_ix': '(True)'}), '(branch, ensemble, site_info, source_type, im_component=\n im.component, as_rupture_id_ix=True)\n', (16339, 16436), False, 'from gmhazard_calc import shared\n'), ((2987, 3033), 'pandas.concat', 'pd.concat', (['[fault_disagg_mean, ds_disagg_mean]'], {}), '([fault_disagg_mean, ds_disagg_mean])\n', (2996, 3033), True, 'import pandas as pd\n'), ((3062, 3133), 'gmhazard_calc.rupture.rupture_id_ix_to_rupture_id', 'rupture.rupture_id_ix_to_rupture_id', (['ensemble', 'full_disagg.index.values'], {}), '(ensemble, full_disagg.index.values)\n', (3097, 3133), False, 'from gmhazard_calc import rupture\n'), ((4837, 4899), 'pandas.concat', 'pd.concat', (['[fault_rrup_disagg_df.rrup, ds_rrup_disagg_df.rrup]'], {}), '([fault_rrup_disagg_df.rrup, ds_rrup_disagg_df.rrup])\n', (4846, 4899), True, 'import pandas as pd\n'), ((5279, 5482), 'pandas.Series', 'pd.Series', ([], {'index': "['magnitude_16th', 'magnitude', 'magnitude_84th', 'epsilon', 'rrup_16th',\n 'rrup', 'rrup_84th']", 'data': '[mag_16th, mag_mean, mag_84th, epsilon_mean, rrup_16th, rrup_mean, rrup_84th]'}), "(index=['magnitude_16th', 'magnitude', 'magnitude_84th', 'epsilon',\n 'rrup_16th', 'rrup', 'rrup_84th'], data=[mag_16th, mag_mean, mag_84th,\n epsilon_mean, rrup_16th, rrup_mean, rrup_84th])\n", (5288, 5482), True, 'import pandas as pd\n'), ((8739, 8777), 'pandas.concat', 'pd.concat', (['[fault_gm_prob, ds_gm_prob]'], {}), '([fault_gm_prob, ds_gm_prob])\n', (8748, 8777), True, 'import pandas as pd\n'), ((14048, 14221), 'numpy.histogram2d', 'np.histogram2d', (['rupture_df.magnitude.loc[cur_mask]', 'rupture_df.rrup.loc[cur_mask]'], {'bins': '(mag_bins, rrup_bins)', 'weights': 'rupture_df.contribution.loc[cur_mask].values'}), '(rupture_df.magnitude.loc[cur_mask], rupture_df.rrup.loc[\n cur_mask], bins=(mag_bins, rrup_bins), weights=rupture_df.contribution.\n loc[cur_mask].values)\n', (14062, 14221), True, 'import numpy as np\n'), ((3582, 3609), 'numpy.abs', 'np.abs', (['full_disagg.epsilon'], {}), '(full_disagg.epsilon)\n', (3588, 3609), True, 'import numpy as np\n'), ((4386, 4448), 'gmhazard_calc.site_source.get_distance_df', 'site_source.get_distance_df', (['ensemble.flt_ssddb_ffp', 'site_info'], {}), '(ensemble.flt_ssddb_ffp, site_info)\n', (4413, 4448), False, 'from gmhazard_calc import site_source\n'), ((4598, 4659), 'gmhazard_calc.site_source.get_distance_df', 'site_source.get_distance_df', (['ensemble.ds_ssddb_ffp', 'site_info'], {}), '(ensemble.ds_ssddb_ffp, site_info)\n', (4625, 4659), False, 'from gmhazard_calc import site_source\n'), ((12548, 12568), 'numpy.asarray', 'np.asarray', (["['rrup']"], {}), "(['rrup'])\n", (12558, 12568), True, 'import numpy as np\n'), ((12633, 12653), 'numpy.asarray', 'np.asarray', (["['rrup']"], {}), "(['rrup'])\n", (12643, 12653), True, 'import numpy as np\n'), ((15387, 15438), 'gmhazard_calc.hazard.run_ensemble_hazard', 'hazard.run_ensemble_hazard', (['ensemble', 'site_info', 'im'], {}), '(ensemble, site_info, im)\n', (15413, 15438), False, 'from gmhazard_calc import hazard\n'), ((16580, 16610), 'gmhazard_calc.utils.to_mu_sigma', 'utils.to_mu_sigma', (['im_data', 'im'], {}), '(im_data, im)\n', (16597, 16610), False, 'from gmhazard_calc import utils\n')]
import numpy as np import cv2 as cv import os import imghdr from tqdm import tqdm """ 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. """ image_files = [] lower_res = [] def compare_images(directory, show_imgs=True, similarity="high", force_remove=False, compression=50, rotate=False, verbose=False): """ directory (str).........Folder to search for duplicate/similar images show_imgs (bool)........True = shows the duplicate/similar images found in output False = doesn't show found images similarity (str)........"high" = Searches for duplicate images, more precise "low" = Finds similar images compression (int).......Recommended not to change default value compression in px (height x width) of the images before being compared the higher the compression i.e. the higher the pixel size, the more computational resources and time required verbose (bool)..........Print results to console if True force_remove (bool).....Removes duplicates if True """ # list where the found duplicate/similar images are stored global lower_res imgs_matrix = create_imgs_matrix(directory, compression) if imgs_matrix.any(): if similarity == "low": # search for similar images ref = 1000 else: # search for 1:1 duplicate images ref = 200 main_img = 0 compared_img = 1 nrows, ncols = compression, compression srow_A = 0 erow_A = nrows srow_B = erow_A erow_B = srow_B + nrows pbar = tqdm(total=len(folder_files), desc='Checking for duplicates') while erow_B <= imgs_matrix.shape[0]: halt = 0 while compared_img < (len(image_files)) and not halt: # select two images from imgs_matrix imgA = imgs_matrix[srow_A: erow_A, 0: ncols] # rows # columns imgB = imgs_matrix[srow_B: erow_B, 0: ncols] # rows # columns # compare the images if not rotate: if image_files[main_img] not in lower_res: err = mse(imgA, imgB) if err < ref: if show_imgs == True: show_img_figs(image_files[main_img], image_files[compared_img], err) show_file_info(compared_img, main_img) halt = check_img_quality(directory, image_files[main_img], image_files[compared_img], lower_res) elif rotate: rotations = 0 # check all rotations of images while image_files[main_img] not in lower_res and rotations <= 3: if rotations != 0: imgB = rotate_img(imgB) err = mse(imgA, imgB) if err < ref: if show_imgs == True: show_img_figs(image_files[main_img], image_files[compared_img], err) show_file_info(compared_img, main_img) halt = 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 pbar.update(1) pbar.close() if verbose: print(f'\nDONE. Found {len(lower_res)} duplicate image pairs in {len(folder_files)} total images.') if len(lower_res) > 0: print(f'\nThe following files had lower resolution:\n{lower_res}') if force_remove: for filename in lower_res: try: os.remove(f"{directory}{filename}") except Exception: print(f"Could not remove {filename}") # Function that searches the folder for image files, converts them to a matrix def create_imgs_matrix(directory, compression): imgs_matrix = None global image_files # create list of all files in directory global folder_files folder_files = [filename for filename in os.listdir(directory)] # create images matrix counter = 0 for filename in tqdm(folder_files, desc='Creating Image Matrix'): if not os.path.isdir(directory + filename) and imghdr.what(directory + filename): img = cv.imdecode(np.fromfile(directory + filename, dtype=np.uint8), cv.IMREAD_UNCHANGED) if type(img) == np.ndarray: if len(img.shape) == 2: # conver greyscale img to 3 channel img img = np.stack((img,) * 3, axis=-1) img = img[...,0:3] img = cv.resize(img, dsize=(compression, compression), interpolation=cv.INTER_CUBIC) if counter == 0: imgs_matrix = img image_files.append(filename) counter += 1 else: try: imgs_matrix = np.concatenate((imgs_matrix, img)) image_files.append(filename) except: print(f"Can't add {filename} to Matrix. It might be a black and white image.") 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): img_a = cv.imread(f"{folder}{imageA}") img_b = cv.imread(f"{folder}{imageB}") img_a = cv.resize(img_a, dsize=(640, 640), interpolation=cv.INTER_CUBIC) img_b = cv.resize(img_b, dsize=(640, 640), interpolation=cv.INTER_CUBIC) display = np.concatenate((img_a, img_b), axis=1) cv.imshow(f"{imageA} and {imageB} has a mse of {err}", display) cv.waitKey(0) cv.destroyAllWindows() #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): size_imgA = os.stat(directory + imageA).st_size size_imgB = os.stat(directory + imageB).st_size stop = False if size_imgA > size_imgB: if imageB not in lower_res: add_to_list(imageB, list) else: if imageA not in lower_res: add_to_list(imageA, list) stop = True return stop if __name__ == '__main__': #global lower_res, folder, image_files folder = 'test_images/' compare_images(folder, show_imgs=False, similarity="High ", compression=50, rotate=False, force_remove=False)
[ "cv2.resize", "numpy.stack", "tqdm.tqdm", "os.remove", "os.stat", "cv2.waitKey", "cv2.destroyAllWindows", "os.path.isdir", "numpy.fromfile", "imghdr.what", "cv2.imread", "numpy.rot90", "cv2.imshow", "os.listdir", "numpy.concatenate" ]
[((4929, 4977), 'tqdm.tqdm', 'tqdm', (['folder_files'], {'desc': '"""Creating Image Matrix"""'}), "(folder_files, desc='Creating Image Matrix')\n", (4933, 4977), False, 'from tqdm import tqdm\n'), ((6358, 6388), 'cv2.imread', 'cv.imread', (['f"""{folder}{imageA}"""'], {}), "(f'{folder}{imageA}')\n", (6367, 6388), True, 'import cv2 as cv\n'), ((6402, 6432), 'cv2.imread', 'cv.imread', (['f"""{folder}{imageB}"""'], {}), "(f'{folder}{imageB}')\n", (6411, 6432), True, 'import cv2 as cv\n'), ((6446, 6510), 'cv2.resize', 'cv.resize', (['img_a'], {'dsize': '(640, 640)', 'interpolation': 'cv.INTER_CUBIC'}), '(img_a, dsize=(640, 640), interpolation=cv.INTER_CUBIC)\n', (6455, 6510), True, 'import cv2 as cv\n'), ((6524, 6588), 'cv2.resize', 'cv.resize', (['img_b'], {'dsize': '(640, 640)', 'interpolation': 'cv.INTER_CUBIC'}), '(img_b, dsize=(640, 640), interpolation=cv.INTER_CUBIC)\n', (6533, 6588), True, 'import cv2 as cv\n'), ((6604, 6642), 'numpy.concatenate', 'np.concatenate', (['(img_a, img_b)'], {'axis': '(1)'}), '((img_a, img_b), axis=1)\n', (6618, 6642), True, 'import numpy as np\n'), ((6648, 6711), 'cv2.imshow', 'cv.imshow', (['f"""{imageA} and {imageB} has a mse of {err}"""', 'display'], {}), "(f'{imageA} and {imageB} has a mse of {err}', display)\n", (6657, 6711), True, 'import cv2 as cv\n'), ((6717, 6730), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (6727, 6730), True, 'import cv2 as cv\n'), ((6736, 6758), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (6756, 6758), True, 'import cv2 as cv\n'), ((6861, 6894), 'numpy.rot90', 'np.rot90', (['image'], {'k': '(1)', 'axes': '(0, 1)'}), '(image, k=1, axes=(0, 1))\n', (6869, 6894), True, 'import numpy as np\n'), ((7403, 7430), 'os.stat', 'os.stat', (['(directory + imageA)'], {}), '(directory + imageA)\n', (7410, 7430), False, 'import os\n'), ((7456, 7483), 'os.stat', 'os.stat', (['(directory + imageB)'], {}), '(directory + imageB)\n', (7463, 7483), False, 'import os\n'), ((4831, 4852), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (4841, 4852), False, 'import os\n'), ((5035, 5068), 'imghdr.what', 'imghdr.what', (['(directory + filename)'], {}), '(directory + filename)\n', (5046, 5068), False, 'import imghdr\n'), ((4995, 5030), 'os.path.isdir', 'os.path.isdir', (['(directory + filename)'], {}), '(directory + filename)\n', (5008, 5030), False, 'import os\n'), ((5101, 5150), 'numpy.fromfile', 'np.fromfile', (['(directory + filename)'], {'dtype': 'np.uint8'}), '(directory + filename, dtype=np.uint8)\n', (5112, 5150), True, 'import numpy as np\n'), ((5412, 5490), 'cv2.resize', 'cv.resize', (['img'], {'dsize': '(compression, compression)', 'interpolation': 'cv.INTER_CUBIC'}), '(img, dsize=(compression, compression), interpolation=cv.INTER_CUBIC)\n', (5421, 5490), True, 'import cv2 as cv\n'), ((4404, 4439), 'os.remove', 'os.remove', (['f"""{directory}{filename}"""'], {}), "(f'{directory}{filename}')\n", (4413, 4439), False, 'import os\n'), ((5323, 5352), 'numpy.stack', 'np.stack', (['((img,) * 3)'], {'axis': '(-1)'}), '((img,) * 3, axis=-1)\n', (5331, 5352), True, 'import numpy as np\n'), ((5736, 5770), 'numpy.concatenate', 'np.concatenate', (['(imgs_matrix, img)'], {}), '((imgs_matrix, img))\n', (5750, 5770), True, 'import numpy as np\n')]
import numpy as np from functools import reduce from numbers import Number from numpy.linalg import det, pinv, matrix_rank, norm from . import linalg from .util import as_array, as_diag # TODO: Change assertions to exceptions # TODO: Add tests # TODO: Convert to new matrix multiplication operator # TODO: Allow specifying Γ as a vector, constant, or maybe even dict? def mc_return(P, r, Γ): """Compute the expected Monte-Carlo return for the Markov chain defined by `P` with expected reward `r`. This is the result of solving the Bellman equation. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. """ assert linalg.is_stochastic(P) ns = len(P) Γ = as_diag(Γ, ns) I = np.eye(ns) return np.linalg.pinv(I - P @ Γ) @ r # TODO: Allow specifying Γ as a vector, constant, or maybe even dict? def ls_weights(P, r, Γ, X): """Compute the least-squares weights for the MDP given feature matrix `X`. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) value = mc_return(P, r, Γ) dist = linalg.stationary(P) D = np.diag(dist) return np.linalg.pinv(X.T @ D @ X) @ X.T @ D @ value # TODO: Allow specifying Γ as a vector, constant, or maybe even dict? def ls_values(P, r, Γ, X): """Compute the state-values under least-squares function approximation. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. """ ns = len(P) Γ = as_diag(Γ, ns) weights = ls_weights(P, r, Γ, X) return X @ weights # TODO: Allow specifying Γ, Λ, as a vector, constant, or maybe even dict? def td_weights(P, r, Γ, Λ, X): """Compute the weights found at the TD fixed point for the MDP under linear function approximation. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. Notes ----- If the feature matrix `X` is of the same rank as `P`, then the result should be the same as computing the exact value function. If `Λ = diag([1, 1, ..., 1])`, then the result should be the same as computing the weights under least-squares. """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) # Calculate intermediate quantities I = np.eye(ns) dist = linalg.stationary(P) D = np.diag(dist) # Set up and solve the equation r_lm = pinv(I - P @ Γ @ Λ) @ r P_lm = I - pinv(I - P @ Γ @ Λ) @ (I - P @ Γ) A = X.T @ D @ (I - P_lm) @ X b = X.T @ D @ r_lm return np.linalg.pinv(A) @ b # TODO: Allow specifying Γ, Λ, as a vector, constant, or maybe even dict? def td_values(P, r, Γ, Λ, X): """Compute state values found at the TD fixed point for the MDP under linear function approximation. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. """ return X @ td_weights(P, r, Γ, Λ, X) def delta_matrix(R, Γ, v): """Returns the matrix whose (i,j)-th entry represents the expected TD-error for transitioning to state `j` from state `i`. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. R : Matrix[float] The reward matrix, with `R[i,j]` the expected reward for transitioning to state `j` from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. v : The value approximate function, with `v[i]` the value assigned to state `i`. If `v` is the true value function, the expected TD-error will be 0. Returns ------- Δ : Matrix[float] The expected TD-error matrix, with `Δ[i,j]` the expected value of `(R_{t+1} + γ_t+1 v(S_{t+1}) - v(S_{t})` given that state `S_{t} = i`, and state `S_{t+1} = j` """ assert linalg.is_square(R) ns = len(R) Γ = as_diag(Γ, ns) ret = np.zeros((ns, ns)) for i, j in np.ndindex(*ret.shape): ret[i, j] = R[i, j] + Γ[j, j] * v[j] - v[i] return ret def expected_delta(P, R, Γ, v): """The expected TD-error given transitions `P`, reward matrix `R`, discount matrix `Γ`, and values `v`. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. R : Matrix[float] The reward matrix, with `R[i,j]` the expected reward for transitioning to state `j` from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. v : The value approximate function, with `v[i]` the value assigned to state `i`. If `v` is the true value function, the expected TD-error will be 0. Returns ------- δ : Vector[float] The expected TD-error vector, with `δ[i]` the expected value of `(R_{t+1} + γ_t+1 v(S_{t+1}) - v(S_{t})` given that state `S_{t} = i`. """ assert linalg.is_stochastic(P) Δ = delta_matrix(R, Γ, v) return (P * Δ).sum(axis=1) def expected_reward(P, R): """Expected immediate reward given transition matrix `P` and expected reward matrix `R`. """ assert linalg.is_stochastic(P) assert P.shape == R.shape return np.multiply(P, R).sum(axis=1) # TODO: Allow specifying Γ, Λ, as a vector, constant, or maybe even dict? def lambda_return(P, r, Γ, Λ, v_hat): """Compute the expected λ-return for the MDP. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. r : Vector[float]. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Notes ----- If `v_hat` is the "true" value function (i.e., the values found by solving the Bellman equation) then the λ-return will be the same as the Monte-Carlo return (which in expectation *is* the true value function). The λ-return is defined via: G_{t}^{λ} = R_{t+1} + γ_{t+1}( (1-λ_{t+1}) v(S_{t+1}) + λ_{t+1}G_{t+1}^{λ} """ assert linalg.is_stochastic(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) I = np.eye(ns) # Incorporate next-state's value into expected reward r_hat = r + P @ Γ @ (I - Λ) @ v_hat # Solve the Bellman equation return np.linalg.pinv(I - P @ Γ @ Λ) @ r_hat def expected_traces(P, Γ, Λ, X): """The trace matrix for accumulating eligibility traces. That is, a matrix with the same shape as `X`, but where the i-th row corresponds to the expected value of the eligibility trace in the steady-state given that the current state is `i`. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) # Calculate intermediate quantities I = np.eye(ns) dist = linalg.stationary(P) D = np.diag(dist) return (X.T @ D @ pinv(I - P @ Γ @ Λ)).T def etd_weights(P, r, Γ, Λ, X, ivec): """Compute the fixed-point of ETD(λ) by solving its Bellman equation. The weight vector returned corresponds to the asymptotic weights for found by Emphatic TD(λ). Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. ivec : Vector[float] The per-state "interest" vector. For example, `ivec[i]` is the interest allocated to state `i`. """ assert linalg.is_stochastic(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) # compute intermediate quantities (could be more efficient) I = np.eye(ns) di = linalg.stationary(P) * ivec m = pinv(I - Λ @ Γ @ P.T) @ (I - Γ @ P.T) @ di M = np.diag(m) # solve the equation A = X.T @ M @ pinv(I - P @ Γ @ Λ) @ (I - P @ Γ) @ X A_inv = np.linalg.pinv(A) b = X.T @ M @ pinv(I - P @ Γ @ Λ) @ r return np.dot(A_inv, b) def etd_values(P, r, Γ, Λ, X, ivec): """Compute the state-values found by Emphatic TD(λ) by solving the appropriate Bellman equation. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. r : The expected reward vector. Element `r[i]` is defined to be the expected reward over the transitions from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. ivec : Vector[float] The per-state "interest" vector. For example, `ivec[i]` is the interest allocated to state `i`. """ # compute intermediate quantities (could be more efficient) theta = etd_weights(P, Γ, Λ, X, ivec, r) return np.dot(X, theta) def followon(P, Γ, ivec): """Compute the followon trace's expected value for each state.""" assert linalg.is_stochastic(P) ns = len(P) Γ = as_diag(Γ, ns) I = np.eye(ns) di = linalg.stationary(P) * ivec return np.dot(np.linalg.pinv(I - Γ @ P.T), di) @as_array def potential(A, tol=1e-6): """Compute the potential matrix for `A`, which is the sum of the matrix geometric series (also referred to as the "Neumann series". B = \sum_{k=0}^{\infty} A^k = (I - A)^{-1} Parameters ---------- A : Matrix[float] A square matrix such that `(I - A)` is invertible. """ assert linalg.is_square(A) assert isinstance(tol, Number) I = np.eye(len(A)) ret = np.linalg.inv(I - A) ret[np.abs(ret) < tol] = 0 # zero values within tolerance return ret def warp(P, Γ, Λ): """ The matrix which warps the distribution due to gamma and lambda. warp = (I - P_{\pi} \Gamma \Lambda)^{-1} Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning to state `j` from state `i`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. Notes ----- The term "warp matrix" is non-standard terminology, but is somewhat appropriate because it represents the asymptotic result of bootstrapping and discounting in the MDP. The i-th row-sum reflects the influence of the subsequent states on state `i`, while the j-th column sum reflects the influence of state `j` on its successors. """ assert linalg.is_stochastic(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) return potential(P @ Γ @ Λ) def lspi_weights(P, r, Γ, X): """Least-squares policy iteration fixed-point weights. TODO: Need to actually go through the details to make sure this is right. """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) # Calculate intermediate quantities I = np.eye(ns) dist = linalg.stationary(P) D = np.diag(dist) Π = X @ pinv(X.T @ D @ X) @ X.T @ D A = X.T @ ( X - P @ Γ @ Π @ X) b = X.T @ r return pinv(A) @ b def lspi_values(P, r, Γ, X): """Least-squares policy iteration fixed-point values.""" return X @ lspi_weights(P, r, Γ, X) def brm_weights(P, r, Γ, X): """Bellman-residual minimization fixed-point weights. TODO: Need to actually go through the details to make sure this is right """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) # Calculate intermediate quantities I = np.eye(ns) dist = linalg.stationary(P) D = np.diag(dist) Π = X @ pinv(X.T @ D @ X) @ X.T @ D A = (X - P @ Γ @ Π @ X).T @ (X - P @ Γ @ Π @ X) b = (X - P @ Γ @ Π @ X).T @ r return pinv(A) @ b def brm_values(P, r, Γ, X): """Bellman-residual minimization fixed-point values. TODO: Need to go through the math to check that this is right; as it currently is it seems kinda terrible, which surely couldn't be the case given that TD(λ) has existed since the 80s? """ return X @ brm_weights(P, r, Γ, X) ############################################################################### # Variance and Second Moment ############################################################################### # TODO: Allow specifying Γ as a vector, constant, or maybe even dict? def sobel_variance(P, R, Γ): """Compute the variance of the return using Sobel's method for a Markov process. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning from state `i` to state `j` . R : Matrix[float] Element `R[i,j]` is defined to be the expected reward for transitioning from state `i` to state `j`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. TODO ----- This function doesn't work if rewards are a function of state, action, and the successor state. It is easy to fix in a haphazard way, via summing over (s,a,s') for P and R, but I would prefer to handle it via something more generic like numpy's `einsum`. """ assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) I = np.eye(ns) r = (P * R) @ np.ones(ns) v_pi = mc_return(P, r, Γ) # Set up Bellman equation q = -v_pi ** 2 for i in range(ns): for j in range(ns): q[i] += P[i, j] * (R[i, j] + Γ[j, j] * v_pi[j]) ** 2 # Solve Bellman equation return np.linalg.pinv(I - P @ Γ @ Γ) @ q # TODO: Allow specifying Γ as a vector, constant, or maybe even dict? def second_moment(P, R, Γ): """Compute the second moment of the return using the method from White and White for a Markov process. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning from state `i` to state `j` . R : Matrix[float] The expected reward matrix. Element `R[i,j]` is defined to be the expected reward for transitioning from state `i` to state `j`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. TODO ----- This function doesn't work if rewards are a function of state, action, and the successor state. It is easy to fix in a haphazard way, via summing over (s,a,s') for P and R, but I would prefer to handle it via something more generic like numpy's `einsum`. """ assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) I = np.eye(ns) # Compute expected state values r = (P * R) @ np.ones(ns) v_pi = mc_return(P, r, Γ) γ = np.diag(Γ) # Compute reward-like transition matrix R_bar = np.zeros((ns, ns)) for i in range(ns): for j in range(ns): R_bar[i, j] = R[i, j] ** 2 + 2 * (γ[j] * R[i, j] * v_pi[j]) # Set up Bellman equation for second moment r_bar = (P * R_bar) @ np.ones(ns) # Solve the Bellman equation return np.linalg.pinv(I - P @ Γ @ Γ) @ r_bar # TODO: Allow specifying Γ, Λ, as a vector, constant, or maybe even dict? def lambda_second_moment(P, R, Γ, Λ, v_hat): """Compute the second moment of the λ-return using the method from White & White for a Markov process. Parameters ---------- P : Matrix[float] The transition matrix, with `P[i,j]` defined as the probability of transitioning from state `i` to state `j` . R : Matrix[float] The expected reward matrix. Element `R[i,j]` is defined to be the expected reward for transitioning from state `i` to state `j`. Γ : Matrix[float] The state-dependent discount matrix, a diagonal matrix whose (i,i)-th entry is the discount applied to state `i`. All entries should be in the interval [0, 1]. Λ : Matrix[float] The state-dependent bootstrapping matrix, a diagonal matrix whose (i,i)-th entry is the bootstrapping (λ value) for state `i`. All entries should be in the interval [0, 1]. X : Matrix The feature matrix, whose rows correspond to the feature representation for each state. For example, `X[i]` provides the features for state `i`. Notes ----- Because we are using the λ-return, the choice of `v_hat` influences the second moment. The λ-return is defined via: G_{t}^{λ} = R_{t+1} + γ_{t+1}( (1-λ_{t+1}) v(S_{t+1}) + λ_{t+1}G_{t+1}^{λ} TODO ----- This function doesn't work if rewards are a function of state, action, and the successor state. It is easy to fix in a haphazard way, via summing over (s,a,s') for P and R, but I would prefer to handle it via something more generic like numpy's `einsum`. """ assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) I = np.eye(ns) # Expected immediate reward r = (P * R) @ np.ones(ns) # Lambda return may be different from approximate lambda return v_lm = lambda_return(P, r, Γ, Λ, v_hat) # Get per-state discount and bootstrapping γ = np.diag(Γ) λ = np.diag(Λ) # Compute reward-like transition matrix R_bar = np.zeros((ns, ns)) for i in range(ns): for j in range(ns): R_bar[i, j] = ( R[i, j] ** 2 + (γ[j] * (1 - λ[j]) * v_hat[j]) ** 2 + 2 * (γ[j] * (1 - λ[j]) * R[i, j] * v_hat[j]) + 2 * (γ[j] * λ[j] * R[i, j] * v_lm[j]) + 2 * ((γ[j] ** 2) * λ[j] * (1 - λ[j]) * (v_hat[j] * v_lm[j])) ) # Set up Bellman equation for second moment r_bar = (P * R_bar) @ np.ones(ns) # Solve the Bellman equation return pinv(I - P @ Γ @ Γ @ Λ @ Λ) @ r_bar ############################################################################### # Objective/Error Functions # # TODO: Objective function for the λ-return ############################################################################### def square_error(P, R, Γ, v): """Square error (SE), the combination of squared bias and the variance.""" bias = value_error(P, R, Γ, v) variance = sobel_variance(P, R, Γ) return variance + bias ** 2 def value_error(P, R, Γ, v): """Value error (VE), the difference between the true value function and the one supplied AKA the bias. """ assert linalg.is_ergodic(P) ns = len(P) Γ = as_diag(Γ, ns) r = (P * R).sum(axis=1) v_pi = mc_return(P, r, Γ) return v_pi - v def projection_error(P, R, Γ, X): """Projection error between the true value and the approximation subspace. (that is., `v_pi - Π v_pi`) """ assert linalg.is_ergodic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) r = (P * R).sum(axis=1) v_pi = mc_return(P, r, Γ) d_pi = linalg.stationary(P) D = np.diag(d_pi) Π = X @ np.linalg.pinv(X.T @ D @ X) @ X.T @ D return v_pi - Π @ v_pi def bellman_error(P, R, Γ, v): """Bellman error (BE), AKA the expected Bellman residual, AKA the expected temporal difference error. """ assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) Δ = delta_matrix(R, Γ, v) return (P * Δ) @ np.ones(ns) def projected_bellman_error(P, R, Γ, X, v): """Projected Bellman error.""" assert linalg.is_ergodic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) r = (P * R).sum(axis=1) d_pi = linalg.stationary(P) D = np.diag(d_pi) Π = X @ np.linalg.pinv(X.T @ D @ X) @ X.T @ D # Bellman operator Tv = r + P @ Γ @ v return v - Π @ Tv def square_td_error(P, R, Γ, v): """Squared temporal difference error (STDE).""" assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) Δ = delta_matrix(R, Γ, v) return (P * Δ ** 2) @ np.ones(ns) def expected_update(P, R, Γ, X, v): """Expected update.""" assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) d_pi = linalg.stationary(P) D = np.diag(d_pi) δ = expected_delta(P, R, Γ, v) return X.T @ D @ δ # ----------------------------------------------------------------------------- # With eligibility traces / λ-return # ----------------------------------------------------------------------------- def lambda_expected_update(P, R, Γ, Λ, X, v): """Expected update with accumulating eligibility traces.""" assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) E = expected_traces(P, Γ, Λ, X) δ = expected_delta(P, R, Γ, v) return E.T @ δ def lambda_projected_bellman_error(P, R, Γ, Λ, X, v): """Projection error with accumulating eligibility traces.""" assert linalg.is_stochastic(P) assert P.shape == R.shape ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns) r = (P * R).sum(axis=1) # Projection operator d_pi = linalg.stationary(P) D = np.diag(d_pi) Π = X @ np.linalg.pinv(X.T @ D @ X) @ X.T @ D # λ-Bellman operator P_lm = I - pinv(I - P @ Γ @ Λ) @ (I - P @ Γ) Tv_lm = pinv(I - P @ Γ @ Λ) @ r + P_lm @ v return Π @ Tv - v # ----------------------------------------------------------------------------- # Weighted/normed versions of the errors # ----------------------------------------------------------------------------- def mse(P, R, Γ, v): """Mean-squared error (MSE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * square_error(P, R, Γ, v)) def msve(P, R, Γ, v): """Mean-squared value error (MSVE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * value_error(P, R, Γ, v) ** 2) def msbe(P, R, Γ, v): """Mean squared Bellman error (MSBE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * bellman_error(P, R, Γ, v) ** 2) def mspbe(P, R, Γ, X, v): """Mean squared projected Bellman error (MSPBE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * projected_bellman_error(P, R, Γ, X, v) ** 2) def mstde(P, R, Γ, v): """Mean squared temporal difference error (MSTDE).""" assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) return np.sum(d_pi * square_td_error(P, R, Γ, v)) def neu(P, R, Γ, X, v): """Norm of the expected update (NEU). NEU(v) = 0 is the fixed-point of TD(0). """ assert linalg.is_ergodic(P) d_pi = linalg.stationary(P) EU = expected_update(P, R, Γ, X, v) return EU.T @ EU
[ "numpy.ndindex", "numpy.multiply", "numpy.abs", "numpy.zeros", "numpy.ones", "numpy.linalg.inv", "numpy.dot", "numpy.eye", "numpy.linalg.pinv", "numpy.diag" ]
[((1180, 1190), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (1186, 1190), True, 'import numpy as np\n'), ((2325, 2338), 'numpy.diag', 'np.diag', (['dist'], {}), '(dist)\n', (2332, 2338), True, 'import numpy as np\n'), ((5014, 5024), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (5020, 5024), True, 'import numpy as np\n'), ((5065, 5078), 'numpy.diag', 'np.diag', (['dist'], {}), '(dist)\n', (5072, 5078), True, 'import numpy as np\n'), ((7647, 7665), 'numpy.zeros', 'np.zeros', (['(ns, ns)'], {}), '((ns, ns))\n', (7655, 7665), True, 'import numpy as np\n'), ((7682, 7704), 'numpy.ndindex', 'np.ndindex', (['*ret.shape'], {}), '(*ret.shape)\n', (7692, 7704), True, 'import numpy as np\n'), ((10700, 10710), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (10706, 10710), True, 'import numpy as np\n'), ((12176, 12186), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (12182, 12186), True, 'import numpy as np\n'), ((12227, 12240), 'numpy.diag', 'np.diag', (['dist'], {}), '(dist)\n', (12234, 12240), True, 'import numpy as np\n'), ((13746, 13756), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (13752, 13756), True, 'import numpy as np\n'), ((13853, 13863), 'numpy.diag', 'np.diag', (['m'], {}), '(m)\n', (13860, 13863), True, 'import numpy as np\n'), ((13958, 13975), 'numpy.linalg.pinv', 'np.linalg.pinv', (['A'], {}), '(A)\n', (13972, 13975), True, 'import numpy as np\n'), ((14029, 14045), 'numpy.dot', 'np.dot', (['A_inv', 'b'], {}), '(A_inv, b)\n', (14035, 14045), True, 'import numpy as np\n'), ((15384, 15400), 'numpy.dot', 'np.dot', (['X', 'theta'], {}), '(X, theta)\n', (15390, 15400), True, 'import numpy as np\n'), ((15582, 15592), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (15588, 15592), True, 'import numpy as np\n'), ((16132, 16152), 'numpy.linalg.inv', 'np.linalg.inv', (['(I - A)'], {}), '(I - A)\n', (16145, 16152), True, 'import numpy as np\n'), ((17864, 17874), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (17870, 17874), True, 'import numpy as np\n'), ((17915, 17928), 'numpy.diag', 'np.diag', (['dist'], {}), '(dist)\n', (17922, 17928), True, 'import numpy as np\n'), ((18546, 18556), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (18552, 18556), True, 'import numpy as np\n'), ((18597, 18610), 'numpy.diag', 'np.diag', (['dist'], {}), '(dist)\n', (18604, 18610), True, 'import numpy as np\n'), ((20429, 20439), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (20435, 20439), True, 'import numpy as np\n'), ((21928, 21938), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (21934, 21938), True, 'import numpy as np\n'), ((22045, 22055), 'numpy.diag', 'np.diag', (['Γ'], {}), '(Γ)\n', (22052, 22055), True, 'import numpy as np\n'), ((22112, 22130), 'numpy.zeros', 'np.zeros', (['(ns, ns)'], {}), '((ns, ns))\n', (22120, 22130), True, 'import numpy as np\n'), ((24295, 24305), 'numpy.eye', 'np.eye', (['ns'], {}), '(ns)\n', (24301, 24305), True, 'import numpy as np\n'), ((24537, 24547), 'numpy.diag', 'np.diag', (['Γ'], {}), '(Γ)\n', (24544, 24547), True, 'import numpy as np\n'), ((24556, 24566), 'numpy.diag', 'np.diag', (['Λ'], {}), '(Λ)\n', (24563, 24566), True, 'import numpy as np\n'), ((24623, 24641), 'numpy.zeros', 'np.zeros', (['(ns, ns)'], {}), '((ns, ns))\n', (24631, 24641), True, 'import numpy as np\n'), ((26290, 26303), 'numpy.diag', 'np.diag', (['d_pi'], {}), '(d_pi)\n', (26297, 26303), True, 'import numpy as np\n'), ((26949, 26962), 'numpy.diag', 'np.diag', (['d_pi'], {}), '(d_pi)\n', (26956, 26962), True, 'import numpy as np\n'), ((27550, 27563), 'numpy.diag', 'np.diag', (['d_pi'], {}), '(d_pi)\n', (27557, 27563), True, 'import numpy as np\n'), ((28490, 28503), 'numpy.diag', 'np.diag', (['d_pi'], {}), '(d_pi)\n', (28497, 28503), True, 'import numpy as np\n'), ((1202, 1227), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(I - P @ Γ)'], {}), '(I - P @ Γ)\n', (1216, 1227), True, 'import numpy as np\n'), ((5127, 5146), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (5131, 5146), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((5267, 5284), 'numpy.linalg.pinv', 'np.linalg.pinv', (['A'], {}), '(A)\n', (5281, 5284), True, 'import numpy as np\n'), ((10853, 10882), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (10867, 10882), True, 'import numpy as np\n'), ((15648, 15675), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(I - Γ @ P.T)'], {}), '(I - Γ @ P.T)\n', (15662, 15675), True, 'import numpy as np\n'), ((18032, 18039), 'numpy.linalg.pinv', 'pinv', (['A'], {}), '(A)\n', (18036, 18039), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((18749, 18756), 'numpy.linalg.pinv', 'pinv', (['A'], {}), '(A)\n', (18753, 18756), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((20458, 20469), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (20465, 20469), True, 'import numpy as np\n'), ((20707, 20736), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(I - P @ Γ @ Γ)'], {}), '(I - P @ Γ @ Γ)\n', (20721, 20736), True, 'import numpy as np\n'), ((21994, 22005), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (22001, 22005), True, 'import numpy as np\n'), ((22329, 22340), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (22336, 22340), True, 'import numpy as np\n'), ((22386, 22415), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(I - P @ Γ @ Γ)'], {}), '(I - P @ Γ @ Γ)\n', (22400, 22415), True, 'import numpy as np\n'), ((24356, 24367), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (24363, 24367), True, 'import numpy as np\n'), ((25091, 25102), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (25098, 25102), True, 'import numpy as np\n'), ((25148, 25175), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Γ @ Λ @ Λ)'], {}), '(I - P @ Γ @ Γ @ Λ @ Λ)\n', (25152, 25175), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((26688, 26699), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (26695, 26699), True, 'import numpy as np\n'), ((27330, 27341), 'numpy.ones', 'np.ones', (['ns'], {}), '(ns)\n', (27337, 27341), True, 'import numpy as np\n'), ((5166, 5185), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (5170, 5185), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((9115, 9132), 'numpy.multiply', 'np.multiply', (['P', 'R'], {}), '(P, R)\n', (9126, 9132), True, 'import numpy as np\n'), ((12263, 12282), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (12267, 12282), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((13802, 13823), 'numpy.linalg.pinv', 'pinv', (['(I - Λ @ Γ @ P.T)'], {}), '(I - Λ @ Γ @ P.T)\n', (13806, 13823), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((13994, 14013), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (13998, 14013), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((16161, 16172), 'numpy.abs', 'np.abs', (['ret'], {}), '(ret)\n', (16167, 16172), True, 'import numpy as np\n'), ((28595, 28614), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (28599, 28614), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((28641, 28660), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (28645, 28660), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((2350, 2377), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (2364, 2377), True, 'import numpy as np\n'), ((13908, 13927), 'numpy.linalg.pinv', 'pinv', (['(I - P @ Γ @ Λ)'], {}), '(I - P @ Γ @ Λ)\n', (13912, 13927), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((17942, 17959), 'numpy.linalg.pinv', 'pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (17946, 17959), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((18624, 18641), 'numpy.linalg.pinv', 'pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (18628, 18641), False, 'from numpy.linalg import det, pinv, matrix_rank, norm\n'), ((26317, 26344), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (26331, 26344), True, 'import numpy as np\n'), ((26976, 27003), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (26990, 27003), True, 'import numpy as np\n'), ((28517, 28544), 'numpy.linalg.pinv', 'np.linalg.pinv', (['(X.T @ D @ X)'], {}), '(X.T @ D @ X)\n', (28531, 28544), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # # Copyright (c) 2021 Krai Ltd. # # SPDX-License-Identifier: BSD-3-Clause. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import json import os import re import sys import numpy as np import torch from transformers import BertConfig, BertTokenizer, BertForQuestionAnswering import tensorflow as tf import onnx_graphsurgeon as gs import onnx from collections import OrderedDict with open("./downloaded/bert_config.json") as f: config = json.load(f) # construct the bert config config = BertConfig( attention_probs_dropout_prob=config["attention_probs_dropout_prob"], hidden_act=config["hidden_act"], hidden_dropout_prob=config["hidden_dropout_prob"], hidden_size=config["hidden_size"], initializer_range=config["initializer_range"], intermediate_size=config["intermediate_size"], max_position_embeddings=config["max_position_embeddings"], num_attention_heads=config["num_attention_heads"], num_hidden_layers=config["num_hidden_layers"], type_vocab_size=config["type_vocab_size"], vocab_size=config["vocab_size"]) model = BertForQuestionAnswering(config) model.classifier = model.qa_outputs # This part is copied from HuggingFace Transformers with a fix to bypass an error init_vars = tf.train.list_variables("./downloaded/model.ckpt-5474") names = [] arrays = [] for name, shape in init_vars: # print("Loading TF weight {} with shape {}".format(name, shape)) array = tf.train.load_variable("./downloaded/model.ckpt-5474", name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any(n in ["adam_v", "adam_m", "global_step"] for n in name): print("Skipping {}".format("/".join(name))) continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "output_weights": pointer = getattr(pointer, "weight") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") # This line is causing the issue else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: print("Skipping {}".format("/".join(name))) continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: assert pointer.shape == array.shape except AssertionError as e: e.args += (pointer.shape, array.shape) raise print("Initialize PyTorch weight {}".format(name)) pointer.data = torch.from_numpy(array) model.qa_outputs = model.classifier del model.classifier tokenizer = BertTokenizer.from_pretrained("bert-large-uncased-whole-word-masking-finetuned-squad") model = model.eval() dummy_input = torch.ones((1, 384), dtype=torch.int64) torch.onnx.export( model, (dummy_input, dummy_input, dummy_input), "./intermediate_model.onnx", verbose=True, input_names = ["input_ids", "input_mask", "segment_ids"], output_names = ["output_start_logits", "output_end_logits"], opset_version=11, dynamic_axes=({"input_ids": {0: "batch_size", 1: "seg_length"}, "input_mask": {0: "batch_size", 1: "seg_length"}, "segment_ids": {0: "batch_size", 1: "seg_length"}, "output_start_logits": {0: "batch_size", 1: "seg_length"}, "output_end_logits": {0: "batch_size", 1: "seg_length"}}) ) def remove_node(node): for inp in node.inputs: inp.outputs.clear() # Disconnet input nodes of all output tensors for out in node.outputs: out.inputs.clear() @gs.Graph.register() def add_2d_mask(self, inputs, outputs): inp1 = inputs[0] inp1.shape = ['batch_size', 'seg_length', 'seg_length'] inp1.dtype = np.bool # Disconnect output nodes of all input tensors for inp in inputs: inp.outputs.clear() # Disconnet input nodes of all output tensors for out in outputs: for out2 in out.outputs: output_copy = list(out2.outputs) remove_node(out2) remove_node(out) # Insert the new node. return self.layer(op="Unsqueeze", name='', attrs=OrderedDict([('axes', [1])]), inputs=[inp1], outputs=output_copy) @gs.Graph.register() def replace_with_comp_mask(self, inputs, outputs, input_mask_node, input_ids_node): input_mask_node.shape = ['batch_size', 8] print(type(input_mask_node.dtype)) input_mask_node.dtype = np.dtype('int64') print(type(input_mask_node.dtype)) for out in input_mask_node.outputs: print('removing: ', out) remove_node(out) # Disconnect output nodes of all input tensors for inp in inputs: inp.outputs.clear() # Disconnet input nodes of all output tensors output_copy = list(outputs) for out in outputs: print('removing: ', out) out.inputs.clear() # Insert the new node. inputsTrans = self.layer(op="Transpose", name='', inputs=[input_mask_node], outputs=['node0']) # cumulativeIncl = OnnxCumSum('inputs', np.array(1)) cumulativeIncl = self.layer(op="CumSum", name='', inputs=[*inputsTrans, np.array([0], dtype=np.int32)], outputs=['node1']) # cumulativeExcl = OnnxCumSum('inputs', np.array(1), exclusive=True) cumulativeExcl = self.layer(op="CumSum", name='', attrs=OrderedDict([('exclusive', True)]), inputs=[*inputsTrans, np.array([0], dtype=np.int32)], outputs=['node2']) # cumulativeIncl = OnnxUnsqueeze(cumulativeIncl, np.array(1)) cumulativeIncl = self.layer(op="Unsqueeze", name='', inputs=[*cumulativeIncl], attrs=OrderedDict([('axes', [0])]), outputs=['node3']) # cumulativeExcl = OnnxUnsqueeze(cumulativeExcl, np.array(1)) cumulativeExcl = self.layer(op="Unsqueeze", name='', inputs=[*cumulativeExcl], attrs=OrderedDict([('axes', [0])]), outputs=['node4']) # cumulativeInclReshaped = OnnxTranspose(cumulativeIncl, perm=np.array([0, 2, 1])) cumulativeInclReshaped = self.layer(op="Transpose", name='', inputs=[*cumulativeIncl], outputs=['node5']) # cumulativeExclReshaped = OnnxTranspose(cumulativeExcl, perm=np.array([0, 2, 1])) cumulativeExclReshaped = self.layer(op="Transpose", name='', inputs=[*cumulativeExcl], outputs=['node6']) # shapeNode = OnnxShape(input_ids) shapeNode = self.layer(op="Shape", name='', inputs=[input_ids_node], outputs=['node7']) # gatherNode = OnnxGather(shapeNode, np.array(1)); gatherNode = self.layer(op='Gather', name='', inputs=[*shapeNode, np.array(1)], outputs=['node8']) # rangeNode = OnnxRange(np.array(0), gatherNode, np.array(1)) rangeNode = self.layer(op='Range', name='', inputs=[np.array(0), *gatherNode, np.array(1)], outputs=['node9']) # lessnode = OnnxLess(rangeNode, cumulativeInclReshaped) lessNode = self.layer(op='Less', name='', inputs=[*rangeNode, *cumulativeInclReshaped], outputs=['node10']) # greaternode = OnnxGreaterOrEqual(rangeNode, cumulativeExclReshaped) greaterNode = self.layer(op='Less', name='', inputs=[*rangeNode, *cumulativeExclReshaped], outputs=['node11']) greaterNode = self.layer(op='Not', name='', inputs=[*greaterNode], outputs=['node12']) # node = OnnxAnd(lessnode, greaternode) node = self.layer(op='And', name='', inputs=[*lessNode, *greaterNode], outputs=['node13']) # node = OnnxCast(node, to=TensorProto.INT32) node = self.layer(op='Cast', name='', inputs=[*node], attrs=OrderedDict([('to', 1)]), outputs=['node14']) # node = OnnxMatMul(OnnxTranspose(node, perm=np.array([0, 2, 1])), node) print('Copy:', output_copy) transNode = self.layer(op='Transpose', name='', inputs=[*node], outputs=['node15'], attrs=OrderedDict([('perm', [0, 2, 1])])) node = self.layer(op='MatMul', name='', inputs=[*transNode, *node], outputs=output_copy) return node def add_position_input(graphPacked): collectGatherNodes = [node for node in graph.nodes if node.op == "Gather"] for gather in collectGatherNodes: if gather.inputs[0].name == "bert.embeddings.position_embeddings.weight": positionInput = gs.Variable(name="input_position_ids", dtype=np.int64, shape=("batch_size", 'seg_length')) gather.inputs[1] = positionInput graphPacked.inputs.append(positionInput) return graphPacked modelFloat = onnx.load("./intermediate_model.onnx") graph = gs.import_onnx(modelFloat) for node in graph.nodes: if len(node.inputs) > 0 and node.inputs[0].name == "input_mask": graph.add_2d_mask(node.inputs, node.outputs) break graph = add_position_input(graph) graph.cleanup().toposort() os.remove("./intermediate_model.onnx") onnx.save(gs.export_onnx(graph), "./intermediate_model.onnx") modelFloat = onnx.load("./intermediate_model.onnx") graph = gs.import_onnx(modelFloat) # print(graph) input_mask_node = None input_ids_node = None for node in graph.nodes: if len(node.inputs) > 0 and node.inputs[0].name == 'input_mask': print(node.inputs[0]) input_mask_node = node.inputs[0] if len(node.inputs) > 1 and node.inputs[1].name == 'input_ids': print(node.inputs[1]) input_ids_node = node.inputs[1] if input_mask_node and input_ids_node: break for node in graph.nodes: if len(node.outputs) > 0 and node.outputs[0].name == "398": print(node) # print(node.attrs) graph.replace_with_comp_mask(node.inputs, node.outputs, input_mask_node, input_ids_node) break graph = graph.cleanup().toposort() print('done') for node in graph.nodes: if node.outputs[0].name in ['396', '397', '400', '491'] or 'node8' in node.outputs[0].name: print(node) if len(node.inputs) > 0 and node.inputs[0].name == "input_mask": print(node) # print(graph) os.remove("./intermediate_model.onnx") onnx.save(gs.export_onnx(graph), "./model.onnx")
[ "os.remove", "onnx_graphsurgeon.Variable", "onnx_graphsurgeon.export_onnx", "torch.ones", "re.fullmatch", "numpy.transpose", "onnx_graphsurgeon.Graph.register", "transformers.BertForQuestionAnswering", "onnx.load", "re.split", "tensorflow.train.list_variables", "transformers.BertConfig", "tr...
[((1952, 2509), 'transformers.BertConfig', 'BertConfig', ([], {'attention_probs_dropout_prob': "config['attention_probs_dropout_prob']", 'hidden_act': "config['hidden_act']", 'hidden_dropout_prob': "config['hidden_dropout_prob']", 'hidden_size': "config['hidden_size']", 'initializer_range': "config['initializer_range']", 'intermediate_size': "config['intermediate_size']", 'max_position_embeddings': "config['max_position_embeddings']", 'num_attention_heads': "config['num_attention_heads']", 'num_hidden_layers': "config['num_hidden_layers']", 'type_vocab_size': "config['type_vocab_size']", 'vocab_size': "config['vocab_size']"}), "(attention_probs_dropout_prob=config[\n 'attention_probs_dropout_prob'], hidden_act=config['hidden_act'],\n hidden_dropout_prob=config['hidden_dropout_prob'], hidden_size=config[\n 'hidden_size'], initializer_range=config['initializer_range'],\n intermediate_size=config['intermediate_size'], max_position_embeddings=\n config['max_position_embeddings'], num_attention_heads=config[\n 'num_attention_heads'], num_hidden_layers=config['num_hidden_layers'],\n type_vocab_size=config['type_vocab_size'], vocab_size=config['vocab_size'])\n", (1962, 2509), False, 'from transformers import BertConfig, BertTokenizer, BertForQuestionAnswering\n'), ((2533, 2565), 'transformers.BertForQuestionAnswering', 'BertForQuestionAnswering', (['config'], {}), '(config)\n', (2557, 2565), False, 'from transformers import BertConfig, BertTokenizer, BertForQuestionAnswering\n'), ((2697, 2752), 'tensorflow.train.list_variables', 'tf.train.list_variables', (['"""./downloaded/model.ckpt-5474"""'], {}), "('./downloaded/model.ckpt-5474')\n", (2720, 2752), True, 'import tensorflow as tf\n'), ((4790, 4881), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-large-uncased-whole-word-masking-finetuned-squad"""'], {}), "(\n 'bert-large-uncased-whole-word-masking-finetuned-squad')\n", (4819, 4881), False, 'from transformers import BertConfig, BertTokenizer, BertForQuestionAnswering\n'), ((4912, 4951), 'torch.ones', 'torch.ones', (['(1, 384)'], {'dtype': 'torch.int64'}), '((1, 384), dtype=torch.int64)\n', (4922, 4951), False, 'import torch\n'), ((4953, 5523), 'torch.onnx.export', 'torch.onnx.export', (['model', '(dummy_input, dummy_input, dummy_input)', '"""./intermediate_model.onnx"""'], {'verbose': '(True)', 'input_names': "['input_ids', 'input_mask', 'segment_ids']", 'output_names': "['output_start_logits', 'output_end_logits']", 'opset_version': '(11)', 'dynamic_axes': "{'input_ids': {(0): 'batch_size', (1): 'seg_length'}, 'input_mask': {(0):\n 'batch_size', (1): 'seg_length'}, 'segment_ids': {(0): 'batch_size', (1\n ): 'seg_length'}, 'output_start_logits': {(0): 'batch_size', (1):\n 'seg_length'}, 'output_end_logits': {(0): 'batch_size', (1): 'seg_length'}}"}), "(model, (dummy_input, dummy_input, dummy_input),\n './intermediate_model.onnx', verbose=True, input_names=['input_ids',\n 'input_mask', 'segment_ids'], output_names=['output_start_logits',\n 'output_end_logits'], opset_version=11, dynamic_axes={'input_ids': {(0):\n 'batch_size', (1): 'seg_length'}, 'input_mask': {(0): 'batch_size', (1):\n 'seg_length'}, 'segment_ids': {(0): 'batch_size', (1): 'seg_length'},\n 'output_start_logits': {(0): 'batch_size', (1): 'seg_length'},\n 'output_end_logits': {(0): 'batch_size', (1): 'seg_length'}})\n", (4970, 5523), False, 'import torch\n'), ((5744, 5763), 'onnx_graphsurgeon.Graph.register', 'gs.Graph.register', ([], {}), '()\n', (5761, 5763), True, 'import onnx_graphsurgeon as gs\n'), ((6372, 6391), 'onnx_graphsurgeon.Graph.register', 'gs.Graph.register', ([], {}), '()\n', (6389, 6391), True, 'import onnx_graphsurgeon as gs\n'), ((10461, 10499), 'onnx.load', 'onnx.load', (['"""./intermediate_model.onnx"""'], {}), "('./intermediate_model.onnx')\n", (10470, 10499), False, 'import onnx\n'), ((10508, 10534), 'onnx_graphsurgeon.import_onnx', 'gs.import_onnx', (['modelFloat'], {}), '(modelFloat)\n', (10522, 10534), True, 'import onnx_graphsurgeon as gs\n'), ((10759, 10797), 'os.remove', 'os.remove', (['"""./intermediate_model.onnx"""'], {}), "('./intermediate_model.onnx')\n", (10768, 10797), False, 'import os\n'), ((10875, 10913), 'onnx.load', 'onnx.load', (['"""./intermediate_model.onnx"""'], {}), "('./intermediate_model.onnx')\n", (10884, 10913), False, 'import onnx\n'), ((10922, 10948), 'onnx_graphsurgeon.import_onnx', 'gs.import_onnx', (['modelFloat'], {}), '(modelFloat)\n', (10936, 10948), True, 'import onnx_graphsurgeon as gs\n'), ((11923, 11961), 'os.remove', 'os.remove', (['"""./intermediate_model.onnx"""'], {}), "('./intermediate_model.onnx')\n", (11932, 11961), False, 'import os\n'), ((1901, 1913), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1910, 1913), False, 'import json\n'), ((2888, 2948), 'tensorflow.train.load_variable', 'tf.train.load_variable', (['"""./downloaded/model.ckpt-5474"""', 'name'], {}), "('./downloaded/model.ckpt-5474', name)\n", (2910, 2948), True, 'import tensorflow as tf\n'), ((4695, 4718), 'torch.from_numpy', 'torch.from_numpy', (['array'], {}), '(array)\n', (4711, 4718), False, 'import torch\n'), ((6589, 6606), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (6597, 6606), True, 'import numpy as np\n'), ((10809, 10830), 'onnx_graphsurgeon.export_onnx', 'gs.export_onnx', (['graph'], {}), '(graph)\n', (10823, 10830), True, 'import onnx_graphsurgeon as gs\n'), ((11973, 11994), 'onnx_graphsurgeon.export_onnx', 'gs.export_onnx', (['graph'], {}), '(graph)\n', (11987, 11994), True, 'import onnx_graphsurgeon as gs\n'), ((3405, 3443), 're.fullmatch', 're.fullmatch', (['"""[A-Za-z]+_\\\\d+"""', 'm_name'], {}), "('[A-Za-z]+_\\\\d+', m_name)\n", (3417, 3443), False, 'import re\n'), ((3471, 3498), 're.split', 're.split', (['"""_(\\\\d+)"""', 'm_name'], {}), "('_(\\\\d+)', m_name)\n", (3479, 3498), False, 'import re\n'), ((4455, 4474), 'numpy.transpose', 'np.transpose', (['array'], {}), '(array)\n', (4467, 4474), True, 'import numpy as np\n'), ((6304, 6332), 'collections.OrderedDict', 'OrderedDict', (["[('axes', [1])]"], {}), "([('axes', [1])])\n", (6315, 6332), False, 'from collections import OrderedDict\n'), ((7470, 7504), 'collections.OrderedDict', 'OrderedDict', (["[('exclusive', True)]"], {}), "([('exclusive', True)])\n", (7481, 7504), False, 'from collections import OrderedDict\n'), ((7735, 7763), 'collections.OrderedDict', 'OrderedDict', (["[('axes', [0])]"], {}), "([('axes', [0])])\n", (7746, 7763), False, 'from collections import OrderedDict\n'), ((7939, 7967), 'collections.OrderedDict', 'OrderedDict', (["[('axes', [0])]"], {}), "([('axes', [0])])\n", (7950, 7967), False, 'from collections import OrderedDict\n'), ((9570, 9594), 'collections.OrderedDict', 'OrderedDict', (["[('to', 1)]"], {}), "([('to', 1)])\n", (9581, 9594), False, 'from collections import OrderedDict\n'), ((9819, 9853), 'collections.OrderedDict', 'OrderedDict', (["[('perm', [0, 2, 1])]"], {}), "([('perm', [0, 2, 1])])\n", (9830, 9853), False, 'from collections import OrderedDict\n'), ((10230, 10324), 'onnx_graphsurgeon.Variable', 'gs.Variable', ([], {'name': '"""input_position_ids"""', 'dtype': 'np.int64', 'shape': "('batch_size', 'seg_length')"}), "(name='input_position_ids', dtype=np.int64, shape=('batch_size',\n 'seg_length'))\n", (10241, 10324), True, 'import onnx_graphsurgeon as gs\n'), ((7286, 7315), 'numpy.array', 'np.array', (['[0]'], {'dtype': 'np.int32'}), '([0], dtype=np.int32)\n', (7294, 7315), True, 'import numpy as np\n'), ((7528, 7557), 'numpy.array', 'np.array', (['[0]'], {'dtype': 'np.int32'}), '([0], dtype=np.int32)\n', (7536, 7557), True, 'import numpy as np\n'), ((8645, 8656), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (8653, 8656), True, 'import numpy as np\n'), ((8800, 8811), 'numpy.array', 'np.array', (['(0)'], {}), '(0)\n', (8808, 8811), True, 'import numpy as np\n'), ((8826, 8837), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (8834, 8837), True, 'import numpy as np\n')]
""" About: Preprocess with pytorch and Spacy """ import torch import torch.nn as nn import torch.optim as optim from torchtext.legacy.datasets import Multi30k from torchtext.legacy.data import Field, BucketIterator from torchtext.data.utils import get_tokenizer import spacy import numpy as np import random import math import de_core_news_sm, en_core_web_sm # set random seeds for deterministic results SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True # create a tokenizers. """ Tokenizer: - A tokenizer is used to turn a string containing a sentence into a list of individual tokens that make up that string e.g. "good morning!" becomes ["good", "morning", "!"]. SpaCy: - spacy has mode for each languae which need to be loaded so we can access the tokenizer of each model """ # tokenize_de = get_tokenizer("spacy", language="de") # tokenize_en = get_tokenizer("spacy", language="en") spacy_de = spacy.load("de_core_news_sm") spacy_en = spacy.load("en_core_web_sm") # create a tokenizer function which is passed to torchtext and will take in the sentence as a string and reutnr the sentence as a list of tokens def tokenize_de(text): """ Tokenize German text from a string into list of token and reverse it """ arr = [] for tok in spacy_de.tokenizer(text): arr.append(tok.text) return arr[::-1] def tokenize_en(text): """ Tokenizes English text from a string into list of token and reverse it """ # arr = [] # for tok in spacy_en.tokenizer(text): # arr.append(tok.text) # return arr[::-1] return [tok.text for tok in spacy_en.tokenizer(text)] # set the tokenized are guments to the correct tokenization function for each, with German being source filed and english being the target field. # the field also appends the start of sequence and end of sequence tokens via init_token and eos_token argument, and converts all words to lowercase SRC = Field(tokenize=tokenize_de, init_token="<sos>", eos_token="<eos>", lower=True) TRG = Field(tokenize=tokenize_en, init_token="<sos>", eos_token="<eos>", lower=True) # download dataset: 30k parallel Enlish, German, French sentense with 12 words per tencese train_data, valid_data, test_data = Multi30k.splits( exts=(".de", ".en"), fields=(SRC, TRG) ) # samples print(f"Number of training examples: {len(train_data.examples)}") print(f"Number of validation examples: {len(valid_data.examples)}") print(f"Number of testing examples: {len(test_data.examples)}") print(vars(train_data.examples[0])) # have to use vars to print out values # build the vocab for the source and target lanauges. The vocab is used to associate each unique token with an index (an integer) # the vocab of the source and target lanauges are distince # using min_freq, we only allow tokens that appear atleast 2 times to appear in out vocab. Tokens that appear only once are converted into unknown token # It is important to note that our vocab should be built from the training set and not the validation set. # This prevent info leakage into our model giving us artifically inflated test scroe SRC.build_vocab(train_data, min_freq=2) TRG.build_vocab(train_data, min_freq=2) print(f"Unique tokens in source/de vocab: {len(SRC.vocab)}") print(f"Unique tokens in target/en vocab: {len(TRG.vocab)}") # create an iterators: convert tokens into sequences of corresponding indexes using the vocab # note that when we get a batch of exmaples using an iterator, we need to make sure that all of the source sentences are padded to the same length, same for the target sentences device = torch.device("cuda" if torch.cuda.is_available() else "cpu") BATCH_SIZE = 128 # these can be iterated on to return a batch of data which will have a src attribute # bucketIterator is better than iterator because it can minimizes the amount of padding in both the source and target sentences train_iterator, valid_iterator, test_iterator = BucketIterator.splits( (train_data, valid_data, test_data), batch_size=BATCH_SIZE, device=device ) # print(f"Testing {train_iterator}") def test_preprocess(): """ Tests file """ print("Running") if __name__ == "__main__": test_preprocess()
[ "numpy.random.seed", "torch.manual_seed", "torch.cuda.manual_seed", "torchtext.legacy.data.BucketIterator.splits", "torchtext.legacy.datasets.Multi30k.splits", "spacy.load", "random.seed", "torch.cuda.is_available", "torchtext.legacy.data.Field" ]
[((424, 441), 'random.seed', 'random.seed', (['SEED'], {}), '(SEED)\n', (435, 441), False, 'import random\n'), ((442, 462), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (456, 462), True, 'import numpy as np\n'), ((463, 486), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (480, 486), False, 'import torch\n'), ((487, 515), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (509, 515), False, 'import torch\n'), ((1007, 1036), 'spacy.load', 'spacy.load', (['"""de_core_news_sm"""'], {}), "('de_core_news_sm')\n", (1017, 1036), False, 'import spacy\n'), ((1048, 1076), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (1058, 1076), False, 'import spacy\n'), ((2013, 2091), 'torchtext.legacy.data.Field', 'Field', ([], {'tokenize': 'tokenize_de', 'init_token': '"""<sos>"""', 'eos_token': '"""<eos>"""', 'lower': '(True)'}), "(tokenize=tokenize_de, init_token='<sos>', eos_token='<eos>', lower=True)\n", (2018, 2091), False, 'from torchtext.legacy.data import Field, BucketIterator\n'), ((2098, 2176), 'torchtext.legacy.data.Field', 'Field', ([], {'tokenize': 'tokenize_en', 'init_token': '"""<sos>"""', 'eos_token': '"""<eos>"""', 'lower': '(True)'}), "(tokenize=tokenize_en, init_token='<sos>', eos_token='<eos>', lower=True)\n", (2103, 2176), False, 'from torchtext.legacy.data import Field, BucketIterator\n'), ((2305, 2360), 'torchtext.legacy.datasets.Multi30k.splits', 'Multi30k.splits', ([], {'exts': "('.de', '.en')", 'fields': '(SRC, TRG)'}), "(exts=('.de', '.en'), fields=(SRC, TRG))\n", (2320, 2360), False, 'from torchtext.legacy.datasets import Multi30k\n'), ((4013, 4114), 'torchtext.legacy.data.BucketIterator.splits', 'BucketIterator.splits', (['(train_data, valid_data, test_data)'], {'batch_size': 'BATCH_SIZE', 'device': 'device'}), '((train_data, valid_data, test_data), batch_size=\n BATCH_SIZE, device=device)\n', (4034, 4114), False, 'from torchtext.legacy.data import Field, BucketIterator\n'), ((3695, 3720), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3718, 3720), False, 'import torch\n')]
import keras import numpy as np import pickle as pickle from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.utils import plot_model from keras.models import load_model from keras.optimizers import RMSprop from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional,TimeDistributed def load_data(file_Name): print('[Load data...]') f = open(file_Name, 'rb') data = pickle.load(f) data_num = len(data[0]) print('Data_num:', data_num) seq_len = len(data[0][0]) print('Sequence length:', seq_len) return data[0], data[1] def createModel(): model = keras.Sequential() model.add(Embedding(256,16,input_length=200)) model.add(Bidirectional(SimpleRNN(8,activation=None, return_sequences=True))) model.add(Activation('relu')) model.add(Bidirectional(SimpleRNN(8, activation=None, return_sequences=True))) model.add(Activation('relu')) model.add(Bidirectional(SimpleRNN(8, activation=None, return_sequences=True))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(TimeDistributed(Dense(2,activation='softmax'))) #model.compile(loss = my_loss_fun, optimizer='sgd', metrics=['accuracy']) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) #plot_model(model, to_file='mymodel.png', show_shapes=True) return model def my_loss_fun(y_true, y_pred): theta = (y_true[:,:,1] - y_pred[:,:,1]) return np.min(theta) def NormalRuleSet(RuleSet): newRuleSet = [] for rule in RuleSet: st_pt = 100 for r in rule: st_pt = np.min([r[0], st_pt]) newrule = [] for r in rule: newrule.append([r[0] - st_pt, r[1]]) newRuleSet.append(newrule) return newRuleSet def selAvailableRule(x, index, RuleSet): selIndex = [] for i in index: covered = False for rule in RuleSet: testSample = np.zeros([1, 4]) for r in rule: testSample[0][int(r[0])] = r[1] for j in range(196): if (x[i][j : j + 4] == testSample).all(): print("find a forbidden instance") covered = True break if covered == True: break if covered == False: selIndex.append(i) return selIndex def main(): data_path = 'D:\\machineLearning_Data\\elf-x86OUT\\1.pkl' x,y = load_data(data_path) y_labels = keras.utils.to_categorical(y, num_classes = 2) dataSize = np.int(len(x) / 10) index = np.random.randint(0,10,dataSize) delindex = [] for i in range(dataSize): delindex.append(i * 10 + index[i]) train_X = x[delindex] train_Y = y_labels[delindex] x = np.delete(x, delindex, axis = 0) y = np.delete(y, delindex, axis = 0) f = open("data\\DNN_train_data.pkl", "wb") pickle.dump([train_X, train_Y], f) f.close() print("finish save my DNN data") dataSize = np.int(len(x) / 10) index = np.random.randint(0, 10, dataSize) delindex = [] for i in range(dataSize): delindex.append(i * 10 + index[i]) mymodel_x = x[delindex] mymodel_y = y[delindex] x = np.delete(x, delindex, axis=0) y = np.delete(y, delindex, axis=0) f = open("data\\build_model_data.pkl", "wb") pickle.dump([mymodel_x, mymodel_y], f) f.close() print("finish save my model data") dataSize = np.int(len(x) / 10) index = np.random.randint(0, 10, dataSize) delindex = [] for i in range(dataSize): delindex.append(i * 10 + index[i]) testDNN_x = x[delindex] testDNN_y = y[delindex] x = np.delete(x, delindex, axis=0) y = np.delete(y, delindex, axis=0) f = open("data\\test_DNN_data.pkl", "wb") pickle.dump([testDNN_x, testDNN_y], f) f.close() print("finish save my test DNN data") f = open("data\\test_model_data.pkl", "wb") pickle.dump([x, y], f) f.close() print("finish save my test model data") model = createModel() model.fit(train_X, train_Y, batch_size=100, validation_split=0.0, epochs=20, ) model.save('model\\rnn_model.h5') print("finish train model") if __name__ == '__main__': main()
[ "keras.layers.SimpleRNN", "keras.optimizers.Adadelta", "pickle.dump", "keras.layers.Activation", "keras.Sequential", "keras.layers.Dropout", "numpy.zeros", "numpy.min", "pickle.load", "numpy.random.randint", "keras.layers.Embedding", "keras.layers.Dense", "numpy.delete", "keras.utils.to_ca...
[((471, 485), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (482, 485), True, 'import pickle as pickle\n'), ((688, 706), 'keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (704, 706), False, 'import keras\n'), ((1639, 1652), 'numpy.min', 'np.min', (['theta'], {}), '(theta)\n', (1645, 1652), True, 'import numpy as np\n'), ((2723, 2767), 'keras.utils.to_categorical', 'keras.utils.to_categorical', (['y'], {'num_classes': '(2)'}), '(y, num_classes=2)\n', (2749, 2767), False, 'import keras\n'), ((2821, 2855), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', 'dataSize'], {}), '(0, 10, dataSize)\n', (2838, 2855), True, 'import numpy as np\n'), ((3020, 3050), 'numpy.delete', 'np.delete', (['x', 'delindex'], {'axis': '(0)'}), '(x, delindex, axis=0)\n', (3029, 3050), True, 'import numpy as np\n'), ((3062, 3092), 'numpy.delete', 'np.delete', (['y', 'delindex'], {'axis': '(0)'}), '(y, delindex, axis=0)\n', (3071, 3092), True, 'import numpy as np\n'), ((3148, 3182), 'pickle.dump', 'pickle.dump', (['[train_X, train_Y]', 'f'], {}), '([train_X, train_Y], f)\n', (3159, 3182), True, 'import pickle as pickle\n'), ((3289, 3323), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', 'dataSize'], {}), '(0, 10, dataSize)\n', (3306, 3323), True, 'import numpy as np\n'), ((3485, 3515), 'numpy.delete', 'np.delete', (['x', 'delindex'], {'axis': '(0)'}), '(x, delindex, axis=0)\n', (3494, 3515), True, 'import numpy as np\n'), ((3525, 3555), 'numpy.delete', 'np.delete', (['y', 'delindex'], {'axis': '(0)'}), '(y, delindex, axis=0)\n', (3534, 3555), True, 'import numpy as np\n'), ((3611, 3649), 'pickle.dump', 'pickle.dump', (['[mymodel_x, mymodel_y]', 'f'], {}), '([mymodel_x, mymodel_y], f)\n', (3622, 3649), True, 'import pickle as pickle\n'), ((3760, 3794), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', 'dataSize'], {}), '(0, 10, dataSize)\n', (3777, 3794), True, 'import numpy as np\n'), ((3956, 3986), 'numpy.delete', 'np.delete', (['x', 'delindex'], {'axis': '(0)'}), '(x, delindex, axis=0)\n', (3965, 3986), True, 'import numpy as np\n'), ((3996, 4026), 'numpy.delete', 'np.delete', (['y', 'delindex'], {'axis': '(0)'}), '(y, delindex, axis=0)\n', (4005, 4026), True, 'import numpy as np\n'), ((4079, 4117), 'pickle.dump', 'pickle.dump', (['[testDNN_x, testDNN_y]', 'f'], {}), '([testDNN_x, testDNN_y], f)\n', (4090, 4117), True, 'import pickle as pickle\n'), ((4234, 4256), 'pickle.dump', 'pickle.dump', (['[x, y]', 'f'], {}), '([x, y], f)\n', (4245, 4256), True, 'import pickle as pickle\n'), ((722, 758), 'keras.layers.Embedding', 'Embedding', (['(256)', '(16)'], {'input_length': '(200)'}), '(256, 16, input_length=200)\n', (731, 758), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((856, 874), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (866, 874), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((977, 995), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (987, 995), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((1098, 1116), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1108, 1116), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((1133, 1145), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (1140, 1145), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((787, 839), 'keras.layers.SimpleRNN', 'SimpleRNN', (['(8)'], {'activation': 'None', 'return_sequences': '(True)'}), '(8, activation=None, return_sequences=True)\n', (796, 839), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((907, 959), 'keras.layers.SimpleRNN', 'SimpleRNN', (['(8)'], {'activation': 'None', 'return_sequences': '(True)'}), '(8, activation=None, return_sequences=True)\n', (916, 959), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((1028, 1080), 'keras.layers.SimpleRNN', 'SimpleRNN', (['(8)'], {'activation': 'None', 'return_sequences': '(True)'}), '(8, activation=None, return_sequences=True)\n', (1037, 1080), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((1180, 1210), 'keras.layers.Dense', 'Dense', (['(2)'], {'activation': '"""softmax"""'}), "(2, activation='softmax')\n", (1185, 1210), False, 'from keras.layers import Dense, Activation, Dropout, SimpleRNN, Embedding, Bidirectional, TimeDistributed\n'), ((1387, 1414), 'keras.optimizers.Adadelta', 'keras.optimizers.Adadelta', ([], {}), '()\n', (1412, 1414), False, 'import keras\n'), ((1799, 1820), 'numpy.min', 'np.min', (['[r[0], st_pt]'], {}), '([r[0], st_pt])\n', (1805, 1820), True, 'import numpy as np\n'), ((2143, 2159), 'numpy.zeros', 'np.zeros', (['[1, 4]'], {}), '([1, 4])\n', (2151, 2159), True, 'import numpy as np\n')]
# Taken and modified from # https://github.com/cyvius96/prototypical-network-pytorch import os.path as osp import numpy as np from PIL import Image import torch from torch.utils.data import Dataset from torchvision import transforms from torch.utils.data import DataLoader from protonets.data.base import CudaTransform class SimpleCudaTransform(object): def __call__(self, data): data = data.cuda() return data class MiniImageNet(Dataset): def __init__(self, ROOT_PATH, setname, cuda=False): self.cuda = cuda csv_path = osp.join(ROOT_PATH, setname + '.csv') lines = [x.strip() for x in open(csv_path, 'r').readlines()][1:] data = [] label = [] lb = -1 self.wnids = [] for l in lines: name, wnid = l.split(',') path = osp.join(ROOT_PATH, 'images', name) if wnid not in self.wnids: self.wnids.append(wnid) lb += 1 data.append(path) label.append(lb) self.data = data self.label = label t = [ transforms.Resize(84), transforms.CenterCrop(84), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ] #if cuda: # t.append(SimpleCudaTransform()) self.transform = transforms.Compose(t) def __len__(self): return len(self.data) def __getitem__(self, i): path, label = self.data[i], self.label[i] image = self.transform(Image.open(path).convert('RGB')) return image, label class CategoriesSampler(object): def __init__(self, label, n_batch, n_cls, n_per): self.n_batch = n_batch self.n_cls = n_cls self.n_per = n_per label = np.array(label) self.m_ind = [] for i in range(max(label) + 1): ind = np.argwhere(label == i).reshape(-1) ind = torch.from_numpy(ind) self.m_ind.append(ind) def __len__(self): return self.n_batch def __iter__(self): for i_batch in range(self.n_batch): batch = [] classes = torch.randperm(len(self.m_ind))[:self.n_cls] for c in classes: l = self.m_ind[c] pos = torch.randperm(len(l))[:self.n_per] batch.append(l[pos]) #batch = torch.stack(batch).t().reshape(-1) # Removed the transpose to get (n_way, n_shot+query) convention batch = torch.stack(batch).reshape(-1) yield batch def AdapterDataLoader(DataLoader): def __init__(self, n_class, n_shot, n_query, *args, **kwargs): self.n_class = n_class self.n_shot = n_shot self.n_query = n_query DataLoader.__init__(self, *args, **kwargs) def __iter__(self): for batch in DataLoader: xs = batch[:self.shot * self.train_way] xq = batch[self.shot * self.train_way] sample = { } def load(opt, splits): ret = { } for split in splits: if split in ['val', 'test'] and opt['data.test_way'] != 0: n_way = opt['data.test_way'] else: n_way = opt['data.way'] if split in ['val', 'test'] and opt['data.test_shot'] != 0: n_support = opt['data.test_shot'] else: n_support = opt['data.shot'] if split in ['val', 'test'] and opt['data.test_query'] != 0: n_query = opt['data.test_query'] else: n_query = opt['data.query'] if split in ['val', 'test']: n_episodes = opt['data.test_episodes'] else: n_episodes = opt['data.train_episodes'] # Right now CUDA is ignored. It will be used in the data adapter. # This is due to issues with multiprocessing and CUDA driver initialization. # https://github.com/pytorch/pytorch/issues/2517 if split == 'train': trainset = MiniImageNet(opt['data.root'], 'train', cuda=opt['data.cuda']) train_sampler = CategoriesSampler(trainset.label, 100, n_way, n_support+n_query) train_loader = DataLoader(dataset=trainset, batch_sampler=train_sampler, num_workers=8, pin_memory=True) ret[split] = train_loader elif split == 'val': valset = MiniImageNet(opt['data.root'], 'val', cuda=opt['data.cuda']) val_sampler = CategoriesSampler(valset.label, 400, n_way, n_support+n_query) val_loader = DataLoader(dataset=valset, batch_sampler=val_sampler, num_workers=8, pin_memory=True) ret[split] = val_loader elif split == 'test': testset = MiniImageNet(opt['data.root'], 'test', cuda=opt['data.cuda']) test_sampler = CategoriesSampler(testset.label, 400, n_way, n_support+n_query) test_loader = DataLoader(dataset=testset, batch_sampler=test_sampler, num_workers=8, pin_memory=True) ret[split] = test_loader else: raise Exception('Split not implemented for MiniImagenet') return ret
[ "torch.from_numpy", "torch.stack", "torch.utils.data.DataLoader", "torchvision.transforms.ToTensor", "PIL.Image.open", "numpy.argwhere", "torchvision.transforms.Compose", "numpy.array", "torch.utils.data.DataLoader.__init__", "torchvision.transforms.CenterCrop", "torchvision.transforms.Normalize...
[((569, 606), 'os.path.join', 'osp.join', (['ROOT_PATH', "(setname + '.csv')"], {}), "(ROOT_PATH, setname + '.csv')\n", (577, 606), True, 'import os.path as osp\n'), ((1437, 1458), 'torchvision.transforms.Compose', 'transforms.Compose', (['t'], {}), '(t)\n', (1455, 1458), False, 'from torchvision import transforms\n'), ((1879, 1894), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (1887, 1894), True, 'import numpy as np\n'), ((2869, 2911), 'torch.utils.data.DataLoader.__init__', 'DataLoader.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (2888, 2911), False, 'from torch.utils.data import DataLoader\n'), ((841, 876), 'os.path.join', 'osp.join', (['ROOT_PATH', '"""images"""', 'name'], {}), "(ROOT_PATH, 'images', name)\n", (849, 876), True, 'import os.path as osp\n'), ((1119, 1140), 'torchvision.transforms.Resize', 'transforms.Resize', (['(84)'], {}), '(84)\n', (1136, 1140), False, 'from torchvision import transforms\n'), ((1154, 1179), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(84)'], {}), '(84)\n', (1175, 1179), False, 'from torchvision import transforms\n'), ((1193, 1214), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1212, 1214), False, 'from torchvision import transforms\n'), ((1228, 1303), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'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', (1248, 1303), False, 'from torchvision import transforms\n'), ((2031, 2052), 'torch.from_numpy', 'torch.from_numpy', (['ind'], {}), '(ind)\n', (2047, 2052), False, 'import torch\n'), ((4328, 4421), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'trainset', 'batch_sampler': 'train_sampler', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(dataset=trainset, batch_sampler=train_sampler, num_workers=8,\n pin_memory=True)\n', (4338, 4421), False, 'from torch.utils.data import DataLoader\n'), ((4764, 4853), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'valset', 'batch_sampler': 'val_sampler', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(dataset=valset, batch_sampler=val_sampler, num_workers=8,\n pin_memory=True)\n', (4774, 4853), False, 'from torch.utils.data import DataLoader\n'), ((1626, 1642), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (1636, 1642), False, 'from PIL import Image\n'), ((1977, 2000), 'numpy.argwhere', 'np.argwhere', (['(label == i)'], {}), '(label == i)\n', (1988, 2000), True, 'import numpy as np\n'), ((2610, 2628), 'torch.stack', 'torch.stack', (['batch'], {}), '(batch)\n', (2621, 2628), False, 'import torch\n'), ((5198, 5289), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'testset', 'batch_sampler': 'test_sampler', 'num_workers': '(8)', 'pin_memory': '(True)'}), '(dataset=testset, batch_sampler=test_sampler, num_workers=8,\n pin_memory=True)\n', (5208, 5289), False, 'from torch.utils.data import DataLoader\n')]
import logging from logging import handlers import numpy as np import random import os # 日志操作 class Logger(object): level_relations = { 'debug':logging.DEBUG, 'info':logging.INFO, 'warning':logging.WARNING, 'error':logging.ERROR, 'crit':logging.CRITICAL }#日志级别关系映射 def __init__(self,filename,level='info',when='D',fmt='%(asctime)s : %(message)s'): self.logger = logging.getLogger(filename) format_str = logging.Formatter(fmt)#设置日志格式 self.logger.setLevel(self.level_relations.get(level))#设置日志级别 sh = logging.StreamHandler()#往屏幕上输出 sh.setFormatter(format_str) #设置屏幕上显示的格式 th = handlers.TimedRotatingFileHandler(filename=filename,when=when,encoding='utf-8')#往文件里写入#指定间隔时间自动生成文件的处理器 #实例化TimedRotatingFileHandler #interval是时间间隔,when是间隔的时间单位,单位有以下几种: # S 秒 # M 分 # H 小时、 # D 天、 # W 每星期(interval==0时代表星期一) # midnight 每天凌晨 th.setFormatter(format_str)#设置文件里写入的格式 self.logger.addHandler(sh) #把对象加到logger里 self.logger.addHandler(th) def info(self,messge): self.logger.info(messge) # 划分训练集和验证集 def split_image_data(image_dir,train_rate=0.2,file_postfix='jpg',shuffle=True): file_name_list = os.listdir(image_dir) image_name_list = [] for i in file_name_list: if i[-3:]==file_postfix: image_name_list.append(i) if shuffle==True: random.seed(6) random.shuffle(image_name_list) data_len = len(image_name_list) train_data = image_name_list[:int(train_rate*data_len)] test_data = image_name_list[int(train_rate*data_len):] return train_data,test_data # CHW->HWC def transepose_image(image,label,predict): t_image = [] t_label = [] t_predict = [] for i,j,k in zip(label,predict,image): t_label.append(np.transpose(i, (1,2,0))) t_predict.append(np.transpose(j, (1,2,0))) t_image.append(np.transpose(k, (1,2,0))) return t_image,t_label,t_predict #-----------get acc import numpy as np import cv2 import os """ 混淆矩阵 P\L P N P TP FP N FN TN """ # 从文件夹读取文件用 def flatten_data(data_dir,label_list,pre_list): label_data_list = [] pre_data_list = [] for i in range(len(label_list)): # 读取灰度图 label_data = cv2.imread(os.path.join(data_dir,label_list[i]),0).astype(np.uint8) pre_data = cv2.imread(os.path.join(data_dir,pre_list[i]),0).astype(np.uint8) # 二值化,大于1的等于1 _,label_data=cv2.threshold(label_data,1,1,cv2.THRESH_TRUNC) _,pre_data=cv2.threshold(pre_data,1,1,cv2.THRESH_TRUNC) label_data_list.append(label_data) pre_data_list.append(pre_data) label_data_list = np.array(label_data_list) pre_data_list = np.array(pre_data_list) label_data_list = label_data_list.flatten() pre_data_list = pre_data_list.flatten() # print(label_data_list.shape) return label_data_list,pre_data_list # 训练过程使用 def process_data(label_list,pre_list): ''' 处理数据 :param label_list: label np格式列表 :param pre_list: 预测图片 np格式列表 :return: flatten的数据 ''' label_data_list = [] pre_data_list = [] for i in range(len(label_list)): # 二值化,大于1的等于1 _,label_data=cv2.threshold(label_list[i].astype(np.uint8),1,1,cv2.THRESH_TRUNC) _,pre_data=cv2.threshold(pre_list[i].astype(np.uint8),1,1,cv2.THRESH_TRUNC) label_data_list.append(label_data) pre_data_list.append(pre_data) label_data_list = np.array(label_data_list) pre_data_list = np.array(pre_data_list) label_data_list = label_data_list.flatten() pre_data_list = pre_data_list.flatten() # print(label_data_list.shape) return label_data_list,pre_data_list def ConfusionMatrix(numClass, imgPredict, Label): # 返回混淆矩阵 mask = (Label >= 0) & (Label < numClass) label = numClass * Label[mask] + imgPredict[mask] count = np.bincount(label, minlength = numClass**2) confusionMatrix = count.reshape(numClass, numClass) return confusionMatrix def OverallAccuracy(confusionMatrix): # 返回所有类的整体像素精度OA # acc = (TP + TN) / (TP + TN + FP + TN) OA = np.diag(confusionMatrix).sum() / confusionMatrix.sum() return OA def Precision(confusionMatrix): # 返回所有类别的精确率precision precision = np.diag(confusionMatrix) / confusionMatrix.sum(axis = 1) return precision def Recall(confusionMatrix): # 返回所有类别的召回率recall recall = np.diag(confusionMatrix) / confusionMatrix.sum(axis = 0) return recall def F1Score(confusionMatrix): precision = np.diag(confusionMatrix) / confusionMatrix.sum(axis = 1) recall = np.diag(confusionMatrix) / confusionMatrix.sum(axis = 0) f1score = 2 * precision * recall / (precision + recall) return f1score def IntersectionOverUnion(confusionMatrix): # 返回交并比IoU intersection = np.diag(confusionMatrix) union = np.sum(confusionMatrix, axis = 1) + np.sum(confusionMatrix, axis = 0) - np.diag(confusionMatrix) IoU = intersection / union return IoU def MeanIntersectionOverUnion(confusionMatrix): # 返回平均交并比mIoU intersection = np.diag(confusionMatrix) union = np.sum(confusionMatrix, axis = 1) + np.sum(confusionMatrix, axis = 0) - np.diag(confusionMatrix) IoU = intersection / union mIoU = np.nanmean(IoU) return mIoU def Frequency_Weighted_Intersection_over_Union(confusionMatrix): # 返回频权交并比FWIoU freq = np.sum(confusionMatrix, axis=1) / np.sum(confusionMatrix) iu = np.diag(confusionMatrix) / ( np.sum(confusionMatrix, axis = 1) + np.sum(confusionMatrix, axis = 0) - np.diag(confusionMatrix)) FWIoU = (freq[freq > 0] * iu[freq > 0]).sum() return FWIoU def get_acc(label,predict,classNum=2): label_all,predict_all = process_data(label,predict) # 计算混淆矩阵及各精度参数 confusionMatrix = ConfusionMatrix(classNum, predict_all, label_all) precision = Precision(confusionMatrix) recall = Recall(confusionMatrix) # OA = OverallAccuracy(confusionMatrix) IoU = IntersectionOverUnion(confusionMatrix) # FWIOU = Frequency_Weighted_Intersection_over_Union(confusionMatrix) # mIOU = MeanIntersectionOverUnion(confusionMatrix) f1ccore = F1Score(confusionMatrix) return precision[1],recall[1],IoU[1],f1ccore[1]
[ "numpy.sum", "random.shuffle", "cv2.threshold", "logging.StreamHandler", "numpy.transpose", "logging.Formatter", "numpy.array", "random.seed", "logging.handlers.TimedRotatingFileHandler", "numpy.diag", "numpy.bincount", "os.path.join", "os.listdir", "logging.getLogger", "numpy.nanmean" ]
[((1323, 1344), 'os.listdir', 'os.listdir', (['image_dir'], {}), '(image_dir)\n', (1333, 1344), False, 'import os\n'), ((2880, 2905), 'numpy.array', 'np.array', (['label_data_list'], {}), '(label_data_list)\n', (2888, 2905), True, 'import numpy as np\n'), ((2928, 2951), 'numpy.array', 'np.array', (['pre_data_list'], {}), '(pre_data_list)\n', (2936, 2951), True, 'import numpy as np\n'), ((3696, 3721), 'numpy.array', 'np.array', (['label_data_list'], {}), '(label_data_list)\n', (3704, 3721), True, 'import numpy as np\n'), ((3744, 3767), 'numpy.array', 'np.array', (['pre_data_list'], {}), '(pre_data_list)\n', (3752, 3767), True, 'import numpy as np\n'), ((4124, 4167), 'numpy.bincount', 'np.bincount', (['label'], {'minlength': '(numClass ** 2)'}), '(label, minlength=numClass ** 2)\n', (4135, 4167), True, 'import numpy as np\n'), ((5091, 5115), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5098, 5115), True, 'import numpy as np\n'), ((5365, 5389), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5372, 5389), True, 'import numpy as np\n'), ((5544, 5559), 'numpy.nanmean', 'np.nanmean', (['IoU'], {}), '(IoU)\n', (5554, 5559), True, 'import numpy as np\n'), ((439, 466), 'logging.getLogger', 'logging.getLogger', (['filename'], {}), '(filename)\n', (456, 466), False, 'import logging\n'), ((489, 511), 'logging.Formatter', 'logging.Formatter', (['fmt'], {}), '(fmt)\n', (506, 511), False, 'import logging\n'), ((603, 626), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (624, 626), False, 'import logging\n'), ((697, 783), 'logging.handlers.TimedRotatingFileHandler', 'handlers.TimedRotatingFileHandler', ([], {'filename': 'filename', 'when': 'when', 'encoding': '"""utf-8"""'}), "(filename=filename, when=when, encoding=\n 'utf-8')\n", (730, 783), False, 'from logging import handlers\n'), ((1520, 1534), 'random.seed', 'random.seed', (['(6)'], {}), '(6)\n', (1531, 1534), False, 'import random\n'), ((1544, 1575), 'random.shuffle', 'random.shuffle', (['image_name_list'], {}), '(image_name_list)\n', (1558, 1575), False, 'import random\n'), ((2659, 2708), 'cv2.threshold', 'cv2.threshold', (['label_data', '(1)', '(1)', 'cv2.THRESH_TRUNC'], {}), '(label_data, 1, 1, cv2.THRESH_TRUNC)\n', (2672, 2708), False, 'import cv2\n'), ((2726, 2773), 'cv2.threshold', 'cv2.threshold', (['pre_data', '(1)', '(1)', 'cv2.THRESH_TRUNC'], {}), '(pre_data, 1, 1, cv2.THRESH_TRUNC)\n', (2739, 2773), False, 'import cv2\n'), ((4524, 4548), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (4531, 4548), True, 'import numpy as np\n'), ((4674, 4698), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (4681, 4698), True, 'import numpy as np\n'), ((4800, 4824), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (4807, 4824), True, 'import numpy as np\n'), ((4871, 4895), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (4878, 4895), True, 'import numpy as np\n'), ((5201, 5225), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5208, 5225), True, 'import numpy as np\n'), ((5475, 5499), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5482, 5499), True, 'import numpy as np\n'), ((5678, 5709), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(1)'}), '(confusionMatrix, axis=1)\n', (5684, 5709), True, 'import numpy as np\n'), ((5712, 5735), 'numpy.sum', 'np.sum', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5718, 5735), True, 'import numpy as np\n'), ((5746, 5770), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5753, 5770), True, 'import numpy as np\n'), ((1959, 1985), 'numpy.transpose', 'np.transpose', (['i', '(1, 2, 0)'], {}), '(i, (1, 2, 0))\n', (1971, 1985), True, 'import numpy as np\n'), ((2011, 2037), 'numpy.transpose', 'np.transpose', (['j', '(1, 2, 0)'], {}), '(j, (1, 2, 0))\n', (2023, 2037), True, 'import numpy as np\n'), ((2061, 2087), 'numpy.transpose', 'np.transpose', (['k', '(1, 2, 0)'], {}), '(k, (1, 2, 0))\n', (2073, 2087), True, 'import numpy as np\n'), ((5129, 5160), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(1)'}), '(confusionMatrix, axis=1)\n', (5135, 5160), True, 'import numpy as np\n'), ((5165, 5196), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(0)'}), '(confusionMatrix, axis=0)\n', (5171, 5196), True, 'import numpy as np\n'), ((5403, 5434), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(1)'}), '(confusionMatrix, axis=1)\n', (5409, 5434), True, 'import numpy as np\n'), ((5439, 5470), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(0)'}), '(confusionMatrix, axis=0)\n', (5445, 5470), True, 'import numpy as np\n'), ((5886, 5910), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (5893, 5910), True, 'import numpy as np\n'), ((4374, 4398), 'numpy.diag', 'np.diag', (['confusionMatrix'], {}), '(confusionMatrix)\n', (4381, 4398), True, 'import numpy as np\n'), ((5788, 5819), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(1)'}), '(confusionMatrix, axis=1)\n', (5794, 5819), True, 'import numpy as np\n'), ((5837, 5868), 'numpy.sum', 'np.sum', (['confusionMatrix'], {'axis': '(0)'}), '(confusionMatrix, axis=0)\n', (5843, 5868), True, 'import numpy as np\n'), ((2469, 2506), 'os.path.join', 'os.path.join', (['data_dir', 'label_list[i]'], {}), '(data_dir, label_list[i])\n', (2481, 2506), False, 'import os\n'), ((2557, 2592), 'os.path.join', 'os.path.join', (['data_dir', 'pre_list[i]'], {}), '(data_dir, pre_list[i])\n', (2569, 2592), False, 'import os\n')]
from __future__ import division import os import zipfile import numpy as np import scipy.sparse as sp import pandas as pd from math import radians, cos, sin, asin, sqrt import joblib import scipy.io import torch from torch import nn """ Geographical information calculation """ def get_long_lat(sensor_index,loc = None): """ Input the index out from 0-206 to access the longitude and latitude of the nodes """ if loc is None: locations = pd.read_csv('data/metr/graph_sensor_locations.csv') else: locations = loc lng = locations['longitude'].loc[sensor_index] lat = locations['latitude'].loc[sensor_index] return lng.to_numpy(),lat.to_numpy() def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 return c * r * 1000 """ Load datasets """ def load_metr_la_rdata(): if (not os.path.isfile("data/metr/adj_mat.npy") or not os.path.isfile("data/metr/node_values.npy")): with zipfile.ZipFile("data/metr/METR-LA.zip", 'r') as zip_ref: zip_ref.extractall("data/metr/") A = np.load("data/metr/adj_mat.npy") X = np.load("data/metr/node_values.npy").transpose((1, 2, 0)) X = X.astype(np.float32) return A, X def generate_nerl_data(): # %% Obtain all the file names filepath = 'data/nrel/al-pv-2006' files = os.listdir(filepath) # %% Begin parse the file names and store them in a pandas Dataframe tp = [] # Type lat = [] # Latitude lng =[] # Longitude yr = [] # Year pv_tp = [] # PV_type cap = [] # Capacity MW time_itv = [] # Time interval file_names =[] for _file in files: parse = _file.split('_') if parse[-2] == '5': tp.append(parse[0]) lat.append(np.double(parse[1])) lng.append(np.double(parse[2])) yr.append(np.int(parse[3])) pv_tp.append(parse[4]) cap.append(np.int(parse[5].split('MW')[0])) time_itv.append(parse[6]) file_names.append(_file) else: pass files_info = pd.DataFrame( np.array([tp,lat,lng,yr,pv_tp,cap,time_itv,file_names]).T, columns=['type','latitude','longitude','year','pv_type','capacity','time_interval','file_name'] ) # %% Read the time series into a numpy 2-D array with 137x105120 size X = np.zeros((len(files_info),365*24*12)) for i in range(files_info.shape[0]): f = filepath + '/' + files_info['file_name'].loc[i] d = pd.read_csv(f) assert d.shape[0] == 365*24*12, 'Data missing!' X[i,:] = d['Power(MW)'] print(i/files_info.shape[0]*100,'%') np.save('data/nrel/nerl_X.npy',X) files_info.to_pickle('data/nrel/nerl_file_infos.pkl') # %% Get the adjacency matrix based on the inverse of distance between two nodes A = np.zeros((files_info.shape[0],files_info.shape[0])) for i in range(files_info.shape[0]): for j in range(i+1,files_info.shape[0]): lng1 = lng[i] lng2 = lng[j] lat1 = lat[i] lat2 = lat[j] d = haversine(lng1,lat1,lng2,lat2) A[i,j] = d A = A/7500 # distance / 7.5 km A += A.T + np.diag(A.diagonal()) A = np.exp(-A) np.save('data/nrel/nerl_A.npy',A) def load_nerl_data(): if (not os.path.isfile("data/nrel/nerl_X.npy") or not os.path.isfile("data/nrel/nerl_A.npy")): with zipfile.ZipFile("data/nrel/al-pv-2006.zip", 'r') as zip_ref: zip_ref.extractall("data/nrel/al-pv-2006") generate_nerl_data() X = np.load('data/nrel/nerl_X.npy') A = np.load('data/nrel/nerl_A.npy') files_info = pd.read_pickle('data/nrel/nerl_file_infos.pkl') X = X.astype(np.float32) # X = (X - X.mean())/X.std() return A,X,files_info def generate_ushcn_data(): pos = [] Utensor = np.zeros((1218, 120, 12, 2)) Omissing = np.ones((1218, 120, 12, 2)) with open("data/ushcn/Ulocation", "r") as f: loc = 0 for line in f.readlines(): poname = line[0:11] pos.append(line[13:30]) with open("data/ushcn/ushcn.v2.5.5.20191231/"+ poname +".FLs.52j.prcp", "r") as fp: temp = 0 for linep in fp.readlines(): if int(linep[12:16]) > 1899: for i in range(12): str_temp = linep[17 + 9*i:22 + 9*i] p_temp = int(str_temp) if p_temp == -9999: Omissing[loc, temp, i, 0] = 0 else: Utensor[loc, temp, i, 0] = p_temp temp = temp + 1 with open("data/ushcn/ushcn.v2.5.5.20191231/"+ poname +".FLs.52j.tavg", "r") as ft: temp = 0 for linet in ft.readlines(): if int(linet[12:16]) > 1899: for i in range(12): str_temp = linet[17 + 9*i:22 + 9*i] t_temp = int(str_temp) if t_temp == -9999: Omissing[loc, temp, i, 1] = 0 else: Utensor[loc, temp, i, 1] = t_temp temp = temp + 1 loc = loc + 1 latlon =np.loadtxt("data/ushcn/latlon.csv",delimiter=",") sim = np.zeros((1218,1218)) for i in range(1218): for j in range(1218): sim[i,j] = haversine(latlon[i, 1], latlon[i, 0], latlon[j, 1], latlon[j, 0]) #RBF sim = np.exp(-sim/10000/10) joblib.dump(Utensor,'data/ushcn/Utensor.joblib') joblib.dump(Omissing,'data/ushcn/Omissing.joblib') joblib.dump(sim,'data/ushcn/sim.joblib') def load_udata(): if (not os.path.isfile("data/ushcn/Utensor.joblib") or not os.path.isfile("data/ushcn/sim.joblib")): with zipfile.ZipFile("data/ushcn/ushcn.v2.5.5.20191231.zip", 'r') as zip_ref: zip_ref.extractall("data/ushcn/ushcn.v2.5.5.20191231/") generate_ushcn_data() X = joblib.load('data/ushcn/Utensor.joblib') A = joblib.load('data/ushcn/sim.joblib') Omissing = joblib.load('data/ushcn/Omissing.joblib') X = X.astype(np.float32) return A,X,Omissing def load_sedata(): assert os.path.isfile('data/sedata/A.mat') assert os.path.isfile('data/sedata/mat.csv') A_mat = scipy.io.loadmat('data/sedata/A.mat') A = A_mat['A'] X = pd.read_csv('data/sedata/mat.csv',index_col=0) X = X.to_numpy() return A,X def load_pems_data(): assert os.path.isfile('data/pems/pems-bay.h5') assert os.path.isfile('data/pems/distances_bay_2017.csv') df = pd.read_hdf('data/pems/pems-bay.h5') transfer_set = df.as_matrix() distance_df = pd.read_csv('data/pems/distances_bay_2017.csv', dtype={'from': 'str', 'to': 'str'}) normalized_k = 0.1 dist_mx = np.zeros((325, 325), dtype=np.float32) dist_mx[:] = np.inf sensor_ids = df.columns.values.tolist() sensor_id_to_ind = {} for i, sensor_id in enumerate(sensor_ids): sensor_id_to_ind[sensor_id] = i for row in distance_df.values: if row[0] not in sensor_id_to_ind or row[1] not in sensor_id_to_ind: continue dist_mx[sensor_id_to_ind[row[0]], sensor_id_to_ind[row[1]]] = row[2] distances = dist_mx[~np.isinf(dist_mx)].flatten() std = distances.std() adj_mx = np.exp(-np.square(dist_mx / std)) adj_mx[adj_mx < normalized_k] = 0 A_new = adj_mx return transfer_set,A_new """ Dynamically construct the adjacent matrix """ def get_Laplace(A): """ Returns the laplacian adjacency matrix. This is for C_GCN """ if A[0, 0] == 1: A = A - np.diag(np.ones(A.shape[0], dtype=np.float32)) # if the diag has been added by 1s D = np.array(np.sum(A, axis=1)).reshape((-1,)) D[D <= 10e-5] = 10e-5 diag = np.reciprocal(np.sqrt(D)) A_wave = np.multiply(np.multiply(diag.reshape((-1, 1)), A), diag.reshape((1, -1))) return A_wave def get_normalized_adj(A): """ Returns the degree normalized adjacency matrix. This is for K_GCN """ if A[0, 0] == 0: A = A + np.diag(np.ones(A.shape[0], dtype=np.float32)) # if the diag has been added by 1s D = np.array(np.sum(A, axis=1)).reshape((-1,)) D[D <= 10e-5] = 10e-5 # Prevent infs diag = np.reciprocal(np.sqrt(D)) A_wave = np.multiply(np.multiply(diag.reshape((-1, 1)), A), diag.reshape((1, -1))) return A_wave def calculate_random_walk_matrix(adj_mx): """ Returns the random walk adjacency matrix. This is for D_GCN """ adj_mx = sp.coo_matrix(adj_mx) d = np.array(adj_mx.sum(1)) d_inv = np.power(d, -1).flatten() d_inv[np.isinf(d_inv)] = 0. d_mat_inv = sp.diags(d_inv) random_walk_mx = d_mat_inv.dot(adj_mx).tocoo() return random_walk_mx.toarray() def test_error(STmodel, unknow_set, test_data, A_s, E_maxvalue, Missing0): """ :param STmodel: The graph neural networks :unknow_set: The unknow locations for spatial prediction :test_data: The true value test_data of shape (test_num_timesteps, num_nodes) :A_s: The full adjacent matrix :Missing0: True: 0 in original datasets means missing data :return: NAE, MAPE and RMSE """ unknow_set = set(unknow_set) time_dim = STmodel.time_dimension test_omask = np.ones(test_data.shape) if Missing0 == True: test_omask[test_data == 0] = 0 test_inputs = (test_data * test_omask).astype('float32') test_inputs_s = test_inputs missing_index = np.ones(np.shape(test_data)) missing_index[:, list(unknow_set)] = 0 missing_index_s = missing_index o = np.zeros([test_data.shape[0]//time_dim*time_dim, test_inputs_s.shape[1]]) #Separate the test data into several h period for i in range(0, test_data.shape[0]//time_dim*time_dim, time_dim): inputs = test_inputs_s[i:i+time_dim, :] missing_inputs = missing_index_s[i:i+time_dim, :] T_inputs = inputs*missing_inputs T_inputs = T_inputs/E_maxvalue T_inputs = np.expand_dims(T_inputs, axis = 0) T_inputs = torch.from_numpy(T_inputs.astype('float32')) A_q = torch.from_numpy((calculate_random_walk_matrix(A_s).T).astype('float32')) A_h = torch.from_numpy((calculate_random_walk_matrix(A_s.T).T).astype('float32')) imputation = STmodel(T_inputs, A_q, A_h) imputation = imputation.data.numpy() o[i:i+time_dim, :] = imputation[0, :, :] o = o*E_maxvalue truth = test_inputs_s[0:test_data.shape[0]//time_dim*time_dim] o[missing_index_s[0:test_data.shape[0]//time_dim*time_dim] == 1] = truth[missing_index_s[0:test_data.shape[0]//time_dim*time_dim] == 1] test_mask = 1 - missing_index_s[0:test_data.shape[0]//time_dim*time_dim] if Missing0 == True: test_mask[truth == 0] = 0 o[truth == 0] = 0 MAE = np.sum(np.abs(o - truth))/np.sum( test_mask) RMSE = np.sqrt(np.sum((o - truth)*(o - truth))/np.sum( test_mask) ) MAPE = np.sum(np.abs(o - truth)/(truth + 1e-5))/np.sum( test_mask) return MAE, RMSE, MAPE, o def rolling_test_error(STmodel, unknow_set, test_data, A_s, E_maxvalue,Missing0): """ :It only calculates the last time points' prediction error, and updates inputs each time point :param STmodel: The graph neural networks :unknow_set: The unknow locations for spatial prediction :test_data: The true value test_data of shape (test_num_timesteps, num_nodes) :A_s: The full adjacent matrix :Missing0: True: 0 in original datasets means missing data :return: NAE, MAPE and RMSE """ unknow_set = set(unknow_set) time_dim = STmodel.time_dimension test_omask = np.ones(test_data.shape) if Missing0 == True: test_omask[test_data == 0] = 0 test_inputs = (test_data * test_omask).astype('float32') test_inputs_s = test_inputs missing_index = np.ones(np.shape(test_data)) missing_index[:, list(unknow_set)] = 0 missing_index_s = missing_index o = np.zeros([test_data.shape[0] - time_dim, test_inputs_s.shape[1]]) for i in range(0, test_data.shape[0] - time_dim): inputs = test_inputs_s[i:i+time_dim, :] missing_inputs = missing_index_s[i:i+time_dim, :] MF_inputs = inputs * missing_inputs MF_inputs = np.expand_dims(MF_inputs, axis = 0) MF_inputs = torch.from_numpy(MF_inputs.astype('float32')) A_q = torch.from_numpy((calculate_random_walk_matrix(A_s).T).astype('float32')) A_h = torch.from_numpy((calculate_random_walk_matrix(A_s.T).T).astype('float32')) imputation = STmodel(MF_inputs, A_q, A_h) imputation = imputation.data.numpy() o[i, :] = imputation[0, time_dim-1, :] truth = test_inputs_s[time_dim:test_data.shape[0]] o[missing_index_s[time_dim:test_data.shape[0]] == 1] = truth[missing_index_s[time_dim:test_data.shape[0]] == 1] o = o*E_maxvalue truth = test_inputs_s[0:test_data.shape[0]//time_dim*time_dim] test_mask = 1 - missing_index_s[time_dim:test_data.shape[0]] if Missing0 == True: test_mask[truth == 0] = 0 o[truth == 0] = 0 MAE = np.sum(np.abs(o - truth))/np.sum( test_mask) RMSE = np.sqrt(np.sum((o - truth)*(o - truth))/np.sum( test_mask) ) MAPE = np.sum(np.abs(o - truth)/(truth + 1e-5))/np.sum( test_mask) #avoid x/0 return MAE, RMSE, MAPE, o def test_error_cap(STmodel, unknow_set, full_set, test_set, A,time_dim,capacities): unknow_set = set(unknow_set) test_omask = np.ones(test_set.shape) test_omask[test_set == 0] = 0 test_inputs = (test_set * test_omask).astype('float32') test_inputs_s = test_inputs#[:, list(proc_set)] missing_index = np.ones(np.shape(test_inputs)) missing_index[:, list(unknow_set)] = 0 missing_index_s = missing_index#[:, list(proc_set)] A_s = A#[:, list(proc_set)][list(proc_set), :] o = np.zeros([test_set.shape[0]//time_dim*time_dim, test_inputs_s.shape[1]]) for i in range(0, test_set.shape[0]//time_dim*time_dim, time_dim): inputs = test_inputs_s[i:i+time_dim, :] missing_inputs = missing_index_s[i:i+time_dim, :] MF_inputs = inputs*missing_inputs MF_inputs = MF_inputs/capacities MF_inputs = np.expand_dims(MF_inputs, axis = 0) MF_inputs = torch.from_numpy(MF_inputs.astype('float32')) A_q = torch.from_numpy((calculate_random_walk_matrix(A_s).T).astype('float32')) A_h = torch.from_numpy((calculate_random_walk_matrix(A_s.T).T).astype('float32')) imputation = STmodel(MF_inputs, A_q, A_h) imputation = imputation.data.numpy() o[i:i+time_dim, :] = imputation[0, :, :] o = o*capacities truth = test_inputs_s[0:test_set.shape[0]//time_dim*time_dim] o[missing_index_s[0:test_set.shape[0]//time_dim*time_dim] == 1] = truth[missing_index_s[0:test_set.shape[0]//time_dim*time_dim] == 1] o[truth == 0] = 0 test_mask = 1 - missing_index_s[0:test_set.shape[0]//time_dim*time_dim] test_mask[truth == 0] = 0 MAE = np.sum(np.abs(o - truth))/np.sum( test_mask) RMSE = np.sqrt(np.sum((o - truth)*(o - truth))/np.sum( test_mask) ) MAPE = np.sum(np.abs(o - truth)/(truth + 1e-5))/np.sum( test_mask) return MAE, RMSE, MAPE ,o
[ "numpy.load", "numpy.sum", "numpy.abs", "numpy.double", "pandas.read_csv", "joblib.dump", "numpy.ones", "numpy.shape", "os.path.isfile", "numpy.exp", "pandas.read_hdf", "numpy.power", "scipy.sparse.coo_matrix", "numpy.int", "numpy.loadtxt", "math.cos", "scipy.sparse.diags", "numpy....
[((1467, 1499), 'numpy.load', 'np.load', (['"""data/metr/adj_mat.npy"""'], {}), "('data/metr/adj_mat.npy')\n", (1474, 1499), True, 'import numpy as np\n'), ((1733, 1753), 'os.listdir', 'os.listdir', (['filepath'], {}), '(filepath)\n', (1743, 1753), False, 'import os\n'), ((3095, 3129), 'numpy.save', 'np.save', (['"""data/nrel/nerl_X.npy"""', 'X'], {}), "('data/nrel/nerl_X.npy', X)\n", (3102, 3129), True, 'import numpy as np\n'), ((3283, 3335), 'numpy.zeros', 'np.zeros', (['(files_info.shape[0], files_info.shape[0])'], {}), '((files_info.shape[0], files_info.shape[0]))\n', (3291, 3335), True, 'import numpy as np\n'), ((3694, 3704), 'numpy.exp', 'np.exp', (['(-A)'], {}), '(-A)\n', (3700, 3704), True, 'import numpy as np\n'), ((3710, 3744), 'numpy.save', 'np.save', (['"""data/nrel/nerl_A.npy"""', 'A'], {}), "('data/nrel/nerl_A.npy', A)\n", (3717, 3744), True, 'import numpy as np\n'), ((4052, 4083), 'numpy.load', 'np.load', (['"""data/nrel/nerl_X.npy"""'], {}), "('data/nrel/nerl_X.npy')\n", (4059, 4083), True, 'import numpy as np\n'), ((4093, 4124), 'numpy.load', 'np.load', (['"""data/nrel/nerl_A.npy"""'], {}), "('data/nrel/nerl_A.npy')\n", (4100, 4124), True, 'import numpy as np\n'), ((4143, 4190), 'pandas.read_pickle', 'pd.read_pickle', (['"""data/nrel/nerl_file_infos.pkl"""'], {}), "('data/nrel/nerl_file_infos.pkl')\n", (4157, 4190), True, 'import pandas as pd\n'), ((4343, 4371), 'numpy.zeros', 'np.zeros', (['(1218, 120, 12, 2)'], {}), '((1218, 120, 12, 2))\n', (4351, 4371), True, 'import numpy as np\n'), ((4388, 4415), 'numpy.ones', 'np.ones', (['(1218, 120, 12, 2)'], {}), '((1218, 120, 12, 2))\n', (4395, 4415), True, 'import numpy as np\n'), ((5922, 5972), 'numpy.loadtxt', 'np.loadtxt', (['"""data/ushcn/latlon.csv"""'], {'delimiter': '""","""'}), "('data/ushcn/latlon.csv', delimiter=',')\n", (5932, 5972), True, 'import numpy as np\n'), ((5983, 6005), 'numpy.zeros', 'np.zeros', (['(1218, 1218)'], {}), '((1218, 1218))\n', (5991, 6005), True, 'import numpy as np\n'), ((6171, 6196), 'numpy.exp', 'np.exp', (['(-sim / 10000 / 10)'], {}), '(-sim / 10000 / 10)\n', (6177, 6196), True, 'import numpy as np\n'), ((6200, 6249), 'joblib.dump', 'joblib.dump', (['Utensor', '"""data/ushcn/Utensor.joblib"""'], {}), "(Utensor, 'data/ushcn/Utensor.joblib')\n", (6211, 6249), False, 'import joblib\n'), ((6254, 6305), 'joblib.dump', 'joblib.dump', (['Omissing', '"""data/ushcn/Omissing.joblib"""'], {}), "(Omissing, 'data/ushcn/Omissing.joblib')\n", (6265, 6305), False, 'import joblib\n'), ((6310, 6351), 'joblib.dump', 'joblib.dump', (['sim', '"""data/ushcn/sim.joblib"""'], {}), "(sim, 'data/ushcn/sim.joblib')\n", (6321, 6351), False, 'import joblib\n'), ((6699, 6739), 'joblib.load', 'joblib.load', (['"""data/ushcn/Utensor.joblib"""'], {}), "('data/ushcn/Utensor.joblib')\n", (6710, 6739), False, 'import joblib\n'), ((6749, 6785), 'joblib.load', 'joblib.load', (['"""data/ushcn/sim.joblib"""'], {}), "('data/ushcn/sim.joblib')\n", (6760, 6785), False, 'import joblib\n'), ((6802, 6843), 'joblib.load', 'joblib.load', (['"""data/ushcn/Omissing.joblib"""'], {}), "('data/ushcn/Omissing.joblib')\n", (6813, 6843), False, 'import joblib\n'), ((6933, 6968), 'os.path.isfile', 'os.path.isfile', (['"""data/sedata/A.mat"""'], {}), "('data/sedata/A.mat')\n", (6947, 6968), False, 'import os\n'), ((6981, 7018), 'os.path.isfile', 'os.path.isfile', (['"""data/sedata/mat.csv"""'], {}), "('data/sedata/mat.csv')\n", (6995, 7018), False, 'import os\n'), ((7099, 7146), 'pandas.read_csv', 'pd.read_csv', (['"""data/sedata/mat.csv"""'], {'index_col': '(0)'}), "('data/sedata/mat.csv', index_col=0)\n", (7110, 7146), True, 'import pandas as pd\n'), ((7221, 7260), 'os.path.isfile', 'os.path.isfile', (['"""data/pems/pems-bay.h5"""'], {}), "('data/pems/pems-bay.h5')\n", (7235, 7260), False, 'import os\n'), ((7273, 7323), 'os.path.isfile', 'os.path.isfile', (['"""data/pems/distances_bay_2017.csv"""'], {}), "('data/pems/distances_bay_2017.csv')\n", (7287, 7323), False, 'import os\n'), ((7334, 7370), 'pandas.read_hdf', 'pd.read_hdf', (['"""data/pems/pems-bay.h5"""'], {}), "('data/pems/pems-bay.h5')\n", (7345, 7370), True, 'import pandas as pd\n'), ((7425, 7512), 'pandas.read_csv', 'pd.read_csv', (['"""data/pems/distances_bay_2017.csv"""'], {'dtype': "{'from': 'str', 'to': 'str'}"}), "('data/pems/distances_bay_2017.csv', dtype={'from': 'str', 'to':\n 'str'})\n", (7436, 7512), True, 'import pandas as pd\n'), ((7550, 7588), 'numpy.zeros', 'np.zeros', (['(325, 325)'], {'dtype': 'np.float32'}), '((325, 325), dtype=np.float32)\n', (7558, 7588), True, 'import numpy as np\n'), ((9423, 9444), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['adj_mx'], {}), '(adj_mx)\n', (9436, 9444), True, 'import scipy.sparse as sp\n'), ((9567, 9582), 'scipy.sparse.diags', 'sp.diags', (['d_inv'], {}), '(d_inv)\n', (9575, 9582), True, 'import scipy.sparse as sp\n'), ((10192, 10216), 'numpy.ones', 'np.ones', (['test_data.shape'], {}), '(test_data.shape)\n', (10199, 10216), True, 'import numpy as np\n'), ((10529, 10606), 'numpy.zeros', 'np.zeros', (['[test_data.shape[0] // time_dim * time_dim, test_inputs_s.shape[1]]'], {}), '([test_data.shape[0] // time_dim * time_dim, test_inputs_s.shape[1]])\n', (10537, 10606), True, 'import numpy as np\n'), ((12664, 12688), 'numpy.ones', 'np.ones', (['test_data.shape'], {}), '(test_data.shape)\n', (12671, 12688), True, 'import numpy as np\n'), ((12997, 13062), 'numpy.zeros', 'np.zeros', (['[test_data.shape[0] - time_dim, test_inputs_s.shape[1]]'], {}), '([test_data.shape[0] - time_dim, test_inputs_s.shape[1]])\n', (13005, 13062), True, 'import numpy as np\n'), ((14578, 14601), 'numpy.ones', 'np.ones', (['test_set.shape'], {}), '(test_set.shape)\n', (14585, 14601), True, 'import numpy as np\n'), ((14979, 15055), 'numpy.zeros', 'np.zeros', (['[test_set.shape[0] // time_dim * time_dim, test_inputs_s.shape[1]]'], {}), '([test_set.shape[0] // time_dim * time_dim, test_inputs_s.shape[1]])\n', (14987, 15055), True, 'import numpy as np\n'), ((485, 536), 'pandas.read_csv', 'pd.read_csv', (['"""data/metr/graph_sensor_locations.csv"""'], {}), "('data/metr/graph_sensor_locations.csv')\n", (496, 536), True, 'import pandas as pd\n'), ((2937, 2951), 'pandas.read_csv', 'pd.read_csv', (['f'], {}), '(f)\n', (2948, 2951), True, 'import pandas as pd\n'), ((8628, 8638), 'numpy.sqrt', 'np.sqrt', (['D'], {}), '(D)\n', (8635, 8638), True, 'import numpy as np\n'), ((9136, 9146), 'numpy.sqrt', 'np.sqrt', (['D'], {}), '(D)\n', (9143, 9146), True, 'import numpy as np\n'), ((9528, 9543), 'numpy.isinf', 'np.isinf', (['d_inv'], {}), '(d_inv)\n', (9536, 9543), True, 'import numpy as np\n'), ((10412, 10431), 'numpy.shape', 'np.shape', (['test_data'], {}), '(test_data)\n', (10420, 10431), True, 'import numpy as np\n'), ((10938, 10970), 'numpy.expand_dims', 'np.expand_dims', (['T_inputs'], {'axis': '(0)'}), '(T_inputs, axis=0)\n', (10952, 10970), True, 'import numpy as np\n'), ((11828, 11845), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (11834, 11845), True, 'import numpy as np\n'), ((11973, 11990), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (11979, 11990), True, 'import numpy as np\n'), ((12884, 12903), 'numpy.shape', 'np.shape', (['test_data'], {}), '(test_data)\n', (12892, 12903), True, 'import numpy as np\n'), ((13298, 13331), 'numpy.expand_dims', 'np.expand_dims', (['MF_inputs'], {'axis': '(0)'}), '(MF_inputs, axis=0)\n', (13312, 13331), True, 'import numpy as np\n'), ((14216, 14233), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (14222, 14233), True, 'import numpy as np\n'), ((14361, 14378), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (14367, 14378), True, 'import numpy as np\n'), ((14788, 14809), 'numpy.shape', 'np.shape', (['test_inputs'], {}), '(test_inputs)\n', (14796, 14809), True, 'import numpy as np\n'), ((15344, 15377), 'numpy.expand_dims', 'np.expand_dims', (['MF_inputs'], {'axis': '(0)'}), '(MF_inputs, axis=0)\n', (15358, 15377), True, 'import numpy as np\n'), ((16199, 16216), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (16205, 16216), True, 'import numpy as np\n'), ((16344, 16361), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (16350, 16361), True, 'import numpy as np\n'), ((1037, 1050), 'math.sin', 'sin', (['(dlat / 2)'], {}), '(dlat / 2)\n', (1040, 1050), False, 'from math import radians, cos, sin, asin, sqrt\n'), ((1111, 1118), 'math.sqrt', 'sqrt', (['a'], {}), '(a)\n', (1115, 1118), False, 'from math import radians, cos, sin, asin, sqrt\n'), ((1232, 1271), 'os.path.isfile', 'os.path.isfile', (['"""data/metr/adj_mat.npy"""'], {}), "('data/metr/adj_mat.npy')\n", (1246, 1271), False, 'import os\n'), ((1292, 1335), 'os.path.isfile', 'os.path.isfile', (['"""data/metr/node_values.npy"""'], {}), "('data/metr/node_values.npy')\n", (1306, 1335), False, 'import os\n'), ((1352, 1397), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""data/metr/METR-LA.zip"""', '"""r"""'], {}), "('data/metr/METR-LA.zip', 'r')\n", (1367, 1397), False, 'import zipfile\n'), ((1509, 1545), 'numpy.load', 'np.load', (['"""data/metr/node_values.npy"""'], {}), "('data/metr/node_values.npy')\n", (1516, 1545), True, 'import numpy as np\n'), ((2528, 2590), 'numpy.array', 'np.array', (['[tp, lat, lng, yr, pv_tp, cap, time_itv, file_names]'], {}), '([tp, lat, lng, yr, pv_tp, cap, time_itv, file_names])\n', (2536, 2590), True, 'import numpy as np\n'), ((3782, 3820), 'os.path.isfile', 'os.path.isfile', (['"""data/nrel/nerl_X.npy"""'], {}), "('data/nrel/nerl_X.npy')\n", (3796, 3820), False, 'import os\n'), ((3841, 3879), 'os.path.isfile', 'os.path.isfile', (['"""data/nrel/nerl_A.npy"""'], {}), "('data/nrel/nerl_A.npy')\n", (3855, 3879), False, 'import os\n'), ((3896, 3944), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""data/nrel/al-pv-2006.zip"""', '"""r"""'], {}), "('data/nrel/al-pv-2006.zip', 'r')\n", (3911, 3944), False, 'import zipfile\n'), ((6397, 6440), 'os.path.isfile', 'os.path.isfile', (['"""data/ushcn/Utensor.joblib"""'], {}), "('data/ushcn/Utensor.joblib')\n", (6411, 6440), False, 'import os\n'), ((6461, 6500), 'os.path.isfile', 'os.path.isfile', (['"""data/ushcn/sim.joblib"""'], {}), "('data/ushcn/sim.joblib')\n", (6475, 6500), False, 'import os\n'), ((6517, 6577), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""data/ushcn/ushcn.v2.5.5.20191231.zip"""', '"""r"""'], {}), "('data/ushcn/ushcn.v2.5.5.20191231.zip', 'r')\n", (6532, 6577), False, 'import zipfile\n'), ((8125, 8149), 'numpy.square', 'np.square', (['(dist_mx / std)'], {}), '(dist_mx / std)\n', (8134, 8149), True, 'import numpy as np\n'), ((9491, 9506), 'numpy.power', 'np.power', (['d', '(-1)'], {}), '(d, -1)\n', (9499, 9506), True, 'import numpy as np\n'), ((11809, 11826), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (11815, 11826), True, 'import numpy as np\n'), ((11867, 11900), 'numpy.sum', 'np.sum', (['((o - truth) * (o - truth))'], {}), '((o - truth) * (o - truth))\n', (11873, 11900), True, 'import numpy as np\n'), ((11899, 11916), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (11905, 11916), True, 'import numpy as np\n'), ((14197, 14214), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (14203, 14214), True, 'import numpy as np\n'), ((14255, 14288), 'numpy.sum', 'np.sum', (['((o - truth) * (o - truth))'], {}), '((o - truth) * (o - truth))\n', (14261, 14288), True, 'import numpy as np\n'), ((14287, 14304), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (14293, 14304), True, 'import numpy as np\n'), ((16180, 16197), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (16186, 16197), True, 'import numpy as np\n'), ((16238, 16271), 'numpy.sum', 'np.sum', (['((o - truth) * (o - truth))'], {}), '((o - truth) * (o - truth))\n', (16244, 16271), True, 'import numpy as np\n'), ((16270, 16287), 'numpy.sum', 'np.sum', (['test_mask'], {}), '(test_mask)\n', (16276, 16287), True, 'import numpy as np\n'), ((1054, 1063), 'math.cos', 'cos', (['lat1'], {}), '(lat1)\n', (1057, 1063), False, 'from math import radians, cos, sin, asin, sqrt\n'), ((1066, 1075), 'math.cos', 'cos', (['lat2'], {}), '(lat2)\n', (1069, 1075), False, 'from math import radians, cos, sin, asin, sqrt\n'), ((1078, 1091), 'math.sin', 'sin', (['(dlon / 2)'], {}), '(dlon / 2)\n', (1081, 1091), False, 'from math import radians, cos, sin, asin, sqrt\n'), ((2175, 2194), 'numpy.double', 'np.double', (['parse[1]'], {}), '(parse[1])\n', (2184, 2194), True, 'import numpy as np\n'), ((2220, 2239), 'numpy.double', 'np.double', (['parse[2]'], {}), '(parse[2])\n', (2229, 2239), True, 'import numpy as np\n'), ((2264, 2280), 'numpy.int', 'np.int', (['parse[3]'], {}), '(parse[3])\n', (2270, 2280), True, 'import numpy as np\n'), ((8449, 8486), 'numpy.ones', 'np.ones', (['A.shape[0]'], {'dtype': 'np.float32'}), '(A.shape[0], dtype=np.float32)\n', (8456, 8486), True, 'import numpy as np\n'), ((8541, 8558), 'numpy.sum', 'np.sum', (['A'], {'axis': '(1)'}), '(A, axis=1)\n', (8547, 8558), True, 'import numpy as np\n'), ((8939, 8976), 'numpy.ones', 'np.ones', (['A.shape[0]'], {'dtype': 'np.float32'}), '(A.shape[0], dtype=np.float32)\n', (8946, 8976), True, 'import numpy as np\n'), ((9031, 9048), 'numpy.sum', 'np.sum', (['A'], {'axis': '(1)'}), '(A, axis=1)\n', (9037, 9048), True, 'import numpy as np\n'), ((11939, 11956), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (11945, 11956), True, 'import numpy as np\n'), ((14327, 14344), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (14333, 14344), True, 'import numpy as np\n'), ((16310, 16327), 'numpy.abs', 'np.abs', (['(o - truth)'], {}), '(o - truth)\n', (16316, 16327), True, 'import numpy as np\n'), ((8047, 8064), 'numpy.isinf', 'np.isinf', (['dist_mx'], {}), '(dist_mx)\n', (8055, 8064), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Wed Aug 30 10:54:21 2017 @author: ishort """ #plotting: import matplotlib import matplotlib.pyplot as plt #%matplotlib inline import pylab from astropy.io import fits import numpy import Gauss2 #General file for printing ad hoc quantities #dbgHandle = open("debug.out", 'w') #Get the data dataPath = "VegaAtlas/" #outPath = absPath + "Outputs/" #If reading FITS file (from STELIB) #http://www.ast.obs-mip.fr/users/leborgne/stelib/fits_files.html #A&A 402, 433–442 (2003) <NAME>, <NAME>, <NAME>, <NAME>, <NAME> , <NAME>, <NAME>, #<NAME>, and <NAME> wav = 0.0 inFile = dataPath + "HD172167_V3.2.fits" hdulist = fits.open(inFile) #Get the coefficients for the wavelength array naxis1 = hdulist[0].header['NAXIS1'] crval1 = hdulist[0].header['CRVAL1'] cdelt = hdulist[0].header['CDELT1'] vhelio = hdulist[0].header['VHELIO'] vlsr = hdulist[0].header['VLSR'] radvel = hdulist[0].header['RADVEL'] flux = hdulist[0].data #Continuum rectification - here a divisor: cy0 = 1.3e-8 wave = [0.0 for i in range(naxis1)] for i in range(naxis1): ii = float(i) wav = crval1 + cdelt*ii wave[i] = 0.1 * wav flux[i] = flux[i] / cy0 """ If reading ascii data #with open("", 'r', encoding='utf-8') as inputHandle: numStr = "" num = 0.0 wav = 0.0 flx = 0.0 wavStr = "" flxStr = "" inLine = "" fields = [" " for i in range(2)] inFile = dataPath + "vega.dat" #Continuum rectification - here a factor: cy0 = 0.65 with open(inFile, 'r') as inputHandle: #No header - we'll figure out number of records on fly wave = [] flux = [] #for i in range(num): inLine = inputHandle.readline() while (inLine != ""): inLine = inputHandle.readline() #print(inLine) if not inLine: break inLine = inputHandle.readline() fields = inLine.split() wavStr = fields[0].strip(); flxStr = fields[1].strip() wav = 0.1 * float(wavStr) wave.append(wav) flx = cy0 * float(flxStr) flux.append(flx) """ pylab.plot(wave, flux, color='black') #Now get the synthetic spectrum pre-computed with ChromaStarPy modelPath = "Outputs/" #outPath = absPath + "Outputs/" numStr = "" num = 0.0 wavStr = "" flxStr = "" inLine = " " #fields = [" " for i in range(2)] """ runVers = "pyLoop" #Model atmosphere teffStr = "9550.0" loggStr = "3.95" logZStr = "-0.5" massStarStr = "2.0" xiTStr = "2.0" logHeFeStr = "0.0" logCOStr = "0.0" logAlphaFeStr = "0.0" #Spectrum synthesis lambdaStartStr = "429.0" lambdaStopStr = "439.0" lineThreshStr = "-3.0" voigtThreshStr = "-3.0" logGammaColStr = "0.0" logKapFudgeStr = "0.0" macroVStr = "2.0" #rotVStr = "275.0" #rotIStr = "5.0" rotVStr = "20.0" rotIStr = "0.0" RVStr = "0.0" strucStem = "Teff" + teffStr + "Logg" + loggStr + "Z" + logZStr + "M" + massStarStr+"xiT"+xiTStr + \ "HeFe" + logHeFeStr + "CO" + logCOStr + "AlfFe" + logAlphaFeStr + "v" + runVers strucFile = "struc." + strucStem + ".out" specFile = "spec." + strucStem + "L"+lambdaStartStr+"-"+lambdaStopStr+"xiT"+xiTStr+"LThr"+lineThreshStr+ \ "GamCol"+logGammaColStr+"Mac"+macroVStr+"Rot"+rotVStr+"-"+rotIStr+"RV"+RVStr + ".out" #with open("", 'r', encoding='utf-8') as inputHandle: inFile = modelPath + specFile; """ project = "Project" runVers = "Run" teff = 9550.0 logg = 3.95 log10ZScale = -0.5 lambdaStart = 429.0 lambdaStop = 439.0 fileStem = project + "-"\ + str(round(teff, 7)) + "-" + str(round(logg, 3)) + "-" + str(round(log10ZScale, 3))\ + "-" + str(round(lambdaStart, 5)) + "-" + str(round(lambdaStop, 5))\ + "-" + runVers inFile = modelPath + fileStem + ".spec.txt" invnAir = 1.0 / 1.000277 #// reciprocal of refractive index of air at STP #numStr = fields[0].strip() #first field is number of following records #num = int(numStr) waveMod = [] fluxMod = [] wav = 0.0 #//initialization wavStr = "" lblStr = "" with open(inFile, 'r') as inputHandle: #Expects number of records on first lines, then white space delimited columns of #wavelengths in nm and continuum rectified fluxes inLine = inputHandle.readline() #line of header print(inLine) inLine = inputHandle.readline() print(inLine) fields = inLine.split() #number of line IDs is last field: numLineIdsStr = fields[len(fields)-1] numLineIds = int(numLineIdsStr) - 1 # to be on safe side print("Recovered that there are " + numLineIdsStr + " lines to ID") inLine = inputHandle.readline() print(inLine) fields = inLine.split() #number of wavelengths in spectrum is last field: numWavsStr = fields[len(fields)-1] numWavs = int(numWavsStr) # to be on safe side print("Recovered that there are " + numWavsStr + " wavelengths") #One more line of header inLine = inputHandle.readline() #line of header print(inLine) waveMod = [0.0 for i in range(numWavs)] fluxMod = [0.0 for i in range(numWavs)] #Get the synthetic spectrum for i in range(numWavs): inLine = inputHandle.readline() fields = inLine.split() wavStr = fields[0].strip(); flxStr = fields[1].strip() wav = invnAir * float(wavStr) waveMod[i] = wav fluxMod[i] = float(flxStr) waveIds = [0.0 for i in range(numLineIds)] lblIds = ["" for i in range(numLineIds)] #Get the line IDs #Expects four white-space-delimited fields: # wavelength, element, ion. stage, and rounded wavelength #Another line of header for line id section inLine = inputHandle.readline() #line of header print(inLine) for i in range(numLineIds): inLine = inputHandle.readline() fields = inLine.split() wavStr = fields[0].strip() wav = invnAir * float(wavStr) waveIds[i] = wav lblStr = fields[1].strip() + " " + fields[2].strip() + " " + fields[3].strip() lblIds[i] = lblStr """ #If we do NOT know number of records: #for i in inputHandle: #doesn't work - 0 iterations while (inLine != ""): inLine = inputHandle.readline() if not inLine: break #print(inLine) fields = inLine.split() wavStr = fields[0].strip(); flxStr = fields[1].strip() wav = invnAir * float(wavStr) waveMod.append(wav) fluxMod.append(float(flxStr)) """ #Interpolate syntehtic spectrum onto uniform wavelength grid and convolve with #instrumental profile accounting for finite spectral resolving power, R delLam = 0.01 #sampling in nm numWavs2 = (waveMod[numWavs-1] - waveMod[0]) / delLam numWavs2 = int(numWavs2) wave2 = [0.0 for i in range(numWavs2)] for i in range(numWavs2): ii = float(i) wave2[i] = waveMod[0] + ii*delLam #necessary?? flux2 = [0.0 for i in range(numWavs2)] #interpolate the flux onto the new wavelength scale flux2 = numpy.interp(wave2, waveMod, fluxMod) specR = 2000 #approximate STELIB value midWave = (waveMod[numWavs-1] + waveMod[0]) / 2.0 deltaR = midWave / specR #resolution element in nm sigma = deltaR /delLam #resolution element in array elements fwhm = 2.0 * sigma #length of array holding Gaussian in array element space if computing Gaussian from -3.5 to +3.5 sigma length = int(7.0 * sigma) #Make a Gaussian instrumental profile gaussian = Gauss2.gauss2(fwhm, length) #Convolve the uniformly sampled synthetic spectrum with the instrumental profile flux2s = numpy.convolve(flux2, gaussian, mode='same') #plot the spectrum #plt.title('Synthetic spectrum') plt.ylabel('$F_\lambda/F^C_\lambda$') plt.xlabel('$\lambda$ (nm)') xMin = min(waveMod) xMax = max(waveMod) pylab.xlim(xMin, xMax) pylab.ylim(0.0, 1.2) #pylab.plot(waveMod, fluxMod, color="gray") pylab.plot(wave2, flux2, color=(0.6, 0.6, 0.6)) pylab.plot(wave2, flux2s, color=(0.3, 0.3, 0.3)) #add the line IDs foundOne = False # work around H I line components being multiply labeled in line list for i in range(numLineIds): if "H I" in lblIds[i] and foundOne == False: foundOne = True thisLam = waveIds[i] thisLbl = lblIds[i] xPoint = [thisLam, thisLam] yPoint = [0.75, 0.8] pylab.plot(xPoint, yPoint, color='black') pylab.text(thisLam, 1.1, thisLbl, rotation=270) #Save as encapsulated postscript (eps) for LaTex epsName = fileStem + ".eps" plt.savefig(epsName, format='eps', dpi=1000)
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "pylab.xlim", "astropy.io.fits.open", "pylab.ylim", "pylab.text", "numpy.interp", "numpy.convolve", "matplotlib.pyplot.xlabel", "pylab.plot", "Gauss2.gauss2" ]
[((699, 716), 'astropy.io.fits.open', 'fits.open', (['inFile'], {}), '(inFile)\n', (708, 716), False, 'from astropy.io import fits\n'), ((2183, 2220), 'pylab.plot', 'pylab.plot', (['wave', 'flux'], {'color': '"""black"""'}), "(wave, flux, color='black')\n", (2193, 2220), False, 'import pylab\n'), ((7181, 7218), 'numpy.interp', 'numpy.interp', (['wave2', 'waveMod', 'fluxMod'], {}), '(wave2, waveMod, fluxMod)\n', (7193, 7218), False, 'import numpy\n'), ((7634, 7661), 'Gauss2.gauss2', 'Gauss2.gauss2', (['fwhm', 'length'], {}), '(fwhm, length)\n', (7647, 7661), False, 'import Gauss2\n'), ((7756, 7800), 'numpy.convolve', 'numpy.convolve', (['flux2', 'gaussian'], {'mode': '"""same"""'}), "(flux2, gaussian, mode='same')\n", (7770, 7800), False, 'import numpy\n'), ((7868, 7907), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$F_\\\\lambda/F^C_\\\\lambda$"""'], {}), "('$F_\\\\lambda/F^C_\\\\lambda$')\n", (7878, 7907), True, 'import matplotlib.pyplot as plt\n'), ((7907, 7936), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$\\\\lambda$ (nm)"""'], {}), "('$\\\\lambda$ (nm)')\n", (7917, 7936), True, 'import matplotlib.pyplot as plt\n'), ((7979, 8001), 'pylab.xlim', 'pylab.xlim', (['xMin', 'xMax'], {}), '(xMin, xMax)\n', (7989, 8001), False, 'import pylab\n'), ((8003, 8023), 'pylab.ylim', 'pylab.ylim', (['(0.0)', '(1.2)'], {}), '(0.0, 1.2)\n', (8013, 8023), False, 'import pylab\n'), ((8078, 8125), 'pylab.plot', 'pylab.plot', (['wave2', 'flux2'], {'color': '(0.6, 0.6, 0.6)'}), '(wave2, flux2, color=(0.6, 0.6, 0.6))\n', (8088, 8125), False, 'import pylab\n'), ((8127, 8175), 'pylab.plot', 'pylab.plot', (['wave2', 'flux2s'], {'color': '(0.3, 0.3, 0.3)'}), '(wave2, flux2s, color=(0.3, 0.3, 0.3))\n', (8137, 8175), False, 'import pylab\n'), ((8705, 8749), 'matplotlib.pyplot.savefig', 'plt.savefig', (['epsName'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(epsName, format='eps', dpi=1000)\n", (8716, 8749), True, 'import matplotlib.pyplot as plt\n'), ((8524, 8565), 'pylab.plot', 'pylab.plot', (['xPoint', 'yPoint'], {'color': '"""black"""'}), "(xPoint, yPoint, color='black')\n", (8534, 8565), False, 'import pylab\n'), ((8575, 8622), 'pylab.text', 'pylab.text', (['thisLam', '(1.1)', 'thisLbl'], {'rotation': '(270)'}), '(thisLam, 1.1, thisLbl, rotation=270)\n', (8585, 8622), False, 'import pylab\n')]
from scipy.linalg import lstsq import pandas as pd import numpy as np import argparse def landmark_registration_ls(pts_f1, pts_f2, out_f, delimiter="\t"): points1 = pd.read_csv(pts_f1, delimiter=delimiter) points2 = pd.read_csv(pts_f2, delimiter=delimiter) src = np.concatenate([np.array(points1['x']).reshape([-1,1]), np.array(points1['y']).reshape([-1,1])], axis=-1) dst = np.concatenate([np.array(points2['x']).reshape([-1,1]), np.array(points2['y']).reshape([-1,1])], axis=-1) A = np.zeros((src.size,6)) A[0:src.shape[0],[0,1]] = src A[0:src.shape[0],2] = 1 A[src.shape[0]:,[3,4]] = src A[src.shape[0]:,5] = 1 b = dst.T.flatten().astype('float64') x = lstsq(A,b) tmat = np.eye(3) tmat[0,:] = x[0].take([0,1,2]) tmat[1,:] = x[0].take([3,4,5]) pd.DataFrame(tmat).to_csv(out_f, header=None, index=False, sep="\t") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Estimate transformation from points using least squares") parser.add_argument("fn_pts1", help="File name src points") parser.add_argument("fn_pts2", help="File name dst points") parser.add_argument("fn_tmat", help="File name transformation matrix") args = parser.parse_args() landmark_registration_ls(args.fn_pts1, args.fn_pts2, args.fn_tmat)
[ "pandas.DataFrame", "argparse.ArgumentParser", "pandas.read_csv", "numpy.zeros", "numpy.array", "scipy.linalg.lstsq", "numpy.eye" ]
[((175, 215), 'pandas.read_csv', 'pd.read_csv', (['pts_f1'], {'delimiter': 'delimiter'}), '(pts_f1, delimiter=delimiter)\n', (186, 215), True, 'import pandas as pd\n'), ((230, 270), 'pandas.read_csv', 'pd.read_csv', (['pts_f2'], {'delimiter': 'delimiter'}), '(pts_f2, delimiter=delimiter)\n', (241, 270), True, 'import pandas as pd\n'), ((619, 642), 'numpy.zeros', 'np.zeros', (['(src.size, 6)'], {}), '((src.size, 6))\n', (627, 642), True, 'import numpy as np\n'), ((814, 825), 'scipy.linalg.lstsq', 'lstsq', (['A', 'b'], {}), '(A, b)\n', (819, 825), False, 'from scipy.linalg import lstsq\n'), ((841, 850), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (847, 850), True, 'import numpy as np\n'), ((1037, 1136), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Estimate transformation from points using least squares"""'}), "(description=\n 'Estimate transformation from points using least squares')\n", (1060, 1136), False, 'import argparse\n'), ((925, 943), 'pandas.DataFrame', 'pd.DataFrame', (['tmat'], {}), '(tmat)\n', (937, 943), True, 'import pandas as pd\n'), ((298, 320), 'numpy.array', 'np.array', (["points1['x']"], {}), "(points1['x'])\n", (306, 320), True, 'import numpy as np\n'), ((365, 387), 'numpy.array', 'np.array', (["points1['y']"], {}), "(points1['y'])\n", (373, 387), True, 'import numpy as np\n'), ((467, 489), 'numpy.array', 'np.array', (["points2['x']"], {}), "(points2['x'])\n", (475, 489), True, 'import numpy as np\n'), ((534, 556), 'numpy.array', 'np.array', (["points2['y']"], {}), "(points2['y'])\n", (542, 556), True, 'import numpy as np\n')]
""" # Copyright 2020 Adobe # All Rights Reserved. # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. """ from src.models.model_image_translation import ResUnetGenerator, VGGLoss import torch import torch.nn as nn from tensorboardX import SummaryWriter import time import numpy as np import cv2 import os, glob from src.dataset.image_translation.image_translation_dataset import vis_landmark_on_img, vis_landmark_on_img98, vis_landmark_on_img74 from thirdparty.AdaptiveWingLoss.core import models from thirdparty.AdaptiveWingLoss.utils.utils import get_preds_fromhm import face_alignment device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Image_translation_block(): def __init__(self, opt_parser, single_test=False): print('Run on device {}'.format(device)) # for key in vars(opt_parser).keys(): # print(key, ':', vars(opt_parser)[key]) self.opt_parser = opt_parser # model if(opt_parser.add_audio_in): self.G = ResUnetGenerator(input_nc=7, output_nc=3, num_downs=6, use_dropout=False) else: self.G = ResUnetGenerator(input_nc=6, output_nc=3, num_downs=6, use_dropout=False) if (opt_parser.load_G_name != ''): ckpt = torch.load(opt_parser.load_G_name) try: self.G.load_state_dict(ckpt['G']) except: tmp = nn.DataParallel(self.G) tmp.load_state_dict(ckpt['G']) self.G.load_state_dict(tmp.module.state_dict()) del tmp if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs in G mode!") self.G = nn.DataParallel(self.G) self.G.to(device) if(not single_test): # dataset if(opt_parser.use_vox_dataset == 'raw'): if(opt_parser.comb_fan_awing): from src.dataset.image_translation.image_translation_dataset import \ image_translation_raw74_dataset as image_translation_dataset elif(opt_parser.add_audio_in): from src.dataset.image_translation.image_translation_dataset import image_translation_raw98_with_audio_dataset as \ image_translation_dataset else: from src.dataset.image_translation.image_translation_dataset import image_translation_raw98_dataset as \ image_translation_dataset else: from src.dataset.image_translation.image_translation_dataset import image_translation_preprocessed98_dataset as \ image_translation_dataset self.dataset = image_translation_dataset(num_frames=opt_parser.num_frames) self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt_parser.batch_size, shuffle=True, num_workers=opt_parser.num_workers) # criterion self.criterionL1 = nn.L1Loss() self.criterionVGG = VGGLoss() if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs in VGG model!") self.criterionVGG = nn.DataParallel(self.criterionVGG) self.criterionVGG.to(device) # optimizer self.optimizer = torch.optim.Adam(self.G.parameters(), lr=opt_parser.lr, betas=(0.5, 0.999)) # writer if(opt_parser.write): self.writer = SummaryWriter(log_dir=os.path.join(opt_parser.log_dir, opt_parser.name)) self.count = 0 # =========================================================== # online landmark alignment : Awing # =========================================================== PRETRAINED_WEIGHTS = 'thirdparty/AdaptiveWingLoss/ckpt/WFLW_4HG.pth' GRAY_SCALE = False HG_BLOCKS = 4 END_RELU = False NUM_LANDMARKS = 98 self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model_ft = models.FAN(HG_BLOCKS, END_RELU, GRAY_SCALE, NUM_LANDMARKS) checkpoint = torch.load(PRETRAINED_WEIGHTS) if 'state_dict' not in checkpoint: model_ft.load_state_dict(checkpoint) else: pretrained_weights = checkpoint['state_dict'] model_weights = model_ft.state_dict() pretrained_weights = {k: v for k, v in pretrained_weights.items() \ if k in model_weights} model_weights.update(pretrained_weights) model_ft.load_state_dict(model_weights) print('Load AWing model sucessfully') if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs for AWing!") self.fa_model = nn.DataParallel(model_ft).to(self.device).eval() else: self.fa_model = model_ft.to(self.device).eval() # =========================================================== # online landmark alignment : FAN # =========================================================== if(opt_parser.comb_fan_awing): if(opt_parser.fan_2or3D == '2D'): self.predictor = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, device='cuda' if torch.cuda.is_available() else "cpu", flip_input=True) else: self.predictor = face_alignment.FaceAlignment(face_alignment.LandmarksType._3D, device='cuda' if torch.cuda.is_available() else "cpu", flip_input=True) def __train_pass__(self, epoch, is_training=True): st_epoch = time.time() if(is_training): self.G.train() status = 'TRAIN' else: self.G.eval() status = 'EVAL' g_time = 0.0 for i, batch in enumerate(self.dataloader): if(i >= len(self.dataloader)-2): break st_batch = time.time() if(self.opt_parser.comb_fan_awing): image_in, image_out, fan_pred_landmarks = batch fan_pred_landmarks = fan_pred_landmarks.reshape(-1, 68, 3).detach().cpu().numpy() elif(self.opt_parser.add_audio_in): image_in, image_out, audio_in = batch audio_in = audio_in.reshape(-1, 1, 256, 256).to(device) else: image_in, image_out = batch with torch.no_grad(): # # online landmark (AwingNet) image_in, image_out = \ image_in.reshape(-1, 3, 256, 256).to(device), image_out.reshape(-1, 3, 256, 256).to(device) inputs = image_out outputs, boundary_channels = self.fa_model(inputs) pred_heatmap = outputs[-1][:, :-1, :, :].detach().cpu() pred_landmarks, _ = get_preds_fromhm(pred_heatmap) pred_landmarks = pred_landmarks.numpy() * 4 # online landmark (FAN) -> replace jaw + eye brow in AwingNet if(self.opt_parser.comb_fan_awing): fl_jaw_eyebrow = fan_pred_landmarks[:, 0:27, 0:2] fl_rest = pred_landmarks[:, 51:, :] pred_landmarks = np.concatenate([fl_jaw_eyebrow, fl_rest], axis=1).astype(np.int) # draw landmark on while bg img_fls = [] for pred_fl in pred_landmarks: img_fl = np.ones(shape=(256, 256, 3)) * 255.0 if(self.opt_parser.comb_fan_awing): img_fl = vis_landmark_on_img74(img_fl, pred_fl) # 74x2 else: img_fl = vis_landmark_on_img98(img_fl, pred_fl) # 98x2 img_fls.append(img_fl.transpose((2, 0, 1))) img_fls = np.stack(img_fls, axis=0).astype(np.float32) / 255.0 image_fls_in = torch.tensor(img_fls, requires_grad=False).to(device) if(self.opt_parser.add_audio_in): # print(image_fls_in.shape, image_in.shape, audio_in.shape) image_in = torch.cat([image_fls_in, image_in, audio_in], dim=1) else: image_in = torch.cat([image_fls_in, image_in], dim=1) # image_in, image_out = \ # image_in.reshape(-1, 6, 256, 256).to(device), image_out.reshape(-1, 3, 256, 256).to(device) # image2image net fp g_out = self.G(image_in) g_out = torch.tanh(g_out) loss_l1 = self.criterionL1(g_out, image_out) loss_vgg, loss_style = self.criterionVGG(g_out, image_out, style=True) loss_vgg, loss_style = torch.mean(loss_vgg), torch.mean(loss_style) loss = loss_l1 + loss_vgg + loss_style if(is_training): self.optimizer.zero_grad() loss.backward() self.optimizer.step() # log if(self.opt_parser.write): self.writer.add_scalar('loss', loss.cpu().detach().numpy(), self.count) self.writer.add_scalar('loss_l1', loss_l1.cpu().detach().numpy(), self.count) self.writer.add_scalar('loss_vgg', loss_vgg.cpu().detach().numpy(), self.count) self.count += 1 # save image to track training process if (i % self.opt_parser.jpg_freq == 0): vis_in = np.concatenate([image_in[0, 3:6].cpu().detach().numpy().transpose((1, 2, 0)), image_in[0, 0:3].cpu().detach().numpy().transpose((1, 2, 0))], axis=1) vis_out = np.concatenate([image_out[0].cpu().detach().numpy().transpose((1, 2, 0)), g_out[0].cpu().detach().numpy().transpose((1, 2, 0))], axis=1) vis = np.concatenate([vis_in, vis_out], axis=0) try: os.makedirs(os.path.join(self.opt_parser.jpg_dir, self.opt_parser.name)) except: pass cv2.imwrite(os.path.join(self.opt_parser.jpg_dir, self.opt_parser.name, 'e{:03d}_b{:04d}.jpg'.format(epoch, i)), vis * 255.0) # save ckpt if (i % self.opt_parser.ckpt_last_freq == 0): self.__save_model__('last', epoch) print("Epoch {}, Batch {}/{}, loss {:.4f}, l1 {:.4f}, vggloss {:.4f}, styleloss {:.4f} time {:.4f}".format( epoch, i, len(self.dataset) // self.opt_parser.batch_size, loss.cpu().detach().numpy(), loss_l1.cpu().detach().numpy(), loss_vgg.cpu().detach().numpy(), loss_style.cpu().detach().numpy(), time.time() - st_batch)) g_time += time.time() - st_batch if(self.opt_parser.test_speed): if(i >= 100): break print('Epoch time usage:', time.time() - st_epoch, 'I/O time usage:', time.time() - st_epoch - g_time, '\n=========================') if(self.opt_parser.test_speed): exit(0) if(epoch % self.opt_parser.ckpt_epoch_freq == 0): self.__save_model__('{:02d}'.format(epoch), epoch) def __save_model__(self, save_type, epoch): try: os.makedirs(os.path.join(self.opt_parser.ckpt_dir, self.opt_parser.name)) except: pass if (self.opt_parser.write): torch.save({ 'G': self.G.state_dict(), 'opt': self.optimizer, 'epoch': epoch }, os.path.join(self.opt_parser.ckpt_dir, self.opt_parser.name, 'ckpt_{}.pth'.format(save_type))) def train(self): for epoch in range(self.opt_parser.nepoch): self.__train_pass__(epoch, is_training=True) def test(self): if (self.opt_parser.use_vox_dataset == 'raw'): if(self.opt_parser.add_audio_in): from src.dataset.image_translation.image_translation_dataset import \ image_translation_raw98_with_audio_test_dataset as image_translation_test_dataset else: from src.dataset.image_translation.image_translation_dataset import image_translation_raw98_test_dataset as image_translation_test_dataset else: from src.dataset.image_translation.image_translation_dataset import image_translation_preprocessed98_test_dataset as image_translation_test_dataset self.dataset = image_translation_test_dataset(num_frames=self.opt_parser.num_frames) self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=1, shuffle=True, num_workers=self.opt_parser.num_workers) self.G.eval() for i, batch in enumerate(self.dataloader): print(i, 50) if (i > 50): break if (self.opt_parser.add_audio_in): image_in, image_out, audio_in = batch audio_in = audio_in.reshape(-1, 1, 256, 256).to(device) else: image_in, image_out = batch # # online landmark (AwingNet) with torch.no_grad(): image_in, image_out = \ image_in.reshape(-1, 3, 256, 256).to(device), image_out.reshape(-1, 3, 256, 256).to(device) pred_landmarks = [] for j in range(image_in.shape[0] // 16): inputs = image_out[j*16:j*16+16] outputs, boundary_channels = self.fa_model(inputs) pred_heatmap = outputs[-1][:, :-1, :, :].detach().cpu() pred_landmark, _ = get_preds_fromhm(pred_heatmap) pred_landmarks.append(pred_landmark.numpy() * 4) pred_landmarks = np.concatenate(pred_landmarks, axis=0) # draw landmark on while bg img_fls = [] for pred_fl in pred_landmarks: img_fl = np.ones(shape=(256, 256, 3)) * 255.0 img_fl = vis_landmark_on_img98(img_fl, pred_fl) # 98x2 img_fls.append(img_fl.transpose((2, 0, 1))) img_fls = np.stack(img_fls, axis=0).astype(np.float32) / 255.0 image_fls_in = torch.tensor(img_fls, requires_grad=False).to(device) if (self.opt_parser.add_audio_in): # print(image_fls_in.shape, image_in.shape, audio_in.shape) image_in = torch.cat([image_fls_in, image_in[0:image_fls_in.shape[0]], audio_in[0:image_fls_in.shape[0]]], dim=1) else: image_in = torch.cat([image_fls_in, image_in[0:image_fls_in.shape[0]]], dim=1) # normal 68 test dataset # image_in, image_out = image_in.reshape(-1, 6, 256, 256), image_out.reshape(-1, 3, 256, 256) # random single frame # cv2.imwrite('random_img_{}.jpg'.format(i), np.swapaxes(image_out[5].numpy(),0, 2)*255.0) image_in, image_out = image_in.to(device), image_out.to(device) writer = cv2.VideoWriter('tmp_{:04d}.mp4'.format(i), cv2.VideoWriter_fourcc(*'mjpg'), 25, (256*4, 256)) for j in range(image_in.shape[0] // 16): g_out = self.G(image_in[j*16:j*16+16]) g_out = torch.tanh(g_out) # norm 68 pts # g_out = np.swapaxes(g_out.cpu().detach().numpy(), 1, 3) # ref_out = np.swapaxes(image_out[j*16:j*16+16].cpu().detach().numpy(), 1, 3) # ref_in = np.swapaxes(image_in[j*16:j*16+16, 3:6, :, :].cpu().detach().numpy(), 1, 3) # fls_in = np.swapaxes(image_in[j * 16:j * 16 + 16, 0:3, :, :].cpu().detach().numpy(), 1, 3) g_out = g_out.cpu().detach().numpy().transpose((0, 2, 3, 1)) g_out[g_out < 0] = 0 ref_out = image_out[j * 16:j * 16 + 16].cpu().detach().numpy().transpose((0, 2, 3, 1)) ref_in = image_in[j * 16:j * 16 + 16, 3:6, :, :].cpu().detach().numpy().transpose((0, 2, 3, 1)) fls_in = image_in[j * 16:j * 16 + 16, 0:3, :, :].cpu().detach().numpy().transpose((0, 2, 3, 1)) for k in range(g_out.shape[0]): frame = np.concatenate((ref_in[k], g_out[k], fls_in[k], ref_out[k]), axis=1) * 255.0 writer.write(frame.astype(np.uint8)) writer.release() os.system('ffmpeg -y -i tmp_{:04d}.mp4 -pix_fmt yuv420p random_{:04d}.mp4'.format(i, i)) os.system('rm tmp_{:04d}.mp4'.format(i)) def single_test(self, jpg=None, fls=None, filename=None, prefix='', grey_only=False): import time st = time.time() self.G.eval() if(jpg is None): jpg = glob.glob1(self.opt_parser.single_test, '*.jpg')[0] jpg = cv2.imread(os.path.join(self.opt_parser.single_test, jpg)) if(fls is None): fls = glob.glob1(self.opt_parser.single_test, '*.txt')[0] fls = np.loadtxt(os.path.join(self.opt_parser.single_test, fls)) fls = fls * 95 fls[:, 0::3] += 130 fls[:, 1::3] += 80 writer = cv2.VideoWriter('out.mp4', cv2.VideoWriter_fourcc(*'mjpg'), 62.5, (256 * 3, 256)) for i, frame in enumerate(fls): img_fl = np.ones(shape=(256, 256, 3)) * 255 fl = frame.astype(int) img_fl = vis_landmark_on_img(img_fl, np.reshape(fl, (68, 3))) frame = np.concatenate((img_fl, jpg), axis=2).astype(np.float32)/255.0 image_in, image_out = frame.transpose((2, 0, 1)), np.zeros(shape=(3, 256, 256)) # image_in, image_out = frame.transpose((2, 1, 0)), np.zeros(shape=(3, 256, 256)) image_in, image_out = torch.tensor(image_in, requires_grad=False), \ torch.tensor(image_out, requires_grad=False) image_in, image_out = image_in.reshape(-1, 6, 256, 256), image_out.reshape(-1, 3, 256, 256) image_in, image_out = image_in.to(device), image_out.to(device) g_out = self.G(image_in) g_out = torch.tanh(g_out) g_out = g_out.cpu().detach().numpy().transpose((0, 2, 3, 1)) g_out[g_out < 0] = 0 ref_in = image_in[:, 3:6, :, :].cpu().detach().numpy().transpose((0, 2, 3, 1)) fls_in = image_in[:, 0:3, :, :].cpu().detach().numpy().transpose((0, 2, 3, 1)) # g_out = g_out.cpu().detach().numpy().transpose((0, 3, 2, 1)) # g_out[g_out < 0] = 0 # ref_in = image_in[:, 3:6, :, :].cpu().detach().numpy().transpose((0, 3, 2, 1)) # fls_in = image_in[:, 0:3, :, :].cpu().detach().numpy().transpose((0, 3, 2, 1)) if(grey_only): g_out_grey =np.mean(g_out, axis=3, keepdims=True) g_out[:, :, :, 0:1] = g_out[:, :, :, 1:2] = g_out[:, :, :, 2:3] = g_out_grey for i in range(g_out.shape[0]): frame = np.concatenate((ref_in[i], g_out[i], fls_in[i]), axis=1) * 255.0 writer.write(frame.astype(np.uint8)) writer.release() print('Time - only video:', time.time() - st) if(filename is None): filename = 'v' os.system('ffmpeg -loglevel error -y -i out.mp4 -i {} -pix_fmt yuv420p -strict -2 examples/{}_{}.mp4'.format( 'examples/'+filename[9:-16]+'.wav', prefix, filename[:-4])) # os.system('rm out.mp4') print('Time - ffmpeg add audio:', time.time() - st)
[ "thirdparty.AdaptiveWingLoss.core.models.FAN", "cv2.VideoWriter_fourcc", "torch.cat", "numpy.ones", "torch.cuda.device_count", "src.dataset.image_translation.image_translation_dataset.image_translation_raw98_dataset", "src.dataset.image_translation.image_translation_dataset.vis_landmark_on_img98", "nu...
[((732, 757), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (755, 757), False, 'import torch\n'), ((6360, 6371), 'time.time', 'time.time', ([], {}), '()\n', (6369, 6371), False, 'import time\n'), ((13183, 13252), 'src.dataset.image_translation.image_translation_dataset.image_translation_raw98_test_dataset', 'image_translation_test_dataset', ([], {'num_frames': 'self.opt_parser.num_frames'}), '(num_frames=self.opt_parser.num_frames)\n', (13213, 13252), True, 'from src.dataset.image_translation.image_translation_dataset import image_translation_raw98_test_dataset as image_translation_test_dataset\n'), ((13279, 13393), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['self.dataset'], {'batch_size': '(1)', 'shuffle': '(True)', 'num_workers': 'self.opt_parser.num_workers'}), '(self.dataset, batch_size=1, shuffle=True,\n num_workers=self.opt_parser.num_workers)\n', (13306, 13393), False, 'import torch\n'), ((17572, 17583), 'time.time', 'time.time', ([], {}), '()\n', (17581, 17583), False, 'import time\n'), ((1121, 1194), 'src.models.model_image_translation.ResUnetGenerator', 'ResUnetGenerator', ([], {'input_nc': '(7)', 'output_nc': '(3)', 'num_downs': '(6)', 'use_dropout': '(False)'}), '(input_nc=7, output_nc=3, num_downs=6, use_dropout=False)\n', (1137, 1194), False, 'from src.models.model_image_translation import ResUnetGenerator, VGGLoss\n'), ((1230, 1303), 'src.models.model_image_translation.ResUnetGenerator', 'ResUnetGenerator', ([], {'input_nc': '(6)', 'output_nc': '(3)', 'num_downs': '(6)', 'use_dropout': '(False)'}), '(input_nc=6, output_nc=3, num_downs=6, use_dropout=False)\n', (1246, 1303), False, 'from src.models.model_image_translation import ResUnetGenerator, VGGLoss\n'), ((1367, 1401), 'torch.load', 'torch.load', (['opt_parser.load_G_name'], {}), '(opt_parser.load_G_name)\n', (1377, 1401), False, 'import torch\n'), ((1682, 1707), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (1705, 1707), False, 'import torch\n'), ((1811, 1834), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.G'], {}), '(self.G)\n', (1826, 1834), True, 'import torch.nn as nn\n'), ((2837, 2896), 'src.dataset.image_translation.image_translation_dataset.image_translation_raw98_dataset', 'image_translation_dataset', ([], {'num_frames': 'opt_parser.num_frames'}), '(num_frames=opt_parser.num_frames)\n', (2862, 2896), True, 'from src.dataset.image_translation.image_translation_dataset import image_translation_raw98_dataset as image_translation_dataset\n'), ((2927, 3056), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['self.dataset'], {'batch_size': 'opt_parser.batch_size', 'shuffle': '(True)', 'num_workers': 'opt_parser.num_workers'}), '(self.dataset, batch_size=opt_parser.batch_size,\n shuffle=True, num_workers=opt_parser.num_workers)\n', (2954, 3056), False, 'import torch\n'), ((3283, 3294), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (3292, 3294), True, 'import torch.nn as nn\n'), ((3327, 3336), 'src.models.model_image_translation.VGGLoss', 'VGGLoss', ([], {}), '()\n', (3334, 3336), False, 'from src.models.model_image_translation import ResUnetGenerator, VGGLoss\n'), ((4413, 4471), 'thirdparty.AdaptiveWingLoss.core.models.FAN', 'models.FAN', (['HG_BLOCKS', 'END_RELU', 'GRAY_SCALE', 'NUM_LANDMARKS'], {}), '(HG_BLOCKS, END_RELU, GRAY_SCALE, NUM_LANDMARKS)\n', (4423, 4471), False, 'from thirdparty.AdaptiveWingLoss.core import models\n'), ((4498, 4528), 'torch.load', 'torch.load', (['PRETRAINED_WEIGHTS'], {}), '(PRETRAINED_WEIGHTS)\n', (4508, 4528), False, 'import torch\n'), ((6685, 6696), 'time.time', 'time.time', ([], {}), '()\n', (6694, 6696), False, 'import time\n'), ((9182, 9199), 'torch.tanh', 'torch.tanh', (['g_out'], {}), '(g_out)\n', (9192, 9199), False, 'import torch\n'), ((18087, 18118), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mjpg'"], {}), "(*'mjpg')\n", (18109, 18118), False, 'import cv2\n'), ((19018, 19035), 'torch.tanh', 'torch.tanh', (['g_out'], {}), '(g_out)\n', (19028, 19035), False, 'import torch\n'), ((1744, 1769), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (1767, 1769), False, 'import torch\n'), ((3352, 3377), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (3375, 3377), False, 'import torch\n'), ((3503, 3537), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.criterionVGG'], {}), '(self.criterionVGG)\n', (3518, 3537), True, 'import torch.nn as nn\n'), ((5086, 5111), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (5109, 5111), False, 'import torch\n'), ((7162, 7177), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7175, 7177), False, 'import torch\n'), ((7588, 7618), 'thirdparty.AdaptiveWingLoss.utils.utils.get_preds_fromhm', 'get_preds_fromhm', (['pred_heatmap'], {}), '(pred_heatmap)\n', (7604, 7618), False, 'from thirdparty.AdaptiveWingLoss.utils.utils import get_preds_fromhm\n'), ((8801, 8853), 'torch.cat', 'torch.cat', (['[image_fls_in, image_in, audio_in]'], {'dim': '(1)'}), '([image_fls_in, image_in, audio_in], dim=1)\n', (8810, 8853), False, 'import torch\n'), ((8899, 8941), 'torch.cat', 'torch.cat', (['[image_fls_in, image_in]'], {'dim': '(1)'}), '([image_fls_in, image_in], dim=1)\n', (8908, 8941), False, 'import torch\n'), ((9377, 9397), 'torch.mean', 'torch.mean', (['loss_vgg'], {}), '(loss_vgg)\n', (9387, 9397), False, 'import torch\n'), ((9399, 9421), 'torch.mean', 'torch.mean', (['loss_style'], {}), '(loss_style)\n', (9409, 9421), False, 'import torch\n'), ((10531, 10572), 'numpy.concatenate', 'np.concatenate', (['[vis_in, vis_out]'], {'axis': '(0)'}), '([vis_in, vis_out], axis=0)\n', (10545, 10572), True, 'import numpy as np\n'), ((11474, 11485), 'time.time', 'time.time', ([], {}), '()\n', (11483, 11485), False, 'import time\n'), ((11635, 11646), 'time.time', 'time.time', ([], {}), '()\n', (11644, 11646), False, 'import time\n'), ((12010, 12070), 'os.path.join', 'os.path.join', (['self.opt_parser.ckpt_dir', 'self.opt_parser.name'], {}), '(self.opt_parser.ckpt_dir, self.opt_parser.name)\n', (12022, 12070), False, 'import os, glob\n'), ((13996, 14011), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14009, 14011), False, 'import torch\n'), ((14631, 14669), 'numpy.concatenate', 'np.concatenate', (['pred_landmarks'], {'axis': '(0)'}), '(pred_landmarks, axis=0)\n', (14645, 14669), True, 'import numpy as np\n'), ((14866, 14904), 'src.dataset.image_translation.image_translation_dataset.vis_landmark_on_img98', 'vis_landmark_on_img98', (['img_fl', 'pred_fl'], {}), '(img_fl, pred_fl)\n', (14887, 14904), False, 'from src.dataset.image_translation.image_translation_dataset import vis_landmark_on_img, vis_landmark_on_img98, vis_landmark_on_img74\n'), ((15280, 15387), 'torch.cat', 'torch.cat', (['[image_fls_in, image_in[0:image_fls_in.shape[0]], audio_in[0:image_fls_in.\n shape[0]]]'], {'dim': '(1)'}), '([image_fls_in, image_in[0:image_fls_in.shape[0]], audio_in[0:\n image_fls_in.shape[0]]], dim=1)\n', (15289, 15387), False, 'import torch\n'), ((15504, 15571), 'torch.cat', 'torch.cat', (['[image_fls_in, image_in[0:image_fls_in.shape[0]]]'], {'dim': '(1)'}), '([image_fls_in, image_in[0:image_fls_in.shape[0]]], dim=1)\n', (15513, 15571), False, 'import torch\n'), ((15997, 16028), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mjpg'"], {}), "(*'mjpg')\n", (16019, 16028), False, 'import cv2\n'), ((16181, 16198), 'torch.tanh', 'torch.tanh', (['g_out'], {}), '(g_out)\n', (16191, 16198), False, 'import torch\n'), ((17650, 17698), 'glob.glob1', 'glob.glob1', (['self.opt_parser.single_test', '"""*.jpg"""'], {}), "(self.opt_parser.single_test, '*.jpg')\n", (17660, 17698), False, 'import os, glob\n'), ((17731, 17777), 'os.path.join', 'os.path.join', (['self.opt_parser.single_test', 'jpg'], {}), '(self.opt_parser.single_test, jpg)\n', (17743, 17777), False, 'import os, glob\n'), ((17823, 17871), 'glob.glob1', 'glob.glob1', (['self.opt_parser.single_test', '"""*.txt"""'], {}), "(self.opt_parser.single_test, '*.txt')\n", (17833, 17871), False, 'import os, glob\n'), ((17904, 17950), 'os.path.join', 'os.path.join', (['self.opt_parser.single_test', 'fls'], {}), '(self.opt_parser.single_test, fls)\n', (17916, 17950), False, 'import os, glob\n'), ((18205, 18233), 'numpy.ones', 'np.ones', ([], {'shape': '(256, 256, 3)'}), '(shape=(256, 256, 3))\n', (18212, 18233), True, 'import numpy as np\n'), ((18324, 18347), 'numpy.reshape', 'np.reshape', (['fl', '(68, 3)'], {}), '(fl, (68, 3))\n', (18334, 18347), True, 'import numpy as np\n'), ((18495, 18524), 'numpy.zeros', 'np.zeros', ([], {'shape': '(3, 256, 256)'}), '(shape=(3, 256, 256))\n', (18503, 18524), True, 'import numpy as np\n'), ((18653, 18696), 'torch.tensor', 'torch.tensor', (['image_in'], {'requires_grad': '(False)'}), '(image_in, requires_grad=False)\n', (18665, 18696), False, 'import torch\n'), ((18734, 18778), 'torch.tensor', 'torch.tensor', (['image_out'], {'requires_grad': '(False)'}), '(image_out, requires_grad=False)\n', (18746, 18778), False, 'import torch\n'), ((19677, 19714), 'numpy.mean', 'np.mean', (['g_out'], {'axis': '(3)', 'keepdims': '(True)'}), '(g_out, axis=3, keepdims=True)\n', (19684, 19714), True, 'import numpy as np\n'), ((20058, 20069), 'time.time', 'time.time', ([], {}), '()\n', (20067, 20069), False, 'import time\n'), ((20413, 20424), 'time.time', 'time.time', ([], {}), '()\n', (20422, 20424), False, 'import time\n'), ((1511, 1534), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.G'], {}), '(self.G)\n', (1526, 1534), True, 'import torch.nn as nn\n'), ((3418, 3443), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (3441, 3443), False, 'import torch\n'), ((4352, 4377), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4375, 4377), False, 'import torch\n'), ((5152, 5177), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (5175, 5177), False, 'import torch\n'), ((8172, 8200), 'numpy.ones', 'np.ones', ([], {'shape': '(256, 256, 3)'}), '(shape=(256, 256, 3))\n', (8179, 8200), True, 'import numpy as np\n'), ((8290, 8328), 'src.dataset.image_translation.image_translation_dataset.vis_landmark_on_img74', 'vis_landmark_on_img74', (['img_fl', 'pred_fl'], {}), '(img_fl, pred_fl)\n', (8311, 8328), False, 'from src.dataset.image_translation.image_translation_dataset import vis_landmark_on_img, vis_landmark_on_img98, vis_landmark_on_img74\n'), ((8388, 8426), 'src.dataset.image_translation.image_translation_dataset.vis_landmark_on_img98', 'vis_landmark_on_img98', (['img_fl', 'pred_fl'], {}), '(img_fl, pred_fl)\n', (8409, 8426), False, 'from src.dataset.image_translation.image_translation_dataset import vis_landmark_on_img, vis_landmark_on_img98, vis_landmark_on_img74\n'), ((8597, 8639), 'torch.tensor', 'torch.tensor', (['img_fls'], {'requires_grad': '(False)'}), '(img_fls, requires_grad=False)\n', (8609, 8639), False, 'import torch\n'), ((11678, 11689), 'time.time', 'time.time', ([], {}), '()\n', (11687, 11689), False, 'import time\n'), ((14498, 14528), 'thirdparty.AdaptiveWingLoss.utils.utils.get_preds_fromhm', 'get_preds_fromhm', (['pred_heatmap'], {}), '(pred_heatmap)\n', (14514, 14528), False, 'from thirdparty.AdaptiveWingLoss.utils.utils import get_preds_fromhm\n'), ((14804, 14832), 'numpy.ones', 'np.ones', ([], {'shape': '(256, 256, 3)'}), '(shape=(256, 256, 3))\n', (14811, 14832), True, 'import numpy as np\n'), ((15075, 15117), 'torch.tensor', 'torch.tensor', (['img_fls'], {'requires_grad': '(False)'}), '(img_fls, requires_grad=False)\n', (15087, 15117), False, 'import torch\n'), ((19878, 19934), 'numpy.concatenate', 'np.concatenate', (['(ref_in[i], g_out[i], fls_in[i])'], {'axis': '(1)'}), '((ref_in[i], g_out[i], fls_in[i]), axis=1)\n', (19892, 19934), True, 'import numpy as np\n'), ((3817, 3866), 'os.path.join', 'os.path.join', (['opt_parser.log_dir', 'opt_parser.name'], {}), '(opt_parser.log_dir, opt_parser.name)\n', (3829, 3866), False, 'import os, glob\n'), ((8517, 8542), 'numpy.stack', 'np.stack', (['img_fls'], {'axis': '(0)'}), '(img_fls, axis=0)\n', (8525, 8542), True, 'import numpy as np\n'), ((10626, 10685), 'os.path.join', 'os.path.join', (['self.opt_parser.jpg_dir', 'self.opt_parser.name'], {}), '(self.opt_parser.jpg_dir, self.opt_parser.name)\n', (10638, 10685), False, 'import os, glob\n'), ((11426, 11437), 'time.time', 'time.time', ([], {}), '()\n', (11435, 11437), False, 'import time\n'), ((14995, 15020), 'numpy.stack', 'np.stack', (['img_fls'], {'axis': '(0)'}), '(img_fls, axis=0)\n', (15003, 15020), True, 'import numpy as np\n'), ((17128, 17196), 'numpy.concatenate', 'np.concatenate', (['(ref_in[k], g_out[k], fls_in[k], ref_out[k])'], {'axis': '(1)'}), '((ref_in[k], g_out[k], fls_in[k], ref_out[k]), axis=1)\n', (17142, 17196), True, 'import numpy as np\n'), ((18369, 18406), 'numpy.concatenate', 'np.concatenate', (['(img_fl, jpg)'], {'axis': '(2)'}), '((img_fl, jpg), axis=2)\n', (18383, 18406), True, 'import numpy as np\n'), ((7973, 8022), 'numpy.concatenate', 'np.concatenate', (['[fl_jaw_eyebrow, fl_rest]'], {'axis': '(1)'}), '([fl_jaw_eyebrow, fl_rest], axis=1)\n', (7987, 8022), True, 'import numpy as np\n'), ((5230, 5255), 'torch.nn.DataParallel', 'nn.DataParallel', (['model_ft'], {}), '(model_ft)\n', (5245, 5255), True, 'import torch.nn as nn\n'), ((5838, 5863), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5861, 5863), False, 'import torch\n'), ((6164, 6189), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6187, 6189), False, 'import torch\n')]
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 14:25:14 2019 @author: gptshubham595 """ import cv2 import numpy as np windowName='Drawing' img=np.zeros((512,512,3),np.uint8); img.fill(255) cv2.namedWindow(windowName) drawing=False mode=True (ix,iy)=(-1,-1) def draw_circle(event,x,y,flags,param): global ix,iy,drawing,mode if (event == cv2.EVENT_LBUTTONDOWN): drawing=True (ix,iy)=x,y elif (event == cv2.EVENT_MOUSEMOVE): if drawing==True: if mode==True: cv2.circle(img,(x,y),3,(0,255,0),-1) else: cv2.circle(img,(x,y),10,(255,255,255),-1) elif event==cv2.EVENT_LBUTTONUP: drawing=False if mode==True: cv2.circle(img,(x,y),3,(0,255,0),-1) else: cv2.circle(img,(x,y),10,(255,255,255),-1) #bind callback to window cv2.setMouseCallback(windowName,draw_circle) def main(): global mode while(True): cv2.imshow(windowName,img) k=cv2.waitKey(1) if k==ord('m') or k==ord('M'): mode=not mode elif k==27: break cv2.destroyWindow(windowName) if __name__=='__main__': main()
[ "cv2.circle", "cv2.waitKey", "numpy.zeros", "cv2.setMouseCallback", "cv2.destroyWindow", "cv2.imshow", "cv2.namedWindow" ]
[((149, 182), 'numpy.zeros', 'np.zeros', (['(512, 512, 3)', 'np.uint8'], {}), '((512, 512, 3), np.uint8)\n', (157, 182), True, 'import numpy as np\n'), ((195, 222), 'cv2.namedWindow', 'cv2.namedWindow', (['windowName'], {}), '(windowName)\n', (210, 222), False, 'import cv2\n'), ((895, 940), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['windowName', 'draw_circle'], {}), '(windowName, draw_circle)\n', (915, 940), False, 'import cv2\n'), ((1162, 1191), 'cv2.destroyWindow', 'cv2.destroyWindow', (['windowName'], {}), '(windowName)\n', (1179, 1191), False, 'import cv2\n'), ((1003, 1030), 'cv2.imshow', 'cv2.imshow', (['windowName', 'img'], {}), '(windowName, img)\n', (1013, 1030), False, 'import cv2\n'), ((1040, 1054), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1051, 1054), False, 'import cv2\n'), ((537, 580), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(3)', '(0, 255, 0)', '(-1)'], {}), '(img, (x, y), 3, (0, 255, 0), -1)\n', (547, 580), False, 'import cv2\n'), ((608, 656), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(10)', '(255, 255, 255)', '(-1)'], {}), '(img, (x, y), 10, (255, 255, 255), -1)\n', (618, 656), False, 'import cv2\n'), ((744, 787), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(3)', '(0, 255, 0)', '(-1)'], {}), '(img, (x, y), 3, (0, 255, 0), -1)\n', (754, 787), False, 'import cv2\n'), ((811, 859), 'cv2.circle', 'cv2.circle', (['img', '(x, y)', '(10)', '(255, 255, 255)', '(-1)'], {}), '(img, (x, y), 10, (255, 255, 255), -1)\n', (821, 859), False, 'import cv2\n')]
import numpy as np from pytest_cases import parametrize class BenchmarkChallenger(object): """ Represents the API that a challenger should implement to enter the benchmark """ def fit(self, x, y): """ Implementors should train the model based on (x, y) """ raise NotImplementedError() def predict(self, x): """ Implementors should return a numpy array of predictions. """ raise NotImplementedError() class PolyFitChallenger(BenchmarkChallenger): """ A benchmark challenger implementation relying on np.polyfit """ def __init__(self, degree): self.coefs = None self.degree = degree def __str__(self): return "NumpyPolyfit(degree=%i)" % self.degree def fit(self, x, y): self.coefs = np.polyfit(x, y, deg=self.degree) def predict(self, x): all_x_powers = np.c_[[x ** d for d in range(self.degree, -1, -1)]] predictions = self.coefs.dot(all_x_powers) return predictions @parametrize(degree=[1, 2]) def algo_polyfit(degree): """ The two challengers based on polyfit, to be injected in the benchmark. """ return PolyFitChallenger(degree=degree)
[ "pytest_cases.parametrize", "numpy.polyfit" ]
[((999, 1025), 'pytest_cases.parametrize', 'parametrize', ([], {'degree': '[1, 2]'}), '(degree=[1, 2])\n', (1010, 1025), False, 'from pytest_cases import parametrize\n'), ((782, 815), 'numpy.polyfit', 'np.polyfit', (['x', 'y'], {'deg': 'self.degree'}), '(x, y, deg=self.degree)\n', (792, 815), True, 'import numpy as np\n')]
import logging import numpy as np import os import time import torch import torch.nn as nn from utils.meter import AverageMeter from torch.cuda.amp import autocast as autocast, GradScaler from utils.reranking import re_ranking import datetime import torch.nn.functional as F def do_train(cfg, model, train_loader, optimizer, scheduler, loss_fn): log_period = cfg.SOLVER.LOG_PERIOD checkpoint_period = cfg.SOLVER.CHECKPOINT_PERIOD device = "cuda" epochs = cfg.SOLVER.MAX_EPOCHS logger = logging.getLogger("reid_baseline.train") logger.info('start training') if device: model.to(device) if torch.cuda.device_count() > 1: print('Using {} GPUs for training'.format(torch.cuda.device_count())) model = nn.DataParallel(model) loss_meter = AverageMeter() acc_meter = AverageMeter() # train scaler = GradScaler() for epoch in range(1, epochs + 1): start_time = time.time() loss_meter.reset() acc_meter.reset() model.train() for n_iter, (img, vid) in enumerate(train_loader): optimizer.zero_grad() if cfg.INPUT.AUGMIX: bs = img[0].size(0) images_cat = torch.cat(img, dim = 0).to(device) # [3 * batch, 3, 32, 32] target = vid.to(device) with autocast(): logits, feat = model(images_cat, target) logits_orig, logits_augmix1, logits_augmix2 = logits[:bs], logits[bs:2*bs], logits[2*bs:] loss = loss_fn (logits_orig, feat, target) p_orig, p_augmix1, p_augmix2 = F.softmax(logits_orig, dim = -1), F.softmax(logits_augmix1, dim = -1), F.softmax(logits_augmix2, dim = -1) # Clamp mixture distribution to avoid exploding KL divergence p_mixture = torch.clamp((p_orig + p_augmix1 + p_augmix2) / 3., 1e-7, 1).log() loss += 12 * (F.kl_div(p_mixture, p_orig, reduction='batchmean') + F.kl_div(p_mixture, p_augmix1, reduction='batchmean') + F.kl_div(p_mixture, p_augmix2, reduction='batchmean')) / 3. else: img = img.to(device) target = vid.to(device) with autocast(): if cfg.MODEL.CHANNEL_HEAD: score, feat, channel_head_feature = model(img, target) #print(feat.shape, channel_head_feature.shape) loss = loss_fn(score, feat, channel_head_feature, target) else: score, feat = model(img, target) loss = loss_fn(score, feat, target) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() acc = (score.max(1)[1] == target).float().mean() loss_meter.update(loss.item(), img.shape[0]) acc_meter.update(acc, 1) if (n_iter + 1) % log_period == 0: logger.info("Epoch[{}] Iteration[{}/{}] Loss: {:.3f}, Acc: {:.3f}, Base Lr: {:.2e}" .format(epoch, (n_iter + 1), len(train_loader), loss_meter.avg, acc_meter.avg, scheduler.get_lr()[0])) scheduler.step() end_time = time.time() time_per_batch = (end_time - start_time) / (n_iter + 1) logger.info("Epoch {} done. Time per batch: {:.3f}[s] Speed: {:.1f}[samples/s]" .format(epoch, time_per_batch, train_loader.batch_size / time_per_batch)) if epoch % checkpoint_period == 0: torch.save(model.state_dict(), os.path.join(cfg.OUTPUT_DIR, cfg.MODEL.NAME + '_{}.pth'.format(epoch))) def cosine_dist(x, y): bs1, bs2 = x.size(0), y.size(0) frac_up = torch.matmul(x, y.transpose(0, 1)) frac_down = (torch.sqrt(torch.sum(torch.pow(x, 2), 1))).view(bs1, 1).repeat(1, bs2) * \ (torch.sqrt(torch.sum(torch.pow(y, 2), 1))).view(1, bs2).repeat(bs1, 1) cosine = frac_up / frac_down return 1 - cosine def do_inference( cfg, model, val_loader, num_query, query_name, gallery_name ): model.eval() model.cuda() features = torch.FloatTensor().cuda() for (input_img, pid, cid) in val_loader: input_img = input_img.cuda() input_img_mirror = input_img.flip(dims=[3]) outputs = model(input_img) outputs_mirror = model(input_img_mirror) f = outputs + outputs_mirror # flip features = torch.cat((features, f), 0) if cfg.TEST.RE_RANKING: feats = torch.nn.functional.normalize(features, dim=1, p=2) qf = feats[:num_query] gf = feats[num_query:] ranking_parameter = cfg.TEST.RE_RANKING_PARAMETER k1 = ranking_parameter[0] k2 = ranking_parameter[1] lambda_value = ranking_parameter[2] distmat = re_ranking(qf, gf, k1=k1, k2=k2, lambda_value=lambda_value) else: qf = features[:num_query] gf = features[num_query:] distmat = cosine_dist(qf, gf) distmat = distmat.cpu().numpy() #np.save(os.path.join(cfg.OUTPUT_DIR, cfg.TEST.DIST_MAT) , distmat) num_q, num_g = distmat.shape indices = np.argsort(distmat, axis=1) max_10_indices = indices[:, :10] res_dict = dict() for q_idx in range(num_q): filename = query_name[q_idx].split("/")[-1] max_10_files = [gallery_name[i].split("/")[-1] for i in max_10_indices[q_idx]] res_dict[filename] = max_10_files with open('%s/submission.csv' % cfg.OUTPUT_DIR, 'w') as file: for k, v in res_dict.items(): writer_string = "%s,{%s,%s,%s,%s,%s,%s,%s,%s,%s,%s}\n"%(k, v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9]) file.write(writer_string) file.close()
[ "utils.reranking.re_ranking", "torch.cuda.amp.autocast", "torch.nn.functional.kl_div", "utils.meter.AverageMeter", "torch.FloatTensor", "torch.cat", "time.time", "numpy.argsort", "torch.cuda.device_count", "torch.nn.functional.softmax", "torch.clamp", "torch.pow", "torch.cuda.amp.GradScaler"...
[((574, 614), 'logging.getLogger', 'logging.getLogger', (['"""reid_baseline.train"""'], {}), "('reid_baseline.train')\n", (591, 614), False, 'import logging\n'), ((875, 889), 'utils.meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (887, 889), False, 'from utils.meter import AverageMeter\n'), ((906, 920), 'utils.meter.AverageMeter', 'AverageMeter', ([], {}), '()\n', (918, 920), False, 'from utils.meter import AverageMeter\n'), ((947, 959), 'torch.cuda.amp.GradScaler', 'GradScaler', ([], {}), '()\n', (957, 959), False, 'from torch.cuda.amp import autocast as autocast, GradScaler\n'), ((5430, 5457), 'numpy.argsort', 'np.argsort', (['distmat'], {'axis': '(1)'}), '(distmat, axis=1)\n', (5440, 5457), True, 'import numpy as np\n'), ((1020, 1031), 'time.time', 'time.time', ([], {}), '()\n', (1029, 1031), False, 'import time\n'), ((3453, 3464), 'time.time', 'time.time', ([], {}), '()\n', (3462, 3464), False, 'import time\n'), ((4711, 4738), 'torch.cat', 'torch.cat', (['(features, f)', '(0)'], {}), '((features, f), 0)\n', (4720, 4738), False, 'import torch\n'), ((4784, 4835), 'torch.nn.functional.normalize', 'torch.nn.functional.normalize', (['features'], {'dim': '(1)', 'p': '(2)'}), '(features, dim=1, p=2)\n', (4813, 4835), False, 'import torch\n'), ((5086, 5145), 'utils.reranking.re_ranking', 're_ranking', (['qf', 'gf'], {'k1': 'k1', 'k2': 'k2', 'lambda_value': 'lambda_value'}), '(qf, gf, k1=k1, k2=k2, lambda_value=lambda_value)\n', (5096, 5145), False, 'from utils.reranking import re_ranking\n'), ((701, 726), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (724, 726), False, 'import torch\n'), ((834, 856), 'torch.nn.DataParallel', 'nn.DataParallel', (['model'], {}), '(model)\n', (849, 856), True, 'import torch.nn as nn\n'), ((4395, 4414), 'torch.FloatTensor', 'torch.FloatTensor', ([], {}), '()\n', (4412, 4414), False, 'import torch\n'), ((786, 811), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (809, 811), False, 'import torch\n'), ((1421, 1431), 'torch.cuda.amp.autocast', 'autocast', ([], {}), '()\n', (1429, 1431), True, 'from torch.cuda.amp import autocast as autocast, GradScaler\n'), ((2397, 2407), 'torch.cuda.amp.autocast', 'autocast', ([], {}), '()\n', (2405, 2407), True, 'from torch.cuda.amp import autocast as autocast, GradScaler\n'), ((1300, 1321), 'torch.cat', 'torch.cat', (['img'], {'dim': '(0)'}), '(img, dim=0)\n', (1309, 1321), False, 'import torch\n'), ((1718, 1748), 'torch.nn.functional.softmax', 'F.softmax', (['logits_orig'], {'dim': '(-1)'}), '(logits_orig, dim=-1)\n', (1727, 1748), True, 'import torch.nn.functional as F\n'), ((1752, 1785), 'torch.nn.functional.softmax', 'F.softmax', (['logits_augmix1'], {'dim': '(-1)'}), '(logits_augmix1, dim=-1)\n', (1761, 1785), True, 'import torch.nn.functional as F\n'), ((1789, 1822), 'torch.nn.functional.softmax', 'F.softmax', (['logits_augmix2'], {'dim': '(-1)'}), '(logits_augmix2, dim=-1)\n', (1798, 1822), True, 'import torch.nn.functional as F\n'), ((1940, 2001), 'torch.clamp', 'torch.clamp', (['((p_orig + p_augmix1 + p_augmix2) / 3.0)', '(1e-07)', '(1)'], {}), '((p_orig + p_augmix1 + p_augmix2) / 3.0, 1e-07, 1)\n', (1951, 2001), False, 'import torch\n'), ((2221, 2274), 'torch.nn.functional.kl_div', 'F.kl_div', (['p_mixture', 'p_augmix2'], {'reduction': '"""batchmean"""'}), "(p_mixture, p_augmix2, reduction='batchmean')\n", (2229, 2274), True, 'import torch.nn.functional as F\n'), ((4018, 4033), 'torch.pow', 'torch.pow', (['x', '(2)'], {}), '(x, 2)\n', (4027, 4033), False, 'import torch\n'), ((4110, 4125), 'torch.pow', 'torch.pow', (['y', '(2)'], {}), '(y, 2)\n', (4119, 4125), False, 'import torch\n'), ((2040, 2090), 'torch.nn.functional.kl_div', 'F.kl_div', (['p_mixture', 'p_orig'], {'reduction': '"""batchmean"""'}), "(p_mixture, p_orig, reduction='batchmean')\n", (2048, 2090), True, 'import torch.nn.functional as F\n'), ((2129, 2182), 'torch.nn.functional.kl_div', 'F.kl_div', (['p_mixture', 'p_augmix1'], {'reduction': '"""batchmean"""'}), "(p_mixture, p_augmix1, reduction='batchmean')\n", (2137, 2182), True, 'import torch.nn.functional as F\n')]
"""Return true where two arrays are element-wise equal within a tolerance.""" from __future__ import annotations import numpy import numpoly from ..baseclass import PolyLike from ..dispatch import implements @implements(numpy.isclose) def isclose( a: PolyLike, b: PolyLike, rtol: float = 1e-5, atol: float = 1e-8, equal_nan: bool = False, ) -> numpy.ndarray: """ Return true where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * abs(`b`)) and the absolute difference `atol` are added together to compare against the absolute difference between `a` and `b`. .. warning:: The default `atol` is not appropriate for comparing numbers that are much smaller than one (see Notes). Args: a, b: Input arrays to compare. rtol: The relative tolerance parameter (see Notes). atol: The absolute tolerance parameter (see Notes). equal_nan: Whether to compare NaN's as equal. If True, NaN's in `a` will be considered equal to NaN's in `b` in the output array. Returns: Returns a boolean array of where `a` and `b` are equal within the given tolerance. If both `a` and `b` are scalars, returns a single boolean value. Notes: For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) Unlike the built-in `math.isclose`, the above equation is not symmetric in `a` and `b` -- it assumes `b` is the reference value -- so that `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. `atol` should be carefully selected for the use case at hand. A zero value for `atol` will result in `False` if either `a` or `b` is zero. Examples: >>> q0, q1 = numpoly.variable(2) >>> numpoly.isclose([1e10*q0, 1e-7], [1.00001e10*q0, 1e-8]) array([ True, False]) >>> numpoly.isclose([1e10*q0, 1e-8], [1.00001e10*q0, 1e-9]) array([ True, True]) >>> numpoly.isclose([1e10*q0, 1e-8], [1.00001e10*q1, 1e-9]) array([False, True]) >>> numpoly.isclose([q0, numpy.nan], ... [q0, numpy.nan], equal_nan=True) array([ True, True]) """ a, b = numpoly.align_polynomials(a, b) out = numpy.ones(a.shape, dtype=bool) for key in a.keys: out &= numpy.isclose( a.values[key], b.values[key], atol=atol, rtol=rtol, equal_nan=equal_nan) return out
[ "numpy.isclose", "numpoly.align_polynomials", "numpy.ones" ]
[((2838, 2869), 'numpoly.align_polynomials', 'numpoly.align_polynomials', (['a', 'b'], {}), '(a, b)\n', (2863, 2869), False, 'import numpoly\n'), ((2880, 2911), 'numpy.ones', 'numpy.ones', (['a.shape'], {'dtype': 'bool'}), '(a.shape, dtype=bool)\n', (2890, 2911), False, 'import numpy\n'), ((2950, 3041), 'numpy.isclose', 'numpy.isclose', (['a.values[key]', 'b.values[key]'], {'atol': 'atol', 'rtol': 'rtol', 'equal_nan': 'equal_nan'}), '(a.values[key], b.values[key], atol=atol, rtol=rtol, equal_nan\n =equal_nan)\n', (2963, 3041), False, 'import numpy\n')]
import numpy as np import torch import torch.nn as nn import torchvision from torchvision import models from torch.autograd import Variable def init_weights(m): classname = m.__class__.__name__ if classname.find('Conv2d') != -1 or classname.find('Linear') != -1: nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) elif classname.find('BatchNorm') != -1: nn.init.ones_(m.weight) nn.init.zeros_(m.bias) class AdversarialLayer(torch.autograd.Function): def __init__(self, high_value=1.0): self.iter_num = 0 self.alpha = 10 self.low = 0.0 self.high = high_value self.max_iter = 10000.0 def forward(self, input): self.iter_num += 1 output = input * 1.0 return output def backward(self, gradOutput): self.coeff = np.float(2.0 * (self.high - self.low) / (1.0 + np.exp(-self.alpha*self.iter_num / self.max_iter)) - (self.high - self.low) + self.low) return -self.coeff * gradOutput class SilenceLayer(torch.autograd.Function): def __init__(self): pass def forward(self, input): return input * 1.0 def backward(self, gradOutput): return 0 * gradOutput # convnet without the last layer class AlexNetFc(nn.Module): def __init__(self, use_bottleneck=True, bottleneck_dim=256, new_cls=False, class_num=1000): super(AlexNetFc, self).__init__() model_alexnet = models.alexnet(pretrained=True) self.features = model_alexnet.features self.classifier = nn.Sequential() for i in range(6): self.classifier.add_module("classifier"+str(i), model_alexnet.classifier[i]) self.use_bottleneck = use_bottleneck self.new_cls = new_cls if new_cls: if self.use_bottleneck: self.bottleneck = nn.Linear(model_alexnet.classifier[6].in_features, bottleneck_dim) self.bottleneck.weight.data.normal_(0, 0.005) self.bottleneck.bias.data.fill_(0.0) self.fc = nn.Linear(bottleneck_dim, class_num) self.fc.weight.data.normal_(0, 0.01) self.fc.bias.data.fill_(0.0) else: self.fc = nn.Linear(model_alexnet.classifier[6].in_features, class_num) self.fc.weight.data.normal_(0, 0.01) self.fc.bias.data.fill_(0.0) self.__in_features = bottleneck_dim else: self.fc = model_resnet.fc self.__in_features = model_resnet.fc.in_features def forward(self, x): x = self.features(x) x = x.view(x.size(0), 256*6*6) x = self.classifier(x) if self.use_bottleneck: x = self.bottleneck_layer(x) y = self.fc(x) return x, y def output_num(self): return self.__in_features resnet_dict = {"ResNet18":models.resnet18, "ResNet34":models.resnet34, "ResNet50":models.resnet50, "ResNet101":models.resnet101, "ResNet152":models.resnet152} class ResNetFc(nn.Module): def __init__(self, resnet_name): super(ResNetFc, self).__init__() model_resnet = resnet_dict[resnet_name](pretrained=True) self.conv1 = model_resnet.conv1 self.bn1 = model_resnet.bn1 self.relu = model_resnet.relu self.maxpool = model_resnet.maxpool self.layer1 = model_resnet.layer1 self.layer2 = model_resnet.layer2 self.layer3 = model_resnet.layer3 self.layer4 = model_resnet.layer4 self.avgpool = nn.AvgPool2d((34,60), stride=1) self.feature_layers = nn.Sequential(self.conv1, self.bn1, self.relu, self.maxpool, \ self.layer1, self.layer2, self.layer3, self.layer4) def forward(self, x): x = self.feature_layers(x) if x.size(2) != 34: avgpool = nn.AvgPool2d((x.size(2), x.size(3)), stride=1) x = avgpool(x) else: x = self.avgpool(x) x = x.view(x.size(0), -1) return x def output_num(self): return self.__in_features class AdversarialNetwork(nn.Module): def __init__(self, in_feature): super(AdversarialNetwork, self).__init__() self.ad_layer1 = nn.Linear(in_feature, 1024) self.ad_layer2 = nn.Linear(1024,1024) self.ad_layer3 = nn.Linear(1024, 1) self.ad_layer1.weight.data.normal_(0, 0.01) self.ad_layer2.weight.data.normal_(0, 0.01) self.ad_layer3.weight.data.normal_(0, 0.3) self.ad_layer1.bias.data.fill_(0.0) self.ad_layer2.bias.data.fill_(0.0) self.ad_layer3.bias.data.fill_(0.0) self.relu1 = nn.ReLU() self.relu2 = nn.ReLU() self.dropout1 = nn.Dropout(0.5) self.dropout2 = nn.Dropout(0.5) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.ad_layer1(x) x = self.relu1(x) x = self.dropout1(x) x = self.ad_layer2(x) x = self.relu2(x) x = self.dropout2(x) x = self.ad_layer3(x) x = self.sigmoid(x) return x def output_num(self): return 1 class TemporalConvModel(nn.Module): def __init__(self, in_feature, seq_len): super(TemporalConvModel, self).__init__() self.conv1 = nn.Conv1d(in_feature, 256, 1, 1) self.conv2 = nn.Conv1d(256,256,3,1,1) self.conv3 = nn.Conv1d(256,256,3,1,1) self.fc = nn.Linear(256*seq_len, 2) self.relu1 = nn.ReLU() self.relu2 = nn.ReLU() self.relu3 = nn.ReLU() #self.dropout1 = nn.Dropout(0.5) #self.dropout2 = nn.Dropout(0.5) self.seq_len = seq_len def forward(self, x): x = self.conv1(x) x = self.relu1(x) x = self.conv2(x) x = self.relu2(x) x = self.conv3(x) x = self.relu3(x) x = x.view(-1, 256*self.seq_len) x = self.fc(x) return x def output_num(self): return 1 class SmallAdversarialNetwork(nn.Module): def __init__(self, in_feature): super(SmallAdversarialNetwork, self).__init__() self.ad_layer1 = nn.Linear(in_feature, 256) self.ad_layer2 = nn.Linear(256, 1) self.ad_layer1.weight.data.normal_(0, 0.01) self.ad_layer2.weight.data.normal_(0, 0.01) self.ad_layer1.bias.data.fill_(0.0) self.ad_layer2.bias.data.fill_(0.0) self.relu1 = nn.ReLU() self.dropout1 = nn.Dropout(0.5) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.ad_layer1(x) x = self.relu1(x) x = self.dropout1(x) x = self.ad_layer2(x) x = self.sigmoid(x) return x def output_num(self): return 1 class LittleAdversarialNetwork(nn.Module): def __init__(self, in_feature): super(LittleAdversarialNetwork, self).__init__() self.ad_layer1 = nn.Linear(in_feature, 1) self.ad_layer1.weight.data.normal_(0, 0.01) self.ad_layer1.bias.data.fill_(0.0) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.ad_layer1(x) x = self.sigmoid(x) return x def output_num(self): return 1
[ "torch.nn.Dropout", "torch.nn.ReLU", "torch.nn.Sequential", "torch.nn.init.xavier_uniform_", "torchvision.models.alexnet", "torch.nn.Conv1d", "torch.nn.init.zeros_", "numpy.exp", "torch.nn.Linear", "torch.nn.init.ones_", "torch.nn.AvgPool2d", "torch.nn.Sigmoid" ]
[((280, 313), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['m.weight'], {}), '(m.weight)\n', (303, 313), True, 'import torch.nn as nn\n'), ((1417, 1448), 'torchvision.models.alexnet', 'models.alexnet', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1431, 1448), False, 'from torchvision import models\n'), ((1514, 1529), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (1527, 1529), True, 'import torch.nn as nn\n'), ((3342, 3374), 'torch.nn.AvgPool2d', 'nn.AvgPool2d', (['(34, 60)'], {'stride': '(1)'}), '((34, 60), stride=1)\n', (3354, 3374), True, 'import torch.nn as nn\n'), ((3400, 3516), 'torch.nn.Sequential', 'nn.Sequential', (['self.conv1', 'self.bn1', 'self.relu', 'self.maxpool', 'self.layer1', 'self.layer2', 'self.layer3', 'self.layer4'], {}), '(self.conv1, self.bn1, self.relu, self.maxpool, self.layer1,\n self.layer2, self.layer3, self.layer4)\n', (3413, 3516), True, 'import torch.nn as nn\n'), ((3984, 4011), 'torch.nn.Linear', 'nn.Linear', (['in_feature', '(1024)'], {}), '(in_feature, 1024)\n', (3993, 4011), True, 'import torch.nn as nn\n'), ((4033, 4054), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (4042, 4054), True, 'import torch.nn as nn\n'), ((4075, 4093), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(1)'], {}), '(1024, 1)\n', (4084, 4093), True, 'import torch.nn as nn\n'), ((4374, 4383), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4381, 4383), True, 'import torch.nn as nn\n'), ((4401, 4410), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4408, 4410), True, 'import torch.nn as nn\n'), ((4431, 4446), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (4441, 4446), True, 'import torch.nn as nn\n'), ((4467, 4482), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (4477, 4482), True, 'import torch.nn as nn\n'), ((4502, 4514), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (4512, 4514), True, 'import torch.nn as nn\n'), ((4930, 4962), 'torch.nn.Conv1d', 'nn.Conv1d', (['in_feature', '(256)', '(1)', '(1)'], {}), '(in_feature, 256, 1, 1)\n', (4939, 4962), True, 'import torch.nn as nn\n'), ((4980, 5008), 'torch.nn.Conv1d', 'nn.Conv1d', (['(256)', '(256)', '(3)', '(1)', '(1)'], {}), '(256, 256, 3, 1, 1)\n', (4989, 5008), True, 'import torch.nn as nn\n'), ((5022, 5050), 'torch.nn.Conv1d', 'nn.Conv1d', (['(256)', '(256)', '(3)', '(1)', '(1)'], {}), '(256, 256, 3, 1, 1)\n', (5031, 5050), True, 'import torch.nn as nn\n'), ((5061, 5088), 'torch.nn.Linear', 'nn.Linear', (['(256 * seq_len)', '(2)'], {}), '(256 * seq_len, 2)\n', (5070, 5088), True, 'import torch.nn as nn\n'), ((5104, 5113), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5111, 5113), True, 'import torch.nn as nn\n'), ((5131, 5140), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5138, 5140), True, 'import torch.nn as nn\n'), ((5158, 5167), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5165, 5167), True, 'import torch.nn as nn\n'), ((5684, 5710), 'torch.nn.Linear', 'nn.Linear', (['in_feature', '(256)'], {}), '(in_feature, 256)\n', (5693, 5710), True, 'import torch.nn as nn\n'), ((5732, 5749), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(1)'], {}), '(256, 1)\n', (5741, 5749), True, 'import torch.nn as nn\n'), ((5943, 5952), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5950, 5952), True, 'import torch.nn as nn\n'), ((5973, 5988), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (5983, 5988), True, 'import torch.nn as nn\n'), ((6008, 6020), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (6018, 6020), True, 'import torch.nn as nn\n'), ((6372, 6396), 'torch.nn.Linear', 'nn.Linear', (['in_feature', '(1)'], {}), '(in_feature, 1)\n', (6381, 6396), True, 'import torch.nn as nn\n'), ((6504, 6516), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (6514, 6516), True, 'import torch.nn as nn\n'), ((357, 379), 'torch.nn.init.zeros_', 'nn.init.zeros_', (['m.bias'], {}), '(m.bias)\n', (371, 379), True, 'import torch.nn as nn\n'), ((432, 455), 'torch.nn.init.ones_', 'nn.init.ones_', (['m.weight'], {}), '(m.weight)\n', (445, 455), True, 'import torch.nn as nn\n'), ((464, 486), 'torch.nn.init.zeros_', 'nn.init.zeros_', (['m.bias'], {}), '(m.bias)\n', (478, 486), True, 'import torch.nn as nn\n'), ((1783, 1849), 'torch.nn.Linear', 'nn.Linear', (['model_alexnet.classifier[6].in_features', 'bottleneck_dim'], {}), '(model_alexnet.classifier[6].in_features, bottleneck_dim)\n', (1792, 1849), True, 'import torch.nn as nn\n'), ((1979, 2015), 'torch.nn.Linear', 'nn.Linear', (['bottleneck_dim', 'class_num'], {}), '(bottleneck_dim, class_num)\n', (1988, 2015), True, 'import torch.nn as nn\n'), ((2142, 2203), 'torch.nn.Linear', 'nn.Linear', (['model_alexnet.classifier[6].in_features', 'class_num'], {}), '(model_alexnet.classifier[6].in_features, class_num)\n', (2151, 2203), True, 'import torch.nn as nn\n'), ((889, 940), 'numpy.exp', 'np.exp', (['(-self.alpha * self.iter_num / self.max_iter)'], {}), '(-self.alpha * self.iter_num / self.max_iter)\n', (895, 940), True, 'import numpy as np\n')]
''' core.py的全部内容都来自我的开源项目:https://github.com/oscarcx123/afk-arena-tools 以前已经实现过这么一套API,就不再重复造轮子了。 部分API可能没什么用,我也懒得删。 普通用户不需要看这个文件。 ''' import os import cv2 import time import random import subprocess import numpy as np import concurrent.futures class Azure(): def __init__(self, scale_percentage): self.scale_percentage = scale_percentage self.threshold = 0.9 self.debug = False # 加载图像资源 def load_res(self, file_dir): # 匹配对象的字典 self.res = {} temp_list = os.listdir(file_dir) for item in temp_list: self.res[item] = {} res_path = os.path.join(file_dir, item) self.res[item]["img"] = cv2.imread(res_path) # 如果不是原尺寸(1440P),进行对应缩放操作 if self.scale_percentage != 100: self.res[item]["width"] = int(self.res[item]["img"].shape[1] * self.scale_percentage / 100) self.res[item]["height"] = int(self.res[item]["img"].shape[0] * self.scale_percentage / 100) self.res[item]["img"] = cv2.resize(self.res[item]["img"], (self.res[item]["width"], self.res[item]["height"]), interpolation=cv2.INTER_AREA) else: self.res[item]["height"], self.res[item]["width"], self.res[item]["channel"] = self.res[item]["img"].shape[::] self.write_log(f"Loaded {item}") # 获取截图 def get_img(self, pop_up_window=False, save_img=False, file_name='screenshot.png'): image_bytes = self.exec_cmd("adb exec-out screencap -p") if image_bytes == b'': self.write_log(f"截图失败!请检查adb是否已经跟手机连接!") else: self.target_img = cv2.imdecode(np.fromstring(image_bytes, dtype='uint8'), cv2.IMREAD_COLOR) if save_img: cv2.imwrite(file_name, self.target_img) if pop_up_window: self.show_img() def show_img(self): cv2.namedWindow("screenshot", cv2.WINDOW_NORMAL) cv2.resizeWindow('screenshot', 360, 640) cv2.imshow("screenshot", self.target_img) cv2.waitKey(0) cv2.destroyWindow("screenshot") # 匹配并获取中心点 def match(self, img_name): # 从加载好的图像资源中获取数据 find_img = self.res[img_name]["img"] find_height = self.res[img_name]["height"] find_width = self.res[img_name]["width"] # 匹配 try: result = cv2.matchTemplate(self.target_img, find_img, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) except: self.write_log(f"OpenCV对比失败!请使用杂项中的截图功能来测试能否正常截图!") print(f"{img_name}最大匹配度:{max_val}") if max_val < self.threshold: return False # 计算位置 self.pointUpLeft = max_loc self.pointLowRight = (int(max_loc[0] + find_width), int(max_loc[1] + find_height)) self.pointCentre = (int(max_loc[0] + (find_width / 2)), int(max_loc[1] + (find_height / 2))) if self.debug: self.draw_circle() self.write_log(f"匹配到{img_name},匹配度:{max_val}") return True # 匹配多个结果 def multiple_match(self, img_name): # 用于存放匹配结果 match_res = [] # 从加载好的图像资源中获取数据 find_img = self.res[img_name]["img"] find_height = self.res[img_name]["height"] find_width = self.res[img_name]["width"] # OpenCV匹配多个结果 # https://stackoverflow.com/a/58514954/12766614 try: result = cv2.matchTemplate(self.target_img, find_img, cv2.TM_CCOEFF_NORMED) # max_val设置为1,从而能够进入循环 max_val = 1 cnt = 0 while max_val > self.threshold: min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) if max_val > self.threshold: # 抹除最大值周围的数值,从而可以在下一次找到其它位置的(第二)最大值 result[max_loc[1]-find_height//2:max_loc[1]+find_height//2+1, max_loc[0]-find_width//2:max_loc[0]+find_width//2+1] = 0 # 计算位置 pointUpLeft = max_loc pointLowRight = (int(max_loc[0] + find_width), int(max_loc[1] + find_height)) pointCentre = (int(max_loc[0] + (find_width / 2)), int(max_loc[1] + (find_height / 2))) # image = cv2.rectangle(image, (max_loc[0],max_loc[1]), (max_loc[0]+find_width+1, max_loc[1]+find_height+1), (0,0,0)) # cv2.imwrite(f'output_{cnt}.png', 255*result) 灰阶输出,越亮匹配度越高 cnt += 1 match_res.append(pointCentre) print(f"{img_name}找到{cnt}个,匹配度:{max_val}") except: self.write_log(f"OpenCV对比失败!请使用杂项中的截图功能来测试能否正常截图!") return match_res # 立即截图,然后匹配,返回boolean def current_match(self, img_name): self.get_img() return self.match(img_name) # 立即截图,然后匹配多个,返回数组,内含若干匹配成功的tuple def current_multiple_match(self, img_name): self.get_img() return self.multiple_match(img_name) # 点击(传入坐标) # 也可以接受比例形式坐标,例如(0.5, 0.5, percentage=True)就是点屏幕中心 # 可以传入randomize=False来禁用坐标的随机偏移 def tap(self, x_coord=None, y_coord=None, percentage=False, randomize=True): if x_coord is None and y_coord is None: x_coord, y_coord = self.get_coord(randomize=randomize) if percentage: x_coord = int(x_coord * self.screen_width * (self.scale_percentage / 100)) y_coord = int(y_coord * self.screen_height * (self.scale_percentage / 100)) x_coord = self.randomize_coord(x_coord, 5) y_coord = self.randomize_coord(y_coord, 5) self.write_log(f"点击坐标:{(x_coord, y_coord)}") cmd = f"adb shell input tap {x_coord} {y_coord}" self.exec_cmd(cmd) # 滑动 / 长按 def swipe(self, fromX=None, fromY=None, toX=None, toY=None, swipe_time=200): if toX is None and toY is None: swipe_time = 500 self.write_log(f"长按坐标:{(fromX, fromY)}") cmd = f"adb shell input swipe {fromX} {fromY} {fromX} {fromY} {swipe_time}" else: self.write_log(f"滑动:从{(fromX, fromY)}到{(toX, toY)}") cmd = f"adb shell input swipe {fromX} {fromY} {toX} {toY} {swipe_time}" self.exec_cmd(cmd) # 执行指令 def exec_cmd(self, cmd, new_thread=False, show_output=False): def do_cmd(cmd): pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) return pipe.stdout.read() if new_thread: if show_output: self.write_log(f"执行{cmd}") with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(do_cmd, cmd) ret_val = future.result() else: if show_output: self.write_log(f"执行{cmd}") ret_val = do_cmd(cmd) if show_output: self.write_log(ret_val.decode("utf-8")) return ret_val # adb连接(WIFI) def adb_connect(self): self.exec_cmd(f"adb connect {self.wifi_adb_addr}", new_thread=True, show_output=True) # adb devices(验证设备是否连接) def adb_devices(self): self.exec_cmd("adb devices", new_thread=True, show_output=True) # 查看adb版本 def adb_version(self): self.exec_cmd("adb --version", new_thread=True, show_output=True) # 画点(测试用) def draw_circle(self): cv2.circle(self.target_img, self.pointUpLeft, 10, (255, 255, 255), 5) cv2.circle(self.target_img, self.pointCentre, 10, (255, 255, 255), 5) cv2.circle(self.target_img, self.pointLowRight, 10, (255, 255, 255), 5) self.show_img() # 获取匹配到的坐标 def get_coord(self, randomize=True): x_coord = self.pointCentre[0] y_coord = self.pointCentre[1] if randomize: x_coord = self.randomize_coord(x_coord, 20) y_coord = self.randomize_coord(y_coord, 15) return x_coord, y_coord # 坐标进行随机偏移处理 def randomize_coord(self, coord, diff): return random.randint(coord - diff, coord + diff) def write_log(self, text): timestamp = time.strftime("[%H:%M:%S] ", time.localtime()) print(timestamp + text) # 判断文件是否为空 def is_file_empty(self, file_name): return os.stat(file_name).st_size == 0 def sleep(self, sec): print(f"Sleep: {sec}s") time.sleep(sec)
[ "cv2.minMaxLoc", "cv2.imshow", "os.path.join", "cv2.matchTemplate", "random.randint", "cv2.imwrite", "numpy.fromstring", "cv2.resize", "time.localtime", "subprocess.Popen", "cv2.circle", "os.stat", "cv2.waitKey", "time.sleep", "cv2.resizeWindow", "os.listdir", "cv2.imread", "cv2.de...
[((516, 536), 'os.listdir', 'os.listdir', (['file_dir'], {}), '(file_dir)\n', (526, 536), False, 'import os\n'), ((1901, 1949), 'cv2.namedWindow', 'cv2.namedWindow', (['"""screenshot"""', 'cv2.WINDOW_NORMAL'], {}), "('screenshot', cv2.WINDOW_NORMAL)\n", (1916, 1949), False, 'import cv2\n'), ((1958, 1998), 'cv2.resizeWindow', 'cv2.resizeWindow', (['"""screenshot"""', '(360)', '(640)'], {}), "('screenshot', 360, 640)\n", (1974, 1998), False, 'import cv2\n'), ((2007, 2048), 'cv2.imshow', 'cv2.imshow', (['"""screenshot"""', 'self.target_img'], {}), "('screenshot', self.target_img)\n", (2017, 2048), False, 'import cv2\n'), ((2057, 2071), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2068, 2071), False, 'import cv2\n'), ((2080, 2111), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""screenshot"""'], {}), "('screenshot')\n", (2097, 2111), False, 'import cv2\n'), ((7420, 7489), 'cv2.circle', 'cv2.circle', (['self.target_img', 'self.pointUpLeft', '(10)', '(255, 255, 255)', '(5)'], {}), '(self.target_img, self.pointUpLeft, 10, (255, 255, 255), 5)\n', (7430, 7489), False, 'import cv2\n'), ((7498, 7567), 'cv2.circle', 'cv2.circle', (['self.target_img', 'self.pointCentre', '(10)', '(255, 255, 255)', '(5)'], {}), '(self.target_img, self.pointCentre, 10, (255, 255, 255), 5)\n', (7508, 7567), False, 'import cv2\n'), ((7576, 7647), 'cv2.circle', 'cv2.circle', (['self.target_img', 'self.pointLowRight', '(10)', '(255, 255, 255)', '(5)'], {}), '(self.target_img, self.pointLowRight, 10, (255, 255, 255), 5)\n', (7586, 7647), False, 'import cv2\n'), ((8048, 8090), 'random.randint', 'random.randint', (['(coord - diff)', '(coord + diff)'], {}), '(coord - diff, coord + diff)\n', (8062, 8090), False, 'import random\n'), ((8392, 8407), 'time.sleep', 'time.sleep', (['sec'], {}), '(sec)\n', (8402, 8407), False, 'import time\n'), ((623, 651), 'os.path.join', 'os.path.join', (['file_dir', 'item'], {}), '(file_dir, item)\n', (635, 651), False, 'import os\n'), ((688, 708), 'cv2.imread', 'cv2.imread', (['res_path'], {}), '(res_path)\n', (698, 708), False, 'import cv2\n'), ((2378, 2444), 'cv2.matchTemplate', 'cv2.matchTemplate', (['self.target_img', 'find_img', 'cv2.TM_CCOEFF_NORMED'], {}), '(self.target_img, find_img, cv2.TM_CCOEFF_NORMED)\n', (2395, 2444), False, 'import cv2\n'), ((2494, 2515), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['result'], {}), '(result)\n', (2507, 2515), False, 'import cv2\n'), ((3462, 3528), 'cv2.matchTemplate', 'cv2.matchTemplate', (['self.target_img', 'find_img', 'cv2.TM_CCOEFF_NORMED'], {}), '(self.target_img, find_img, cv2.TM_CCOEFF_NORMED)\n', (3479, 3528), False, 'import cv2\n'), ((6369, 6454), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'stdin': 'subprocess.PIPE', 'stdout': 'subprocess.PIPE', 'shell': '(True)'}), '(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True\n )\n', (6385, 6454), False, 'import subprocess\n'), ((8172, 8188), 'time.localtime', 'time.localtime', ([], {}), '()\n', (8186, 8188), False, 'import time\n'), ((1050, 1171), 'cv2.resize', 'cv2.resize', (["self.res[item]['img']", "(self.res[item]['width'], self.res[item]['height'])"], {'interpolation': 'cv2.INTER_AREA'}), "(self.res[item]['img'], (self.res[item]['width'], self.res[item][\n 'height']), interpolation=cv2.INTER_AREA)\n", (1060, 1171), False, 'import cv2\n'), ((1664, 1705), 'numpy.fromstring', 'np.fromstring', (['image_bytes'], {'dtype': '"""uint8"""'}), "(image_bytes, dtype='uint8')\n", (1677, 1705), True, 'import numpy as np\n'), ((1766, 1805), 'cv2.imwrite', 'cv2.imwrite', (['file_name', 'self.target_img'], {}), '(file_name, self.target_img)\n', (1777, 1805), False, 'import cv2\n'), ((3705, 3726), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['result'], {}), '(result)\n', (3718, 3726), False, 'import cv2\n'), ((8293, 8311), 'os.stat', 'os.stat', (['file_name'], {}), '(file_name)\n', (8300, 8311), False, 'import os\n')]
# coding: utf-8 import unittest import os, subprocess, sys import time import scipy import numpy as np from numpy.testing import assert_almost_equal, assert_equal,\ assert_raises from scipy.special import lpmn, sph_harm from scipy.interpolate import CubicSpline from scipy.special import factorial2 as fac2 from nose import SkipTest from nose.tools import nottest from nose.plugins.skip import Skip from pawpyseed.core import pawpyc from pawpyseed.core.tests import testc class PawpyTestError(Exception): """ Class for handling errors that occur during execution of Python functions in pawpyseed """ def __init__(self, msg): self.msg = msg MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) from pymatgen.io.vasp.inputs import Poscar, Potcar from pymatgen.io.vasp.outputs import Vasprun, Chgcar from pymatgen.core.structure import Structure from pawpyseed.core.utils import * from pawpyseed.core.wavefunction import * from pawpyseed.core.projector import Projector from pawpyseed.core.noncollinear import NCLWavefunction class DummyProjector(Projector): def make_site_lists(self): M_R, M_S, N_R, N_S, N_RS = super(DummyProjector, self).make_site_lists() return [], [], M_R, M_S, [pair for pair in zip(M_R, M_S)] class TestC: def setup(self): self.currdir = os.getcwd() os.chdir(os.path.join(MODULE_DIR, '../../../test_files')) self.vr = Vasprun("vasprun.xml") self.cr = CoreRegion(Potcar.from_file("POTCAR")) def teardown(self): os.chdir(self.currdir) def test_legendre(self): xs = np.linspace(0,1,10000) ys = np.zeros(10000*16) ys2 = np.zeros(10000*16) for i in range(xs.shape[0]): if i == 0: print (lpmn(-3,3,xs[i])[0]) ys[16*i:16*(i+1)] = lpmn(-3,3,xs[i])[0].flatten() for i in range(xs.shape[0]): for l in range(4): for m in range(0,-l-1,-1): ys2[i*16-m*4+l] = pawpyc.legendre(l, m, xs[i]) assert_almost_equal(np.linalg.norm(ys-ys2), 0.0) def test_Ylm(self): for l in range(4): for m in range(-l,l): xs = np.linspace(0,1,100) ys = np.zeros(10000, np.complex128) ys1 = np.zeros(10000, np.complex128) ys2 = np.zeros(10000, np.complex128) for i in range(xs.shape[0]): for j in range(xs.shape[0]): ys[i*100+j] = sph_harm(m, l, xs[j]*2*np.pi, xs[i]*np.pi) i,j=0,0 for i in range(xs.shape[0]): for j in range(xs.shape[0]): ys1[i*100+j] = pawpyc.Ylm(l, m, xs[i]*np.pi, xs[j]*np.pi*2) ys2[i*100+j] = pawpyc.Ylm2(l, m, np.cos(xs[i]*np.pi), xs[j]*np.pi*2) assert_almost_equal(np.linalg.norm(ys-ys1),0.0) assert_almost_equal(np.linalg.norm(ys1-ys2),0.0) def test_unit_conversion(self): struct = Poscar.from_file("CONTCAR").structure lattice = struct.lattice.matrix reclattice = struct.lattice.reciprocal_lattice.matrix for site in struct: coord = site.coords fcoord = site.frac_coords temp1 = np.copy(fcoord, order='C') pawpyc.frac_to_cartesian(temp1, lattice) assert_almost_equal(np.linalg.norm(temp1-coord), 0.0) temp2 = np.copy(coord, order='C') pawpyc.cartesian_to_frac(temp2, reclattice) assert_almost_equal(np.linalg.norm(temp2-fcoord), 0.0) def test_spline(self): vr = self.vr cr = self.cr struct = Poscar.from_file("CONTCAR").structure grid = cr.pps['Ga'].projgrid vals = cr.pps['Ga'].realprojs[0] rmax = cr.pps['Ga'].rmax tst = np.linspace(0, max(grid), 400) res1 = CubicSpline(grid, vals, extrapolate=True, bc_type='natural')(tst) x, y = grid[:], vals[:] res2 = np.zeros(tst.shape) pawpyc.interpolate(res2, tst, x, y, rmax, 100, 400) assert_almost_equal(np.linalg.norm(res1-res2), 0, 2) sys.stdout.flush() def test_fft3d(self): print("TEST FFT") vr = self.vr weights = np.array(vr.actual_kpoints_weights) res = testc.fft_check("WAVECAR", weights, np.array([20,20,20], dtype=np.int32, order='C')) assert_equal(res, 0) def test_sbt(self): from scipy.special import spherical_jn as jn cr = CoreRegion(Potcar.from_file("POTCAR")) r = cr.pps['Ga'].grid f = cr.pps['Ga'].aewaves[0] - cr.pps['Ga'].pswaves[0]; ks, res = pawpyc.spherical_bessel_transform(1e6, 0, r, f) k = ks[180] vals = jn(0, r * k) * f * r integral = np.trapz(vals, r) print (integral) print (ks[180]) print (res[180]) assert_almost_equal(integral, res[180], decimal=3) perc = ks**2 * res**2 perc = np.cumsum(perc) perc /= np.max(perc) def test_radial(self): try: import pawpyseed.core.tests.reference as gint except ImportError: print("No McMurchie-Davidson installed, skipping radial test") raise SkipTest() h0 = ([1], [0]) h1 = ([2], [1]) h2 = ([4, -2], [2, 0]) h3 = ([8, -12], [3, 1]) H = [h0, h1, h2, h3] def eval_overlap(a, ijk1, A, b, ijk2, B): ov = 0 for ci1, i1 in zip(*(H[ijk1[0]])): for cj1, j1 in zip(*(H[ijk1[1]])): for ck1, k1 in zip(*(H[ijk1[2]])): for ci2, i2 in zip(*(H[ijk2[0]])): for cj2, j2 in zip(*(H[ijk2[1]])): for ck2, k2 in zip(*(H[ijk2[2]])): ov += ci1 * ci2 * cj1 * cj2 * ck1 *ck2\ * gint.overlap(a, (i1,j1,k1), A, b,(i2,j2,k2), B) return ov def getf(f, r, a, n, m): if n == 0: N = 0.25 ijks = [(0,0,0)] coefs = [1] elif n == 1 and m == 0: N = .25 ijks = [(0,0,1)] coefs = [1] elif n == 1: N = 0.25 ijks = [(1,0,0), (0,1,0)] if m == 1: coefs = [1,1j] else: coefs = [1,-1j] elif n == 2 and m == 0: N = 3 ijks = [(0,0,2), (2,0,0), (0,2,0)] coefs = [2,-1,-1] elif n == 2 and m == 1: N = 0.25 ijks = [(1,0,1), (0,1,1)] coefs = [1, 1.0j] elif n == 2 and m == -1: N = 0.25 ijks = [(1,0,1), (0,1,1)] coefs = [1, -1.0j] elif n ==2 and m == 2: N = 1 ijks = [(2,0,0), (0,2,0), (1,1,0)] coefs=[1, -1, 1.0j*2] elif n ==2 and m == -2: N = 1 ijks = [(2,0,0), (0,2,0), (1,1,0)] coefs=[1, -1, -1.0j*2] elif n == 3 and m == 0: N = 15 ijks = [(0,0,3), (0,2,1), (2,0,1)] coefs = [2, -3, -3] else: raise ValueError('Do not know that n,m pair %d %d' % (n, m)) return r * 2**(n+2) * np.sqrt(np.pi * N / fac2(2*n+1)) * (a*r)**n * f, ijks, coefs """ elif n == 2 and m == 1: N = 0.25 ijks = [(1,0,1)] coefs = [1] elif n == 2 and m == -1: N = 0.25 ijks = [(0,1,1)] coefs = [1] """ """ elif n == 2 and m == 2: N = 1 ijks = [(2,0,0), (0,2,0)] coefs = [1,-1] elif n == 2 and m == -2: N = 0.25 ijks = [(1,1,0)] coefs = [1] """ # test realspace radial overlap # test recipspace radial overlap pols = ([0,0,0],[0,0,1],[0,0,2],[0,0,3],[0,1,1]) ls = (0,1,2,3,2, 2, 2,2,1, 1) ms = (0,0,0,0,1,-1,-2,2,1,-1) a = 1 b = 1 A = [0,0,0] Bs = ([0,0,0], [0.5,0.5,0.5], [-0.5,0.5,-0.5], [0.123,0.543,-0.96]) r = np.exp(np.linspace(np.log(0.001),np.log(4), 600)) init_f1 = np.exp(-a * r**2) init_f2 = np.exp(-b * r**2) for B in Bs: Barr = np.array(B, dtype=np.float64, order='C') for l1, m1 in zip(ls, ms): f1, ijks1, coefs1 = getf(init_f1, r, a, l1, m1) for l2, m2 in zip(ls, ms): #print("START", l1, m1, l2, m2, a, b, B) f2, ijks2, coefs2 = getf(init_f2, r, b, l2, m2) ov1 = 0 for coef1, ijk1 in zip(coefs1, ijks1): for coef2, ijk2 in zip(coefs2, ijks2): #print(ijk1, ijk2, coef1, coef2) ov1 += coef1 * np.conj(coef2) * eval_overlap(a,ijk1,A,b,ijk2,B) if m1 != 0: ov1 /= np.sqrt(2) if m2 != 0: ov1 /= np.sqrt(2) if np.linalg.norm(B) > 0: # sign convention adjustment if m1 > 0: ov1 *= (-1)**(m1) if m2 > 0: ov1 *= (-1)**(m2) ov2 = pawpyc.reciprocal_offsite_wave_overlap(Barr, r, f1, r, f2, l1, m1, l2, m2) if (np.abs(ov1) > 1e-10 and (np.abs(ov1 - ov2))/np.abs(ov1) > 1e-4): print(l1, m1, l2, m2, B, ov1, ov2) if np.abs(ov1) < 1e-10: assert_almost_equal(np.abs(ov2), 0, 10) else: assert_almost_equal((np.abs(ov1 - ov2))/np.abs(ov1), 0, 4) @nottest def test_sphagain(self): # a little snippet to check the sign of teh gaussians vs spherical harmonics h0 = ([1], [0]) h1 = ([2], [1]) h2 = ([4, -2], [2, 0]) h3 = ([8, -12], [3, 1]) H = [h0, h1, h2, h3] for n, m in [(2,1), (2,-1), (2,0), (2,2), (2,-2)]: if n == 0: N = 0.25 ijks = [(0,0,0)] coefs = [1] elif n == 1 and m == 0: N = .25 ijks = [(0,0,1)] coefs = [1] elif n == 1: N = 0.25 ijks = [(1,0,0), (0,1,0)] if m == 1: coefs = [1,1j] else: coefs = [1,-1j] elif n == 2 and m == 0: N = 3 ijks = [(0,0,2), (2,0,0), (0,2,0)] coefs = [2,-1,-1] elif n == 2 and m == 1: N = 0.25 ijks = [(1,0,1), (0,1,1)] coefs = [1, 1.0j] elif n == 2 and m == -1: N = 0.25 ijks = [(1,0,1), (0,1,1)] coefs = [1, -1.0j] elif n ==2 and m == 2: N = 1 ijks = [(2,0,0), (0,2,0), (1,1,0)] coefs=[1, -1, 1.0j*2] elif n ==2 and m == -2: N = 1 ijks = [(2,0,0), (0,2,0), (1,1,0)] coefs=[1, -1, -1.0j*2] elif n == 3 and m == 0: N = 15 ijks = [(0,0,3), (0,2,1), (2,0,1)] coefs = [2, -3, -3] ov = 0 o, p = np.pi/4, np.pi/4 for ijk1, coef in zip(ijks, coefs): for ci1, i1 in zip(*(H[ijk1[0]])): for cj1, j1 in zip(*(H[ijk1[1]])): for ck1, k1 in zip(*(H[ijk1[2]])): ov += ci1 * cj1 * ck1 * coef\ * (np.sin(o)*np.cos(p))**i1\ * (np.sin(o)*np.sin(p))**j1\ * (np.cos(o))**k1 print("SPHHARM CHECK!!!") print(sph_harm(m, n, o, p)) print(ov) @nottest class TestMem: def setup(self): self.currdir = os.getcwd() os.chdir(os.path.join(MODULE_DIR, '../../../test_files')) structure = Poscar.from_file("CONTCAR").structure cr = CoreRegion(Potcar.from_file("POTCAR")) pps = {} labels = {} label = 0 for e in cr.pps: pps[label] = cr.pps[e] labels[e] = label label += 1 clabels = np.array([], np.int32) ls = np.array([], np.int32) projectors = np.array([], np.float64) aewaves = np.array([], np.float64) pswaves = np.array([], np.float64) wgrids = np.array([], np.float64) pgrids = np.array([], np.float64) num_els = 0 for num in pps: pp = pps[num] clabels = np.append(clabels, [num, len(pp.ls), pp.ndata, len(pp.grid)]) ls = np.append(ls, pp.ls) wgrids = np.append(wgrids, pp.grid) pgrids = np.append(pgrids, pp.projgrid) num_els += 1 for i in range(len(pp.ls)): proj = pp.realprojs[i] aepw = pp.aewaves[i] pspw = pp.pswaves[i] projectors = np.append(projectors, proj) aewaves = np.append(aewaves, aepw) pswaves = np.append(pswaves, pspw) print ("rmax", cr.pps['Ga'].rmax * 0.529177) selfnums = np.array([labels[el(s)] for s in structure], dtype=np.int32) selfcoords = np.array([], np.float64) for s in structure: selfcoords = np.append(selfcoords, s.frac_coords) f = open('potholder.txt', 'w') f.write('%d '%num_els) for i in range(len(clabels)): f.write('%d '%clabels[i]) f.write('%d '%len(ls)) for i in range(len(ls)): f.write('%d '%ls[i]) f.write('%d '%len(pgrids)) for i in range(len(pgrids)): f.write('%f '%pgrids[i]) f.write('%d '%len(wgrids)) for i in range(len(wgrids)): f.write('%f '%wgrids[i]) f.write('%d '%len(projectors)) for i in range(len(projectors)): f.write('%f '%projectors[i]) f.write('%d '%len(aewaves)) for i in range(len(aewaves)): f.write('%f '%aewaves[i]) f.write('%d '%len(pswaves)) for i in range(len(pswaves)): f.write('%f '%pswaves[i]) f.write('%f '%(cr.pps['Ga'].rmax*0.529177)) f.write('%d '%len(selfnums)) for i in range(len(selfnums)): f.write('%d '%selfnums[i]) for i in range(len(selfnums)*3): f.write('%f '%selfcoords[i]) f.close() def teardown(self): os.remove('potholder.txt') os.chdir(self.currdir) def test_memory(self): f = open('mtest.out', 'w') subprocess.call('valgrind ../pawpyseed/core/memtest --track-origins=yes --leak-check=full'.split(), stdout=f, stderr=f) f.close() class TestPy: def setup(self): self.currdir = os.getcwd() os.chdir(os.path.join(MODULE_DIR, '../../../test_files')) def teardown(self): os.chdir(self.currdir) def test_init(self): print("TEST INIT") sys.stdout.flush() wf = Wavefunction.from_directory('.', True) wf = Wavefunction.from_directory('.', False) wf = Wavefunction.from_files('CONTCAR', 'WAVECAR', 'POTCAR', 'vasprun.xml', True) wf = Wavefunction.from_files('CONTCAR', 'WAVECAR', 'POTCAR', 'vasprun.xml', False) wf = Wavefunction.from_files('CONTCAR', 'WAVECAR2.gz', 'POTCAR', 'vasprun.xml', False) with assert_raises(FileNotFoundError): wf = Wavefunction.from_files('bubbles', 'WAVECAR', 'POTCAR', 'vasprun.xml', True) def test_writestate(self): print("TEST WRITE") sys.stdout.flush() wf = Wavefunction.from_directory('.') fileprefix = '' b, k, s = 10, 1, 0 state1 = wf.write_state_realspace(b, k, s, fileprefix = "", dim=np.array([30,30,30])) wf = Wavefunction.from_directory('.', False) state2 = wf.write_state_realspace(b, k, s, fileprefix = "", dim=np.array([30,30,30])) assert_almost_equal(np.linalg.norm(state1-state2),0) state2 = wf.write_state_realspace(b, k, s, fileprefix = "", dim=np.array([30,30,30]), remove_phase=True) assert state1.shape[0] == 30 assert state1.shape[1] == 30 assert state1.shape[2] == 30 assert state1.dtype == np.complex128 filename_base = "%sB%dK%dS%d" % (fileprefix, b, k, s) filename1 = "%s_REAL" % filename_base filename2 = "%s_IMAG" % filename_base #os.remove(filename1) #os.remove(filename2) with assert_raises(ValueError): wf.write_state_realspace(-1, 0, 0) def test_density(self): print("TEST DENSITY") sys.stdout.flush() wf = Wavefunction.from_directory('nosym') #wf = wf.desymmetrized_copy() wf.write_density_realspace(dim=np.array([40,40,40]), scale = wf.structure.lattice.volume) tstchg = Chgcar.from_file("AECCAR2").data['total']# / wf.structure.volume chg = Chgcar.from_file("PYAECCAR").data['total'] reldiff = np.sqrt(np.mean(((chg-tstchg)/tstchg)**2)) newchg = chg-tstchg Chgcar(Poscar(wf.structure), {'total': newchg}).write_file('DIFFCHGCAR.vasp') print(np.sum(chg)/40**3, np.sum(tstchg)/40**3) assert_almost_equal(reldiff, 0, decimal=2) wf = Wavefunction.from_directory('nosym') res = wf.write_density_realspace(filename="BAND4DENS", bands=4) #os.remove('PYAECCAR') print("DENS shape", res.shape) assert_almost_equal(np.sum(res)*wf.structure.lattice.volume/np.cumprod(res.shape)[-1], 1, 4) def test_state_wf_and_density(self): wf = Wavefunction.from_directory('.') chg_from_wf = np.abs(wf.get_state_realspace(0, 0, 0))**2 chg = wf.get_state_realspace_density(0,0,0,dim=wf.dim) assert_equal(chg.shape, chg_from_wf.shape) dv = wf.structure.volume / np.cumprod(chg.shape)[-1] assert_almost_equal(np.sum(chg)*dv, 1, 3) assert_almost_equal(np.sum(chg_from_wf)*dv, 1, 3) reldiff = np.sqrt(np.mean(np.abs(chg-chg_from_wf))) assert_almost_equal(reldiff, 0, decimal=2) def test_pseudoprojector(self): print("TEST PSEUDO") sys.stdout.flush() # test ps projections wf = Wavefunction.from_directory('.') basis = Wavefunction.from_directory('.') pr = Projector(wf, basis, method = "pseudo") res = pr.single_band_projection(6) assert res.shape[0] == basis.nband * basis.nspin * basis.nwk res = pr.defect_band_analysis(4, 10, False) assert len(res.keys()) == 15 def test_projector(self): print("TEST PROJ") sys.stdout.flush() # test ae projections wf1 = Wavefunction.from_directory('.', False) basis = Wavefunction.from_directory('.', False) pr = Projector(wf1, basis) for b in range(wf1.nband): v, c = pr.proportion_conduction(b) if b < 6: assert_almost_equal(v, 1, decimal=4) assert_almost_equal(c, 0, decimal=8) else: assert_almost_equal(v, 0, decimal=8) assert_almost_equal(c, 1, decimal=4) generator = Projector.setup_multiple_projections('.', ['.', '.']) for wf_dir, wf in generator: wf.defect_band_analysis(4, 10, spinpol=True) wf1 = Wavefunction.from_directory('.', False) basis = Wavefunction.from_directory('.', False) pr = Projector(wf1, basis, 'aug_recip') for b in range(wf1.nband): v, c = pr.proportion_conduction(b) if b < 6: assert_almost_equal(v, 1, decimal=4) assert_almost_equal(c, 0, decimal=8) else: assert_almost_equal(v, 0, decimal=8) assert_almost_equal(c, 1, decimal=4) wf1 = Wavefunction.from_directory('.', False) basis = Wavefunction.from_directory('.', False) pr = Projector(wf1, basis, 'realspace') for b in range(wf1.nband): v, c = pr.proportion_conduction(b) if b < 6: assert_almost_equal(v, 1, decimal=4) assert_almost_equal(c, 0, decimal=8) else: assert_almost_equal(v, 0, decimal=8) assert_almost_equal(c, 1, decimal=4) with assert_raises(ValueError): pr.proportion_conduction(100) pr.proportion_conduction(-1) def test_projector_gz(self): print("TEST PROJGZ") sys.stdout.flush() # test ae projections wf1 = Wavefunction.from_files('CONTCAR', 'WAVECAR2.gz', 'POTCAR', 'vasprun.xml', False) basis = Wavefunction.from_directory('.', False) pr = Projector(wf1, basis) for b in range(wf1.nband): v, c = pr.proportion_conduction(b) if b < 6: assert_almost_equal(v, 1, decimal=4) assert_almost_equal(c, 0, decimal=8) else: assert_almost_equal(v, 0, decimal=8) assert_almost_equal(c, 1, decimal=4) generator = Projector.setup_multiple_projections('.', ['.', '.']) for wf_dir, wf in generator: wf.defect_band_analysis(4, 10, spinpol=True) def test_offsite(self): Projector = DummyProjector print("TEST OFFSITE") sys.stdout.flush() wf1 = Wavefunction.from_directory('nosym', False) basis = Wavefunction.from_directory('nosym', False) print("ENCUT", wf1.encut, basis.encut) pr = Projector(wf1, basis) test_vals = {} for b in range(wf1.nband): v, c = pr.proportion_conduction(b) print("CHECK_VALS", v,c) test_vals[b] = (v,c) for b in range(wf1.nband//2): if b < 6: assert_almost_equal(test_vals[b][0], 1, decimal=2) assert_almost_equal(test_vals[b][1], 0, decimal=4) else: assert_almost_equal(test_vals[b][0], 0, decimal=4) assert_almost_equal(test_vals[b][1], 1, decimal=2) generator = Projector.setup_multiple_projections('.', ['.', '.']) for wf_dir, wf in generator: wf.defect_band_analysis(4, 10, spinpol=True) wf1 = Wavefunction.from_directory('nosym', False) basis = Wavefunction.from_directory('nosym', False) print("ENCUT", wf1.encut, basis.encut) pr = Projector(wf1, basis, 'aug_recip') test_vals = {} for b in range(wf1.nband): v, c = pr.proportion_conduction(b) print("CHECK_VALS", v,c) test_vals[b] = (v,c) for b in range(wf1.nband//2): if b < 6: assert_almost_equal(test_vals[b][0], 1, decimal=2) assert_almost_equal(test_vals[b][1], 0, decimal=4) else: assert_almost_equal(test_vals[b][0], 0, decimal=4) assert_almost_equal(test_vals[b][1], 1, decimal=2) def test_desymmetrization(self): print("TEST DESYM") sys.stdout.flush() # test ae projections wf1 = Wavefunction.from_directory('.', False) basis = Wavefunction.from_directory('nosym', False) pr = Projector(wf1, basis, unsym_wf=True, unsym_basis=True) test_vals = {} for b in range(wf1.nband): v, c = pr.proportion_conduction(b) print("CHECK_VALS", v,c) test_vals[b] = (v,c) for b in range(wf1.nband//2): if b < 6: assert_almost_equal(test_vals[b][0], 1, decimal=3) assert_almost_equal(test_vals[b][1], 0, decimal=7) else: assert_almost_equal(test_vals[b][0], 0, decimal=7) assert_almost_equal(test_vals[b][1], 1, decimal=3) def test_norm(self): wf = Wavefunction.from_directory('.', setup_projectors=True) wf.check_c_projectors() testc.proj_check(wf) def test_writestate_ncl(self): print("TEST WRITE NCL") sys.stdout.flush() from pymatgen.io.vasp.outputs import Chgcar wf = NCLWavefunction.from_directory('noncollinear') fileprefix = '' b, k, s = 10, 1, 0 state1, state2 = wf.write_state_realspace(b, k, s, fileprefix = "") state1, state2 = wf.write_state_realspace(b, k, s, fileprefix = "", dim=np.array([30,30,30])) assert state1.shape[0] == 30 assert state1.shape[1] == 30 assert state1.shape[2] == 30 assert state1.dtype == np.complex128 filename_base = "%sB%dK%dS%d" % (fileprefix, b, k, s) filename1 = "%s_UP_REAL" % filename_base filename2 = "%s_UP_IMAG" % filename_base filename3 = "%s_DOWN_REAL" % filename_base filename4 = "%s_DOWN_IMAG" % filename_base chg1 = Chgcar.from_file(filename1) chg2 = Chgcar.from_file(filename2) chg3 = Chgcar.from_file(filename3) chg4 = Chgcar.from_file(filename4) upart = chg1.data['total']**2 + chg2.data['total']**2 dpart = chg3.data['total']**2 + chg4.data['total']**2 vol = chg1.poscar.structure.volume assert_almost_equal(np.sum((upart + dpart) * vol / 30**3), 1, 2) os.remove(filename1) os.remove(filename2) os.remove(filename3) os.remove(filename4) def test_density_ncl(self): print("TEST DENSITY NCL") sys.stdout.flush() print("LOAD WAVEFUNCTION") sys.stdout.flush() wf = NCLWavefunction.from_directory('noncollinear') print("FINISHED LOAD WAVEFUNCTION") sys.stdout.flush() #wf = wf.desymmetrized_copy() wf.write_density_realspace(scale = wf.structure.lattice.volume) wf.write_density_realspace(dim=np.array([40,40,40]), scale = wf.structure.lattice.volume) tstchg = Chgcar.from_file("AECCAR2").data['total']# / wf.structure.volume chg = Chgcar.from_file("PYAECCAR").data['total'] reldiff = np.sqrt(np.mean(((chg-tstchg)/tstchg)**2)) newchg = chg-tstchg Chgcar(Poscar(wf.structure), {'total': newchg}).write_file('DIFFCHGCAR.vasp') print(np.sum(chg)/40**3, np.sum(tstchg)/40**3) assert_almost_equal(reldiff, 0, decimal=3) def test_flip_spin(self): wf = Wavefunction.from_directory('.', False) basis = Wavefunction.from_directory('.', False) pr = Projector(wf, basis) for b in range(wf.nband): res = pr.single_band_projection(b, flip_spin=True) res = np.abs(res)**2 print(b,res) for br in range(basis.nband): expected = 1 if b == br else 0 decimal = 4 if b == br else 8 for k in range(basis.nspin * basis.nwk): assert_almost_equal(np.sum(res[br*basis.nwk*basis.nspin + k]), expected, decimal=decimal) pr = Projector(wf, basis, method='aug_recip') for b in range(wf.nband): res = pr.single_band_projection(b, flip_spin=True) res = np.abs(res)**2 print(b,res) for br in range(basis.nband): expected = 1 if b == br else 0 decimal = 4 if b == br else 8 for k in range(basis.nspin * basis.nwk): assert_almost_equal(np.sum(res[br*basis.nwk*basis.nspin + k]), expected, decimal=decimal)
[ "os.remove", "pawpyseed.core.projector.Projector.setup_multiple_projections", "numpy.sum", "numpy.abs", "scipy.interpolate.CubicSpline", "numpy.mean", "sys.stdout.flush", "numpy.exp", "numpy.linalg.norm", "numpy.sin", "os.path.join", "os.chdir", "os.path.abspath", "numpy.cumprod", "pawpy...
[((688, 713), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (703, 713), False, 'import os, subprocess, sys\n'), ((1295, 1306), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1304, 1306), False, 'import os, subprocess, sys\n'), ((1379, 1401), 'pymatgen.io.vasp.outputs.Vasprun', 'Vasprun', (['"""vasprun.xml"""'], {}), "('vasprun.xml')\n", (1386, 1401), False, 'from pymatgen.io.vasp.outputs import Vasprun, Chgcar\n'), ((1477, 1499), 'os.chdir', 'os.chdir', (['self.currdir'], {}), '(self.currdir)\n', (1485, 1499), False, 'import os, subprocess, sys\n'), ((1534, 1558), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10000)'], {}), '(0, 1, 10000)\n', (1545, 1558), True, 'import numpy as np\n'), ((1564, 1584), 'numpy.zeros', 'np.zeros', (['(10000 * 16)'], {}), '(10000 * 16)\n', (1572, 1584), True, 'import numpy as np\n'), ((1591, 1611), 'numpy.zeros', 'np.zeros', (['(10000 * 16)'], {}), '(10000 * 16)\n', (1599, 1611), True, 'import numpy as np\n'), ((3475, 3494), 'numpy.zeros', 'np.zeros', (['tst.shape'], {}), '(tst.shape)\n', (3483, 3494), True, 'import numpy as np\n'), ((3497, 3548), 'pawpyseed.core.pawpyc.interpolate', 'pawpyc.interpolate', (['res2', 'tst', 'x', 'y', 'rmax', '(100)', '(400)'], {}), '(res2, tst, x, y, rmax, 100, 400)\n', (3515, 3548), False, 'from pawpyseed.core import pawpyc\n'), ((3606, 3624), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3622, 3624), False, 'import os, subprocess, sys\n'), ((3697, 3732), 'numpy.array', 'np.array', (['vr.actual_kpoints_weights'], {}), '(vr.actual_kpoints_weights)\n', (3705, 3732), True, 'import numpy as np\n'), ((3828, 3848), 'numpy.testing.assert_equal', 'assert_equal', (['res', '(0)'], {}), '(res, 0)\n', (3840, 3848), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((4057, 4110), 'pawpyseed.core.pawpyc.spherical_bessel_transform', 'pawpyc.spherical_bessel_transform', (['(1000000.0)', '(0)', 'r', 'f'], {}), '(1000000.0, 0, r, f)\n', (4090, 4110), False, 'from pawpyseed.core import pawpyc\n'), ((4162, 4179), 'numpy.trapz', 'np.trapz', (['vals', 'r'], {}), '(vals, r)\n', (4170, 4179), True, 'import numpy as np\n'), ((4238, 4288), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['integral', 'res[180]'], {'decimal': '(3)'}), '(integral, res[180], decimal=3)\n', (4257, 4288), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((4322, 4337), 'numpy.cumsum', 'np.cumsum', (['perc'], {}), '(perc)\n', (4331, 4337), True, 'import numpy as np\n'), ((4348, 4360), 'numpy.max', 'np.max', (['perc'], {}), '(perc)\n', (4354, 4360), True, 'import numpy as np\n'), ((6842, 6861), 'numpy.exp', 'np.exp', (['(-a * r ** 2)'], {}), '(-a * r ** 2)\n', (6848, 6861), True, 'import numpy as np\n'), ((6872, 6891), 'numpy.exp', 'np.exp', (['(-b * r ** 2)'], {}), '(-b * r ** 2)\n', (6878, 6891), True, 'import numpy as np\n'), ((9582, 9593), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9591, 9593), False, 'import os, subprocess, sys\n'), ((9881, 9903), 'numpy.array', 'np.array', (['[]', 'np.int32'], {}), '([], np.int32)\n', (9889, 9903), True, 'import numpy as np\n'), ((9911, 9933), 'numpy.array', 'np.array', (['[]', 'np.int32'], {}), '([], np.int32)\n', (9919, 9933), True, 'import numpy as np\n'), ((9949, 9973), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (9957, 9973), True, 'import numpy as np\n'), ((9986, 10010), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (9994, 10010), True, 'import numpy as np\n'), ((10023, 10047), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (10031, 10047), True, 'import numpy as np\n'), ((10059, 10083), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (10067, 10083), True, 'import numpy as np\n'), ((10095, 10119), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (10103, 10119), True, 'import numpy as np\n'), ((10740, 10764), 'numpy.array', 'np.array', (['[]', 'np.float64'], {}), '([], np.float64)\n', (10748, 10764), True, 'import numpy as np\n'), ((11739, 11765), 'os.remove', 'os.remove', (['"""potholder.txt"""'], {}), "('potholder.txt')\n", (11748, 11765), False, 'import os, subprocess, sys\n'), ((11768, 11790), 'os.chdir', 'os.chdir', (['self.currdir'], {}), '(self.currdir)\n', (11776, 11790), False, 'import os, subprocess, sys\n'), ((12034, 12045), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (12043, 12045), False, 'import os, subprocess, sys\n'), ((12130, 12152), 'os.chdir', 'os.chdir', (['self.currdir'], {}), '(self.currdir)\n', (12138, 12152), False, 'import os, subprocess, sys\n'), ((12199, 12217), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (12215, 12217), False, 'import os, subprocess, sys\n'), ((12761, 12779), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (12777, 12779), False, 'import os, subprocess, sys\n'), ((13696, 13714), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (13712, 13714), False, 'import os, subprocess, sys\n'), ((14218, 14260), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['reldiff', '(0)'], {'decimal': '(2)'}), '(reldiff, 0, decimal=2)\n', (14237, 14260), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((14721, 14763), 'numpy.testing.assert_equal', 'assert_equal', (['chg.shape', 'chg_from_wf.shape'], {}), '(chg.shape, chg_from_wf.shape)\n', (14733, 14763), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((14971, 15013), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['reldiff', '(0)'], {'decimal': '(2)'}), '(reldiff, 0, decimal=2)\n', (14990, 15013), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((15073, 15091), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (15089, 15091), False, 'import os, subprocess, sys\n'), ((15206, 15243), 'pawpyseed.core.projector.Projector', 'Projector', (['wf', 'basis'], {'method': '"""pseudo"""'}), "(wf, basis, method='pseudo')\n", (15215, 15243), False, 'from pawpyseed.core.projector import Projector\n'), ((15474, 15492), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (15490, 15492), False, 'import os, subprocess, sys\n'), ((15622, 15643), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis'], {}), '(wf1, basis)\n', (15631, 15643), False, 'from pawpyseed.core.projector import Projector\n'), ((15912, 15965), 'pawpyseed.core.projector.Projector.setup_multiple_projections', 'Projector.setup_multiple_projections', (['"""."""', "['.', '.']"], {}), "('.', ['.', '.'])\n", (15948, 15965), False, 'from pawpyseed.core.projector import Projector\n'), ((16151, 16185), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis', '"""aug_recip"""'], {}), "(wf1, basis, 'aug_recip')\n", (16160, 16185), False, 'from pawpyseed.core.projector import Projector\n'), ((16545, 16579), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis', '"""realspace"""'], {}), "(wf1, basis, 'realspace')\n", (16554, 16579), False, 'from pawpyseed.core.projector import Projector\n'), ((16989, 17007), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (17005, 17007), False, 'import os, subprocess, sys\n'), ((17182, 17203), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis'], {}), '(wf1, basis)\n', (17191, 17203), False, 'from pawpyseed.core.projector import Projector\n'), ((17472, 17525), 'pawpyseed.core.projector.Projector.setup_multiple_projections', 'Projector.setup_multiple_projections', (['"""."""', "['.', '.']"], {}), "('.', ['.', '.'])\n", (17508, 17525), False, 'from pawpyseed.core.projector import Projector\n'), ((17686, 17704), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (17702, 17704), False, 'import os, subprocess, sys\n'), ((17859, 17880), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis'], {}), '(wf1, basis)\n', (17868, 17880), False, 'from pawpyseed.core.projector import Projector\n'), ((18306, 18359), 'pawpyseed.core.projector.Projector.setup_multiple_projections', 'Projector.setup_multiple_projections', (['"""."""', "['.', '.']"], {}), "('.', ['.', '.'])\n", (18342, 18359), False, 'from pawpyseed.core.projector import Projector\n'), ((18594, 18628), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis', '"""aug_recip"""'], {}), "(wf1, basis, 'aug_recip')\n", (18603, 18628), False, 'from pawpyseed.core.projector import Projector\n'), ((19098, 19116), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (19114, 19116), False, 'import os, subprocess, sys\n'), ((19250, 19304), 'pawpyseed.core.projector.Projector', 'Projector', (['wf1', 'basis'], {'unsym_wf': '(True)', 'unsym_basis': '(True)'}), '(wf1, basis, unsym_wf=True, unsym_basis=True)\n', (19259, 19304), False, 'from pawpyseed.core.projector import Projector\n'), ((19829, 19849), 'pawpyseed.core.tests.testc.proj_check', 'testc.proj_check', (['wf'], {}), '(wf)\n', (19845, 19849), False, 'from pawpyseed.core.tests import testc\n'), ((19911, 19929), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (19927, 19929), False, 'import os, subprocess, sys\n'), ((19983, 20029), 'pawpyseed.core.noncollinear.NCLWavefunction.from_directory', 'NCLWavefunction.from_directory', (['"""noncollinear"""'], {}), "('noncollinear')\n", (20013, 20029), False, 'from pawpyseed.core.noncollinear import NCLWavefunction\n'), ((20612, 20639), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['filename1'], {}), '(filename1)\n', (20628, 20639), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((20649, 20676), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['filename2'], {}), '(filename2)\n', (20665, 20676), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((20686, 20713), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['filename3'], {}), '(filename3)\n', (20702, 20713), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((20723, 20750), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['filename4'], {}), '(filename4)\n', (20739, 20750), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((20969, 20989), 'os.remove', 'os.remove', (['filename1'], {}), '(filename1)\n', (20978, 20989), False, 'import os, subprocess, sys\n'), ((20992, 21012), 'os.remove', 'os.remove', (['filename2'], {}), '(filename2)\n', (21001, 21012), False, 'import os, subprocess, sys\n'), ((21015, 21035), 'os.remove', 'os.remove', (['filename3'], {}), '(filename3)\n', (21024, 21035), False, 'import os, subprocess, sys\n'), ((21038, 21058), 'os.remove', 'os.remove', (['filename4'], {}), '(filename4)\n', (21047, 21058), False, 'import os, subprocess, sys\n'), ((21119, 21137), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (21135, 21137), False, 'import os, subprocess, sys\n'), ((21169, 21187), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (21185, 21187), False, 'import os, subprocess, sys\n'), ((21195, 21241), 'pawpyseed.core.noncollinear.NCLWavefunction.from_directory', 'NCLWavefunction.from_directory', (['"""noncollinear"""'], {}), "('noncollinear')\n", (21225, 21241), False, 'from pawpyseed.core.noncollinear import NCLWavefunction\n'), ((21282, 21300), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (21298, 21300), False, 'import os, subprocess, sys\n'), ((21826, 21868), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['reldiff', '(0)'], {'decimal': '(3)'}), '(reldiff, 0, decimal=3)\n', (21845, 21868), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((22002, 22022), 'pawpyseed.core.projector.Projector', 'Projector', (['wf', 'basis'], {}), '(wf, basis)\n', (22011, 22022), False, 'from pawpyseed.core.projector import Projector\n'), ((22405, 22445), 'pawpyseed.core.projector.Projector', 'Projector', (['wf', 'basis'], {'method': '"""aug_recip"""'}), "(wf, basis, method='aug_recip')\n", (22414, 22445), False, 'from pawpyseed.core.projector import Projector\n'), ((1318, 1365), 'os.path.join', 'os.path.join', (['MODULE_DIR', '"""../../../test_files"""'], {}), "(MODULE_DIR, '../../../test_files')\n", (1330, 1365), False, 'import os, subprocess, sys\n'), ((1425, 1451), 'pymatgen.io.vasp.inputs.Potcar.from_file', 'Potcar.from_file', (['"""POTCAR"""'], {}), "('POTCAR')\n", (1441, 1451), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((1894, 1918), 'numpy.linalg.norm', 'np.linalg.norm', (['(ys - ys2)'], {}), '(ys - ys2)\n', (1908, 1918), True, 'import numpy as np\n'), ((2643, 2670), 'pymatgen.io.vasp.inputs.Poscar.from_file', 'Poscar.from_file', (['"""CONTCAR"""'], {}), "('CONTCAR')\n", (2659, 2670), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((2856, 2882), 'numpy.copy', 'np.copy', (['fcoord'], {'order': '"""C"""'}), "(fcoord, order='C')\n", (2863, 2882), True, 'import numpy as np\n'), ((2886, 2926), 'pawpyseed.core.pawpyc.frac_to_cartesian', 'pawpyc.frac_to_cartesian', (['temp1', 'lattice'], {}), '(temp1, lattice)\n', (2910, 2926), False, 'from pawpyseed.core import pawpyc\n'), ((2995, 3020), 'numpy.copy', 'np.copy', (['coord'], {'order': '"""C"""'}), "(coord, order='C')\n", (3002, 3020), True, 'import numpy as np\n'), ((3024, 3067), 'pawpyseed.core.pawpyc.cartesian_to_frac', 'pawpyc.cartesian_to_frac', (['temp2', 'reclattice'], {}), '(temp2, reclattice)\n', (3048, 3067), False, 'from pawpyseed.core import pawpyc\n'), ((3192, 3219), 'pymatgen.io.vasp.inputs.Poscar.from_file', 'Poscar.from_file', (['"""CONTCAR"""'], {}), "('CONTCAR')\n", (3208, 3219), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((3371, 3431), 'scipy.interpolate.CubicSpline', 'CubicSpline', (['grid', 'vals'], {'extrapolate': '(True)', 'bc_type': '"""natural"""'}), "(grid, vals, extrapolate=True, bc_type='natural')\n", (3382, 3431), False, 'from scipy.interpolate import CubicSpline\n'), ((3571, 3598), 'numpy.linalg.norm', 'np.linalg.norm', (['(res1 - res2)'], {}), '(res1 - res2)\n', (3585, 3598), True, 'import numpy as np\n'), ((3777, 3826), 'numpy.array', 'np.array', (['[20, 20, 20]'], {'dtype': 'np.int32', 'order': '"""C"""'}), "([20, 20, 20], dtype=np.int32, order='C')\n", (3785, 3826), True, 'import numpy as np\n'), ((3936, 3962), 'pymatgen.io.vasp.inputs.Potcar.from_file', 'Potcar.from_file', (['"""POTCAR"""'], {}), "('POTCAR')\n", (3952, 3962), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((6915, 6955), 'numpy.array', 'np.array', (['B'], {'dtype': 'np.float64', 'order': '"""C"""'}), "(B, dtype=np.float64, order='C')\n", (6923, 6955), True, 'import numpy as np\n'), ((9605, 9652), 'os.path.join', 'os.path.join', (['MODULE_DIR', '"""../../../test_files"""'], {}), "(MODULE_DIR, '../../../test_files')\n", (9617, 9652), False, 'import os, subprocess, sys\n'), ((9668, 9695), 'pymatgen.io.vasp.inputs.Poscar.from_file', 'Poscar.from_file', (['"""CONTCAR"""'], {}), "('CONTCAR')\n", (9684, 9695), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((9724, 9750), 'pymatgen.io.vasp.inputs.Potcar.from_file', 'Potcar.from_file', (['"""POTCAR"""'], {}), "('POTCAR')\n", (9740, 9750), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((10253, 10273), 'numpy.append', 'np.append', (['ls', 'pp.ls'], {}), '(ls, pp.ls)\n', (10262, 10273), True, 'import numpy as np\n'), ((10286, 10312), 'numpy.append', 'np.append', (['wgrids', 'pp.grid'], {}), '(wgrids, pp.grid)\n', (10295, 10312), True, 'import numpy as np\n'), ((10325, 10355), 'numpy.append', 'np.append', (['pgrids', 'pp.projgrid'], {}), '(pgrids, pp.projgrid)\n', (10334, 10355), True, 'import numpy as np\n'), ((10804, 10840), 'numpy.append', 'np.append', (['selfcoords', 's.frac_coords'], {}), '(selfcoords, s.frac_coords)\n', (10813, 10840), True, 'import numpy as np\n'), ((12057, 12104), 'os.path.join', 'os.path.join', (['MODULE_DIR', '"""../../../test_files"""'], {}), "(MODULE_DIR, '../../../test_files')\n", (12069, 12104), False, 'import os, subprocess, sys\n'), ((12585, 12617), 'numpy.testing.assert_raises', 'assert_raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (12598, 12617), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((13112, 13143), 'numpy.linalg.norm', 'np.linalg.norm', (['(state1 - state2)'], {}), '(state1 - state2)\n', (13126, 13143), True, 'import numpy as np\n'), ((13579, 13604), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (13592, 13604), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((14030, 14069), 'numpy.mean', 'np.mean', (['(((chg - tstchg) / tstchg) ** 2)'], {}), '(((chg - tstchg) / tstchg) ** 2)\n', (14037, 14069), True, 'import numpy as np\n'), ((16841, 16866), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError'], {}), '(ValueError)\n', (16854, 16866), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((20922, 20961), 'numpy.sum', 'np.sum', (['((upart + dpart) * vol / 30 ** 3)'], {}), '((upart + dpart) * vol / 30 ** 3)\n', (20928, 20961), True, 'import numpy as np\n'), ((21638, 21677), 'numpy.mean', 'np.mean', (['(((chg - tstchg) / tstchg) ** 2)'], {}), '(((chg - tstchg) / tstchg) ** 2)\n', (21645, 21677), True, 'import numpy as np\n'), ((2000, 2022), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (2011, 2022), True, 'import numpy as np\n'), ((2030, 2060), 'numpy.zeros', 'np.zeros', (['(10000)', 'np.complex128'], {}), '(10000, np.complex128)\n', (2038, 2060), True, 'import numpy as np\n'), ((2071, 2101), 'numpy.zeros', 'np.zeros', (['(10000)', 'np.complex128'], {}), '(10000, np.complex128)\n', (2079, 2101), True, 'import numpy as np\n'), ((2112, 2142), 'numpy.zeros', 'np.zeros', (['(10000)', 'np.complex128'], {}), '(10000, np.complex128)\n', (2120, 2142), True, 'import numpy as np\n'), ((2950, 2979), 'numpy.linalg.norm', 'np.linalg.norm', (['(temp1 - coord)'], {}), '(temp1 - coord)\n', (2964, 2979), True, 'import numpy as np\n'), ((3091, 3121), 'numpy.linalg.norm', 'np.linalg.norm', (['(temp2 - fcoord)'], {}), '(temp2 - fcoord)\n', (3105, 3121), True, 'import numpy as np\n'), ((4128, 4140), 'scipy.special.spherical_jn', 'jn', (['(0)', '(r * k)'], {}), '(0, r * k)\n', (4130, 4140), True, 'from scipy.special import spherical_jn as jn\n'), ((4539, 4549), 'nose.SkipTest', 'SkipTest', ([], {}), '()\n', (4547, 4549), False, 'from nose import SkipTest\n'), ((6799, 6812), 'numpy.log', 'np.log', (['(0.001)'], {}), '(0.001)\n', (6805, 6812), True, 'import numpy as np\n'), ((6813, 6822), 'numpy.log', 'np.log', (['(4)'], {}), '(4)\n', (6819, 6822), True, 'import numpy as np\n'), ((9485, 9505), 'scipy.special.sph_harm', 'sph_harm', (['m', 'n', 'o', 'p'], {}), '(m, n, o, p)\n', (9493, 9505), False, 'from scipy.special import lpmn, sph_harm\n'), ((10497, 10524), 'numpy.append', 'np.append', (['projectors', 'proj'], {}), '(projectors, proj)\n', (10506, 10524), True, 'import numpy as np\n'), ((10539, 10563), 'numpy.append', 'np.append', (['aewaves', 'aepw'], {}), '(aewaves, aepw)\n', (10548, 10563), True, 'import numpy as np\n'), ((10578, 10602), 'numpy.append', 'np.append', (['pswaves', 'pspw'], {}), '(pswaves, pspw)\n', (10587, 10602), True, 'import numpy as np\n'), ((12929, 12951), 'numpy.array', 'np.array', (['[30, 30, 30]'], {}), '([30, 30, 30])\n', (12937, 12951), True, 'import numpy as np\n'), ((13068, 13090), 'numpy.array', 'np.array', (['[30, 30, 30]'], {}), '([30, 30, 30])\n', (13076, 13090), True, 'import numpy as np\n'), ((13215, 13237), 'numpy.array', 'np.array', (['[30, 30, 30]'], {}), '([30, 30, 30])\n', (13223, 13237), True, 'import numpy as np\n'), ((13824, 13846), 'numpy.array', 'np.array', (['[40, 40, 40]'], {}), '([40, 40, 40])\n', (13832, 13846), True, 'import numpy as np\n'), ((13894, 13921), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['"""AECCAR2"""'], {}), "('AECCAR2')\n", (13910, 13921), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((13967, 13995), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['"""PYAECCAR"""'], {}), "('PYAECCAR')\n", (13983, 13995), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((14175, 14186), 'numpy.sum', 'np.sum', (['chg'], {}), '(chg)\n', (14181, 14186), True, 'import numpy as np\n'), ((14194, 14208), 'numpy.sum', 'np.sum', (['tstchg'], {}), '(tstchg)\n', (14200, 14208), True, 'import numpy as np\n'), ((14793, 14814), 'numpy.cumprod', 'np.cumprod', (['chg.shape'], {}), '(chg.shape)\n', (14803, 14814), True, 'import numpy as np\n'), ((14841, 14852), 'numpy.sum', 'np.sum', (['chg'], {}), '(chg)\n', (14847, 14852), True, 'import numpy as np\n'), ((14885, 14904), 'numpy.sum', 'np.sum', (['chg_from_wf'], {}), '(chg_from_wf)\n', (14891, 14904), True, 'import numpy as np\n'), ((14943, 14968), 'numpy.abs', 'np.abs', (['(chg - chg_from_wf)'], {}), '(chg - chg_from_wf)\n', (14949, 14968), True, 'import numpy as np\n'), ((15728, 15764), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(1)'], {'decimal': '(4)'}), '(v, 1, decimal=4)\n', (15747, 15764), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((15769, 15805), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(0)'], {'decimal': '(8)'}), '(c, 0, decimal=8)\n', (15788, 15805), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((15819, 15855), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(0)'], {'decimal': '(8)'}), '(v, 0, decimal=8)\n', (15838, 15855), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((15860, 15896), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(1)'], {'decimal': '(4)'}), '(c, 1, decimal=4)\n', (15879, 15896), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16270, 16306), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(1)'], {'decimal': '(4)'}), '(v, 1, decimal=4)\n', (16289, 16306), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16311, 16347), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(0)'], {'decimal': '(8)'}), '(c, 0, decimal=8)\n', (16330, 16347), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16361, 16397), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(0)'], {'decimal': '(8)'}), '(v, 0, decimal=8)\n', (16380, 16397), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16402, 16438), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(1)'], {'decimal': '(4)'}), '(c, 1, decimal=4)\n', (16421, 16438), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16664, 16700), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(1)'], {'decimal': '(4)'}), '(v, 1, decimal=4)\n', (16683, 16700), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16705, 16741), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(0)'], {'decimal': '(8)'}), '(c, 0, decimal=8)\n', (16724, 16741), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16755, 16791), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(0)'], {'decimal': '(8)'}), '(v, 0, decimal=8)\n', (16774, 16791), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((16796, 16832), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(1)'], {'decimal': '(4)'}), '(c, 1, decimal=4)\n', (16815, 16832), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((17288, 17324), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(1)'], {'decimal': '(4)'}), '(v, 1, decimal=4)\n', (17307, 17324), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((17329, 17365), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(0)'], {'decimal': '(8)'}), '(c, 0, decimal=8)\n', (17348, 17365), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((17379, 17415), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', '(0)'], {'decimal': '(8)'}), '(v, 0, decimal=8)\n', (17398, 17415), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((17420, 17456), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['c', '(1)'], {'decimal': '(4)'}), '(c, 1, decimal=4)\n', (17439, 17456), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18066, 18116), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(1)'], {'decimal': '(2)'}), '(test_vals[b][0], 1, decimal=2)\n', (18085, 18116), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18121, 18171), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(0)'], {'decimal': '(4)'}), '(test_vals[b][1], 0, decimal=4)\n', (18140, 18171), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18185, 18235), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(0)'], {'decimal': '(4)'}), '(test_vals[b][0], 0, decimal=4)\n', (18204, 18235), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18240, 18290), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(1)'], {'decimal': '(2)'}), '(test_vals[b][1], 1, decimal=2)\n', (18259, 18290), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18814, 18864), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(1)'], {'decimal': '(2)'}), '(test_vals[b][0], 1, decimal=2)\n', (18833, 18864), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18869, 18919), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(0)'], {'decimal': '(4)'}), '(test_vals[b][1], 0, decimal=4)\n', (18888, 18919), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18933, 18983), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(0)'], {'decimal': '(4)'}), '(test_vals[b][0], 0, decimal=4)\n', (18952, 18983), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((18988, 19038), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(1)'], {'decimal': '(2)'}), '(test_vals[b][1], 1, decimal=2)\n', (19007, 19038), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((19490, 19540), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(1)'], {'decimal': '(3)'}), '(test_vals[b][0], 1, decimal=3)\n', (19509, 19540), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((19545, 19595), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(0)'], {'decimal': '(7)'}), '(test_vals[b][1], 0, decimal=7)\n', (19564, 19595), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((19609, 19659), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][0]', '(0)'], {'decimal': '(7)'}), '(test_vals[b][0], 0, decimal=7)\n', (19628, 19659), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((19664, 19714), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['test_vals[b][1]', '(1)'], {'decimal': '(3)'}), '(test_vals[b][1], 1, decimal=3)\n', (19683, 19714), False, 'from numpy.testing import assert_almost_equal, assert_equal, assert_raises\n'), ((20217, 20239), 'numpy.array', 'np.array', (['[30, 30, 30]'], {}), '([30, 30, 30])\n', (20225, 20239), True, 'import numpy as np\n'), ((21432, 21454), 'numpy.array', 'np.array', (['[40, 40, 40]'], {}), '([40, 40, 40])\n', (21440, 21454), True, 'import numpy as np\n'), ((21502, 21529), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['"""AECCAR2"""'], {}), "('AECCAR2')\n", (21518, 21529), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((21575, 21603), 'pymatgen.io.vasp.outputs.Chgcar.from_file', 'Chgcar.from_file', (['"""PYAECCAR"""'], {}), "('PYAECCAR')\n", (21591, 21603), False, 'from pymatgen.io.vasp.outputs import Chgcar\n'), ((21783, 21794), 'numpy.sum', 'np.sum', (['chg'], {}), '(chg)\n', (21789, 21794), True, 'import numpy as np\n'), ((21802, 21816), 'numpy.sum', 'np.sum', (['tstchg'], {}), '(tstchg)\n', (21808, 21816), True, 'import numpy as np\n'), ((22114, 22125), 'numpy.abs', 'np.abs', (['res'], {}), '(res)\n', (22120, 22125), True, 'import numpy as np\n'), ((22537, 22548), 'numpy.abs', 'np.abs', (['res'], {}), '(res)\n', (22543, 22548), True, 'import numpy as np\n'), ((1843, 1871), 'pawpyseed.core.pawpyc.legendre', 'pawpyc.legendre', (['l', 'm', 'xs[i]'], {}), '(l, m, xs[i])\n', (1858, 1871), False, 'from pawpyseed.core import pawpyc\n'), ((2517, 2541), 'numpy.linalg.norm', 'np.linalg.norm', (['(ys - ys1)'], {}), '(ys - ys1)\n', (2531, 2541), True, 'import numpy as np\n'), ((2569, 2594), 'numpy.linalg.norm', 'np.linalg.norm', (['(ys1 - ys2)'], {}), '(ys1 - ys2)\n', (2583, 2594), True, 'import numpy as np\n'), ((7625, 7699), 'pawpyseed.core.pawpyc.reciprocal_offsite_wave_overlap', 'pawpyc.reciprocal_offsite_wave_overlap', (['Barr', 'r', 'f1', 'r', 'f2', 'l1', 'm1', 'l2', 'm2'], {}), '(Barr, r, f1, r, f2, l1, m1, l2, m2)\n', (7663, 7699), False, 'from pawpyseed.core import pawpyc\n'), ((14096, 14116), 'pymatgen.io.vasp.inputs.Poscar', 'Poscar', (['wf.structure'], {}), '(wf.structure)\n', (14102, 14116), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((14451, 14462), 'numpy.sum', 'np.sum', (['res'], {}), '(res)\n', (14457, 14462), True, 'import numpy as np\n'), ((14491, 14512), 'numpy.cumprod', 'np.cumprod', (['res.shape'], {}), '(res.shape)\n', (14501, 14512), True, 'import numpy as np\n'), ((21704, 21724), 'pymatgen.io.vasp.inputs.Poscar', 'Poscar', (['wf.structure'], {}), '(wf.structure)\n', (21710, 21724), False, 'from pymatgen.io.vasp.inputs import Poscar, Potcar\n'), ((1662, 1680), 'scipy.special.lpmn', 'lpmn', (['(-3)', '(3)', 'xs[i]'], {}), '(-3, 3, xs[i])\n', (1666, 1680), False, 'from scipy.special import lpmn, sph_harm\n'), ((1706, 1724), 'scipy.special.lpmn', 'lpmn', (['(-3)', '(3)', 'xs[i]'], {}), '(-3, 3, xs[i])\n', (1710, 1724), False, 'from scipy.special import lpmn, sph_harm\n'), ((2230, 2278), 'scipy.special.sph_harm', 'sph_harm', (['m', 'l', '(xs[j] * 2 * np.pi)', '(xs[i] * np.pi)'], {}), '(m, l, xs[j] * 2 * np.pi, xs[i] * np.pi)\n', (2238, 2278), False, 'from scipy.special import lpmn, sph_harm\n'), ((2373, 2423), 'pawpyseed.core.pawpyc.Ylm', 'pawpyc.Ylm', (['l', 'm', '(xs[i] * np.pi)', '(xs[j] * np.pi * 2)'], {}), '(l, m, xs[i] * np.pi, xs[j] * np.pi * 2)\n', (2383, 2423), False, 'from pawpyseed.core import pawpyc\n'), ((7411, 7421), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7418, 7421), True, 'import numpy as np\n'), ((7452, 7462), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7459, 7462), True, 'import numpy as np\n'), ((7471, 7488), 'numpy.linalg.norm', 'np.linalg.norm', (['B'], {}), '(B)\n', (7485, 7488), True, 'import numpy as np\n'), ((7835, 7846), 'numpy.abs', 'np.abs', (['ov1'], {}), '(ov1)\n', (7841, 7846), True, 'import numpy as np\n'), ((22317, 22362), 'numpy.sum', 'np.sum', (['res[br * basis.nwk * basis.nspin + k]'], {}), '(res[br * basis.nwk * basis.nspin + k])\n', (22323, 22362), True, 'import numpy as np\n'), ((22740, 22785), 'numpy.sum', 'np.sum', (['res[br * basis.nwk * basis.nspin + k]'], {}), '(res[br * basis.nwk * basis.nspin + k])\n', (22746, 22785), True, 'import numpy as np\n'), ((2457, 2478), 'numpy.cos', 'np.cos', (['(xs[i] * np.pi)'], {}), '(xs[i] * np.pi)\n', (2463, 2478), True, 'import numpy as np\n'), ((7721, 7732), 'numpy.abs', 'np.abs', (['ov1'], {}), '(ov1)\n', (7727, 7732), True, 'import numpy as np\n'), ((7882, 7893), 'numpy.abs', 'np.abs', (['ov2'], {}), '(ov2)\n', (7888, 7893), True, 'import numpy as np\n'), ((7746, 7763), 'numpy.abs', 'np.abs', (['(ov1 - ov2)'], {}), '(ov1 - ov2)\n', (7752, 7763), True, 'import numpy as np\n'), ((7765, 7776), 'numpy.abs', 'np.abs', (['ov1'], {}), '(ov1)\n', (7771, 7776), True, 'import numpy as np\n'), ((7940, 7957), 'numpy.abs', 'np.abs', (['(ov1 - ov2)'], {}), '(ov1 - ov2)\n', (7946, 7957), True, 'import numpy as np\n'), ((7959, 7970), 'numpy.abs', 'np.abs', (['ov1'], {}), '(ov1)\n', (7965, 7970), True, 'import numpy as np\n'), ((6098, 6113), 'scipy.special.factorial2', 'fac2', (['(2 * n + 1)'], {}), '(2 * n + 1)\n', (6102, 6113), True, 'from scipy.special import factorial2 as fac2\n'), ((7332, 7346), 'numpy.conj', 'np.conj', (['coef2'], {}), '(coef2)\n', (7339, 7346), True, 'import numpy as np\n'), ((9432, 9441), 'numpy.cos', 'np.cos', (['o'], {}), '(o)\n', (9438, 9441), True, 'import numpy as np\n'), ((5021, 5073), 'pawpyseed.core.tests.reference.overlap', 'gint.overlap', (['a', '(i1, j1, k1)', 'A', 'b', '(i2, j2, k2)', 'B'], {}), '(a, (i1, j1, k1), A, b, (i2, j2, k2), B)\n', (5033, 5073), True, 'import pawpyseed.core.tests.reference as gint\n'), ((9394, 9403), 'numpy.sin', 'np.sin', (['o'], {}), '(o)\n', (9400, 9403), True, 'import numpy as np\n'), ((9404, 9413), 'numpy.sin', 'np.sin', (['p'], {}), '(p)\n', (9410, 9413), True, 'import numpy as np\n'), ((9356, 9365), 'numpy.sin', 'np.sin', (['o'], {}), '(o)\n', (9362, 9365), True, 'import numpy as np\n'), ((9366, 9375), 'numpy.cos', 'np.cos', (['p'], {}), '(p)\n', (9372, 9375), True, 'import numpy as np\n')]
from .path_alg import solve_path_Conc import numpy as np import numpy.linalg as LA from .misc_functions import unpenalized r""" Problem : min ||Ab - y||^2/sigma + n/2 sigma + lambda ||b||1 with C.b= 0 and sigma > 0 Dimensions : A : m*d ; y : m ; b : d ; C : k*d The first function compute a solution of a Lasso problem for a given lambda. The parameters are lam (lambda/lambdamax, \in [0,1]) and pb, which has to be a 'problem_LS type', which is defined bellow in order to contain all the important parameters of the problem. One can initialise it this way : pb = class_of_problem.problem(data = (A,C,y),type_of_algo). We solve the problem without normalizing anything. """ tol = 1e-5 def Classo_R3(pb, lam): pb_type = pb.type # can be 'Path-Alg' or 'DR' (m, d, k), (A, C, y) = pb.dim, pb.matrix sigmax = pb.sigmax if lam < 1e-5: beta = unpenalized(pb.matrix) sigma = LA.norm(A.dot(beta) - y) / np.sqrt(m / 2) return beta, sigma # Path algorithm # here we compute the path algo until our lambda, and just take the last beta # here we use our path algorithm for concomitant problem, and then only takes the last beta. # Actually, the function solve_path_Conc has the argument concomitant = 'fix_lam' so it means it will directly stop when it has to. # Then we only have to finc the solution between the last beta computed and the one before. if pb_type == "Path-Alg": (beta1, beta2), (s1, s2), (r1, r2) = solve_path_Conc( (A, C, y), lam, lassopath=False ) dr, ds = r1 - r2, s1 - s2 teta = root_2( LA.norm(dr) ** 2 - ds ** 2, np.vdot(dr, r2) - s2 * ds, LA.norm(r2) ** 2 - s2 ** 2, ) sigma = (s1 * teta + s2 * (1 - teta)) * sigmax beta = beta1 * teta + beta2 * (1 - teta) return (beta, sigma) else: # DR regpath = pb.regpath if not regpath: pb.compute_param() lamb = lam * pb.lambdamax Anorm = pb.Anorm tol = pb.tol * LA.norm(y) / Anorm # tolerance rescaled Proj = proj_c(C, d) # Proj = I - C^t . (C . C^t )^-1 . C QA = pb.QA Q1 = pb.Q1 Q2 = pb.Q2 # Save some matrix products already computed in problem.compute_param() gamma = pb.gam / (pb.Anorm2 * lam) # Normalize gamma w = lamb * gamma * pb.weights zerod = np.zeros(d) # two vectors usefull to compute the prox of f(b)= sum(wi |bi|) mu, c, root = pb.mu, pb.c, 0.0 xs, nu, o, xbar, x = pb.init b, s = 0.0, 0.0 # just for flake8 purpose. for i in range(pb.N): nv_b = x + Q1.dot(o) - QA.dot(x) - Q2.dot(x - xbar) nv_s = (xs + nu) / 2 if i % 10 == 2 and LA.norm(b - nv_b) + LA.norm(s - nv_s) / Anorm < 2 * tol: s = s / np.sqrt(m) if regpath: return (b, (xs, nu, o, xbar, x), s) else: return (b, s) s, b = nv_s, nv_b Ab = A.dot(b) p1, p2, root = prox_phi_1(xs, 2 * Ab - o - y, np.sqrt(m) * gamma / c, root) sup1 = max(0, nu) - s sup2 = p1 - s sup3 = p2 + y - Ab sup4 = prox(2 * b - xbar, w, zerod) - b sup5 = Proj.dot(2 * b - x) - b xs = xs + mu * sup1 nu = nu + mu * sup2 o = o + mu * sup3 xbar = xbar + mu * sup4 x = x + mu * sup5 if LA.norm(b) + LA.norm(s) > 1e6: raise ValueError("The algorithm of Doulgas Rachford diverges") raise ValueError( "The algorithm of Doulgas Rachford did not converge after %i iterations " % pb.N ) """ This function compute the the solution for a given path of lam : by calling the function 'algo' for each lambda with warm start, or wuth the method ODE, by computing the whole path thanks to the ODE that rules Beta and the subgradient s, and then to evaluate it in the given finite path. """ def pathlasso_R3(pb, path, n_active=False): n, d, k = pb.dim BETA, SIGMA, tol = [], [], pb.tol if pb.type == "Path-Alg": y = pb.matrix[2] sigmax = LA.norm(y) X, LAM, R = solve_path_Conc(pb.matrix, path[-1], n_active=n_active) LAM.append(path[-1]), X.append(X[-1]), R.append(R[-1]) beta2, l2, r2, j = X[0], path[0] + 0.1, -y / LA.norm(y), 0 for lam in path: if lam == 0: lam = 1e-4 while (LA.norm(r2) < l2 / lam) and (j < len(LAM)): beta1, l1, r1, beta2, l2, r2, j = ( beta2, l2, r2, X[j], LAM[j], R[j], j + 1, ) s1, s2 = l1 / lam, l2 / lam dr, ds = r1 - r2, s1 - s2 teta = root_2( LA.norm(dr) ** 2 - ds ** 2, np.vdot(dr, r2) - s2 * ds, LA.norm(r2) ** 2 - s2 ** 2, ) SIGMA.append((s1 * teta + s2 * (1 - teta)) * sigmax) BETA.append(beta1 * teta + beta2 * (1 - teta)) return (BETA, SIGMA) save_init = pb.init pb.regpath = True pb.compute_param() if type(n_active) == int and n_active > 0: n_act = n_active else: n_act = d + 1 for lam in path: X = Classo_R3(pb, lam) BETA.append(X[0]) SIGMA.append(X[-1]) pb.init = X[1] if ( sum([(abs(X[0][i]) > 1e-5) for i in range(len(X[0]))]) >= n_act or type(X[1]) == str ): pb.init = save_init BETA.extend([BETA[-1]] * (len(path) - len(BETA))) SIGMA.extend([SIGMA[-1]] * (len(path) - len(SIGMA))) pb.regpath = False return (BETA, SIGMA) pb.init = save_init pb.regpath = False return (BETA, SIGMA) """ Class of problem : we define a type, which will contain as keys, all the parameters we need for a given problem. """ class problem_R3: def __init__(self, data, algo): self.N = 500000 (A, C, y) = data self.dim = (A.shape[0], A.shape[1], C.shape[0]) self.matrix = (A, C, y) (m, d, k) = self.dim self.weights = np.ones(d) self.tol = tol self.regpath = False self.name = algo + " Concomitant" self.type = algo # type of algorithm used self.proj_sigm = lambda x: max(x, 0) self.mu = 1.95 self.gam = 1.0 # np.sqrt(d/m) self.Aty = (A.T).dot(y) self.sigmax = LA.norm(y) / np.sqrt(m / 2) self.lambdamax = 2 * LA.norm(self.Aty, np.infty) / self.sigmax self.init = 0.0, 0.0, np.zeros(m), np.zeros(d), np.zeros(d) # Here we compute the costful matrices products and inverts in order to compute it only once, which is especially helpful for warmstarts. def compute_param(self): (A, C, y) = self.matrix m, d, k = self.dim self.Anorm = LA.norm(A, "fro") self.Anorm2 = self.Anorm ** 2 c = (d / LA.norm(A, 2)) ** 2 # parameter for Concomitant problem : the matrix is scaled as c*A^2 self.c = c self.Q1, self.Q2 = QQ(c, A) self.QA = self.Q1.dot(A) """ Functions used in the algorithms, modules needed : """ # compute the prox of the function : f(b)= sum (wi * |bi| ) def prox(b, w, zeros): return np.minimum(b + w, zeros) + np.maximum(b - w, zeros) # Compute I - C^t (C.C^t)^-1 . C : the projection on Ker(C) def proj_c(M, d): if LA.matrix_rank(M) == 0: return np.eye(d) return np.eye(d) - LA.multi_dot([M.T, np.linalg.inv(M.dot(M.T)), M]) # Compute the real positive root of a polynomial of degree 3 in the form : # X^3 + a*X - b with Newton method and a warm start (for Comcomitant problem) def calc_Newton(a, b, root): er = -b while abs(er) > 1e-6: root = root - er / (3 * root ** 2 + a) er = root ** 3 + a * root - b return root def QQ(coef, A): # compute QQ = coef A^t (2.I.+coef A A^t )^-1 , (2.I.+coef A^t A)^-1 return ( coef * (A.T).dot(LA.inv(2 * np.eye(A.shape[0]) + coef * A.dot(A.T))), LA.inv(2 * np.eye(A.shape[1]) + coef * (A.T).dot(A)), ) # Return the cost function of some Beta for a given Lasso problem : L_LS = ||y-Ab||2^2 + lambda* ||b||1 def L_LS(pb, lam, sol): return LA.norm( pb.matrix[0].dot(sol) - pb.matrix[2] ) ** 2 + lam * pb.lambdamax * LA.norm(sol, 1) # Return the prox operator for the function # phi = ||(y-Ab)||2^2 /sigma + 1/2 * sigma with the warm start on the computation of the root def prox_phi_1(sig, u, gamma, warm_start): l2u = LA.norm(u) Po0 = 4 * gamma * sig + l2u ** 2 if Po0 < 2 * gamma ** 2: return (0.0, 0.0, 0.0) else: root = calc_Newton((4 * sig / gamma + 6.0), 8 * l2u / gamma, warm_start) return ( sig + 0.5 * gamma * (0.5 * root ** 2 - 1.0), u * (1 - gamma * root / l2u), root, ) # Return the positive root in [0,1] of the polynomial aX^2 + 2bX + c if it exists, 1. if not def root_2(a, b, c): if a == 0.0: return c / (2 * b) root = (-np.sqrt(b ** 2 - a * c) - b) / a if root > 1: return 1.0 return root # The aim : # solve the equation : # |dr|^2 teta^2 + 2 (dr.r2) teta + |r2|^2 = # |ds|^2 teta^2 + 2 (ds.s2) teta + |s2|^2 # Which comes from the equation : # | teta r1 + (1-teta) r2 | = | teta s1 + (1-teta) s2 | # Which comes from the equation : # lam * | teta r1 + (1-teta) r2 | = | teta l1 + (1-teta) l2 | # lam * | y - X.( teta beta1 + (1-teta)beta2 ) | = | teta l1 + (1-teta) l2 | # in other word : $lam.|y-X.beta(gamma)| = gamma $ # so find a gamma such that sigma(gamma) * lam = gamma
[ "numpy.minimum", "numpy.maximum", "numpy.zeros", "numpy.ones", "numpy.vdot", "numpy.linalg.matrix_rank", "numpy.linalg.norm", "numpy.eye", "numpy.sqrt" ]
[((8817, 8827), 'numpy.linalg.norm', 'LA.norm', (['u'], {}), '(u)\n', (8824, 8827), True, 'import numpy.linalg as LA\n'), ((2434, 2445), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (2442, 2445), True, 'import numpy as np\n'), ((4273, 4283), 'numpy.linalg.norm', 'LA.norm', (['y'], {}), '(y)\n', (4280, 4283), True, 'import numpy.linalg as LA\n'), ((6389, 6399), 'numpy.ones', 'np.ones', (['d'], {}), '(d)\n', (6396, 6399), True, 'import numpy as np\n'), ((7128, 7145), 'numpy.linalg.norm', 'LA.norm', (['A', '"""fro"""'], {}), "(A, 'fro')\n", (7135, 7145), True, 'import numpy.linalg as LA\n'), ((7542, 7566), 'numpy.minimum', 'np.minimum', (['(b + w)', 'zeros'], {}), '(b + w, zeros)\n', (7552, 7566), True, 'import numpy as np\n'), ((7569, 7593), 'numpy.maximum', 'np.maximum', (['(b - w)', 'zeros'], {}), '(b - w, zeros)\n', (7579, 7593), True, 'import numpy as np\n'), ((7681, 7698), 'numpy.linalg.matrix_rank', 'LA.matrix_rank', (['M'], {}), '(M)\n', (7695, 7698), True, 'import numpy.linalg as LA\n'), ((7720, 7729), 'numpy.eye', 'np.eye', (['d'], {}), '(d)\n', (7726, 7729), True, 'import numpy as np\n'), ((7741, 7750), 'numpy.eye', 'np.eye', (['d'], {}), '(d)\n', (7747, 7750), True, 'import numpy as np\n'), ((948, 962), 'numpy.sqrt', 'np.sqrt', (['(m / 2)'], {}), '(m / 2)\n', (955, 962), True, 'import numpy as np\n'), ((6709, 6719), 'numpy.linalg.norm', 'LA.norm', (['y'], {}), '(y)\n', (6716, 6719), True, 'import numpy.linalg as LA\n'), ((6722, 6736), 'numpy.sqrt', 'np.sqrt', (['(m / 2)'], {}), '(m / 2)\n', (6729, 6736), True, 'import numpy as np\n'), ((6838, 6849), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (6846, 6849), True, 'import numpy as np\n'), ((6851, 6862), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (6859, 6862), True, 'import numpy as np\n'), ((6864, 6875), 'numpy.zeros', 'np.zeros', (['d'], {}), '(d)\n', (6872, 6875), True, 'import numpy as np\n'), ((8608, 8623), 'numpy.linalg.norm', 'LA.norm', (['sol', '(1)'], {}), '(sol, 1)\n', (8615, 8623), True, 'import numpy.linalg as LA\n'), ((1679, 1694), 'numpy.vdot', 'np.vdot', (['dr', 'r2'], {}), '(dr, r2)\n', (1686, 1694), True, 'import numpy as np\n'), ((2073, 2083), 'numpy.linalg.norm', 'LA.norm', (['y'], {}), '(y)\n', (2080, 2083), True, 'import numpy.linalg as LA\n'), ((4476, 4486), 'numpy.linalg.norm', 'LA.norm', (['y'], {}), '(y)\n', (4483, 4486), True, 'import numpy.linalg as LA\n'), ((6766, 6793), 'numpy.linalg.norm', 'LA.norm', (['self.Aty', 'np.infty'], {}), '(self.Aty, np.infty)\n', (6773, 6793), True, 'import numpy.linalg as LA\n'), ((7201, 7214), 'numpy.linalg.norm', 'LA.norm', (['A', '(2)'], {}), '(A, 2)\n', (7208, 7214), True, 'import numpy.linalg as LA\n'), ((9334, 9357), 'numpy.sqrt', 'np.sqrt', (['(b ** 2 - a * c)'], {}), '(b ** 2 - a * c)\n', (9341, 9357), True, 'import numpy as np\n'), ((1639, 1650), 'numpy.linalg.norm', 'LA.norm', (['dr'], {}), '(dr)\n', (1646, 1650), True, 'import numpy.linalg as LA\n'), ((1718, 1729), 'numpy.linalg.norm', 'LA.norm', (['r2'], {}), '(r2)\n', (1725, 1729), True, 'import numpy.linalg as LA\n'), ((2886, 2896), 'numpy.sqrt', 'np.sqrt', (['m'], {}), '(m)\n', (2893, 2896), True, 'import numpy as np\n'), ((3545, 3555), 'numpy.linalg.norm', 'LA.norm', (['b'], {}), '(b)\n', (3552, 3555), True, 'import numpy.linalg as LA\n'), ((3558, 3568), 'numpy.linalg.norm', 'LA.norm', (['s'], {}), '(s)\n', (3565, 3568), True, 'import numpy.linalg as LA\n'), ((4586, 4597), 'numpy.linalg.norm', 'LA.norm', (['r2'], {}), '(r2)\n', (4593, 4597), True, 'import numpy.linalg as LA\n'), ((5047, 5062), 'numpy.vdot', 'np.vdot', (['dr', 'r2'], {}), '(dr, r2)\n', (5054, 5062), True, 'import numpy as np\n'), ((8329, 8347), 'numpy.eye', 'np.eye', (['A.shape[1]'], {}), '(A.shape[1])\n', (8335, 8347), True, 'import numpy as np\n'), ((2805, 2822), 'numpy.linalg.norm', 'LA.norm', (['(b - nv_b)'], {}), '(b - nv_b)\n', (2812, 2822), True, 'import numpy.linalg as LA\n'), ((3152, 3162), 'numpy.sqrt', 'np.sqrt', (['m'], {}), '(m)\n', (3159, 3162), True, 'import numpy as np\n'), ((5003, 5014), 'numpy.linalg.norm', 'LA.norm', (['dr'], {}), '(dr)\n', (5010, 5014), True, 'import numpy.linalg as LA\n'), ((5090, 5101), 'numpy.linalg.norm', 'LA.norm', (['r2'], {}), '(r2)\n', (5097, 5101), True, 'import numpy.linalg as LA\n'), ((2825, 2842), 'numpy.linalg.norm', 'LA.norm', (['(s - nv_s)'], {}), '(s - nv_s)\n', (2832, 2842), True, 'import numpy.linalg as LA\n'), ((8268, 8286), 'numpy.eye', 'np.eye', (['A.shape[0]'], {}), '(A.shape[0])\n', (8274, 8286), True, 'import numpy as np\n')]
"""Text and number formatting operations""" from copy import deepcopy import json import numpy as np def round_all_numbers_in_dict(d, rounding_digits=2, outplace=True): """ Return a new version of dict d with all floats rounded to N digits.""" if outplace: d = deepcopy(d) for k, v in d.items(): if isinstance(v, float): d[k] = np.round(v, rounding_digits) if isinstance(v, dict): round_all_numbers_in_dict(v, rounding_digits, outplace=False) return d def dict_to_pretty_string(d, rounding_digits=2, indent=2): """Return a nicely JSON-like formatted string to print a dict.""" d = round_all_numbers_in_dict(d, rounding_digits) formatted_text = json.dumps(d, indent=indent) for char in '{}",': formatted_text = formatted_text.replace(char, "") return formatted_text def score_to_formatted_string(score, characters=9): """Transform a number (score) into a best-format string. The format will be either int (2234), float (10.234) or engineering (1.20E5), whichever is shorter. The score is then padded with left whitespaces to obtained the desired number of ``characters``.""" raw = str(int(score) if (int(score) == score) else score) as_float = "%.02f" % score as_eng = "%.02E." % score return min([raw, as_float, as_eng], key=len).rjust(characters)
[ "copy.deepcopy", "numpy.round", "json.dumps" ]
[((725, 753), 'json.dumps', 'json.dumps', (['d'], {'indent': 'indent'}), '(d, indent=indent)\n', (735, 753), False, 'import json\n'), ((280, 291), 'copy.deepcopy', 'deepcopy', (['d'], {}), '(d)\n', (288, 291), False, 'from copy import deepcopy\n'), ((371, 399), 'numpy.round', 'np.round', (['v', 'rounding_digits'], {}), '(v, rounding_digits)\n', (379, 399), True, 'import numpy as np\n')]
from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import sys,math,cv2 import os import argparse import tensorflow as tf import numpy as np import random import align.detect_face from time import sleep def get_lot(Line): Dir = Line.split(' ')[0] file = Dir.split('/')[-2] pic_name = Dir.split('/')[-1] return file,pic_name def rote_image(image,angle): height, width = image.shape[:2] image_center = (width/2, height/2) rotation_matrix = cv2.getRotationMatrix2D(image_center, angle, 1.) abs_cos = abs(rotation_matrix[0, 0]) abs_sin = abs(rotation_matrix[0, 1]) rotated_width = int(height*abs_sin + width*abs_cos)+35 rotated_height = int(height*abs_cos + width*abs_sin)+35 rotation_matrix[0, 2] += rotated_width/2 - image_center[0] rotation_matrix[1, 2] += rotated_height/2 - image_center[1] return cv2.warpAffine(image,rotation_matrix,(rotated_width, rotated_height)) def main(args): with tf.Graph().as_default(): sess = tf.Session() with sess.as_default(): pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None) minsize = 20 threshold = [ 0.6, 0.7, 0.7 ] factor = 0.709 random_key = np.random.randint(0, high=99999) bounding_boxes_filename = args.output_dir+'/'+'new_boxes.txt' with open(bounding_boxes_filename, "w") as text_file: for line in open(args.txt_dir): Dir,Angle = line.split(' ') angle = float(Angle.split('/')[0]) img = misc.imread(Dir) im_rote = rote_image(img,angle) bounding_boxes, _ = align.detect_face.detect_face(im_rote, minsize, pnet, rnet, onet, threshold, factor) nrof_faces = bounding_boxes.shape[0] if nrof_faces>0: det = bounding_boxes[:,0:4] det_arr = [] img_size = np.asarray(im_rote.shape)[0:2] if nrof_faces>1: bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1]) img_center = img_size / 2 offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ]) offset_dist_squared = np.sum(np.power(offsets,2.0),0) index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering det_arr.append(det[index,:]) else: det_arr.append(np.squeeze(det)) for i, det in enumerate(det_arr): det = np.squeeze(det) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0]-args.margin/2, 0) bb[1] = np.maximum(det[1]-args.margin/2, 0) bb[2] = np.minimum(det[2]+args.margin/2, img_size[1]) bb[3] = np.minimum(det[3]+args.margin/2, img_size[0]) cropped = im_rote[bb[1]:bb[3],bb[0]:bb[2],:] scaled = cropped f_name,Im_name = get_lot(line) if not os.path.exists(args.output_dir+'/'+f_name): os.makedirs(args.output_dir+'/'+f_name) misc.imsave(args.output_dir+'/'+f_name+'/'+Im_name,scaled) text_file.write('%s %f %d %d %d %d\n' % (Dir,angle,bb[0],bb[1],bb[2],bb[3])) print('Number of successfully aligned images: %d' % success_aligned) def parse_arguments(argv): parser = argparse.ArgumentParser() parser.add_argument('--input_dir', type=str, help='Directory with unaligned images.', default="./data/facenet/src/faceims") parser.add_argument('--txt_dir', type=str, help='Directory with unaligned images.', default="./data/facenet/src/facesalign/bounding_boxes.txt") parser.add_argument('--output_dir', type=str, help='Directory with aligned face thumbnails.', default="./data/facenet/src/facesalign") parser.add_argument('--image_size', type=int, help='Image size (height, width) in pixels.', default=100) parser.add_argument('--margin', type=int, help='Margin for the crop around the bounding box (height, width) in pixels.', default=30) parser.add_argument('--random_order', help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true') parser.add_argument('--gpu_memory_fraction', type=float, help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0) parser.add_argument('--detect_multiple_faces', type=bool, help='Detect and align multiple faces per image.', default=True) return parser.parse_args(argv) if __name__ == '__main__': main(parse_arguments(sys.argv[1:]))
[ "numpy.minimum", "numpy.maximum", "argparse.ArgumentParser", "os.makedirs", "numpy.argmax", "numpy.power", "numpy.asarray", "tensorflow.Session", "numpy.zeros", "os.path.exists", "cv2.warpAffine", "numpy.random.randint", "tensorflow.Graph", "scipy.misc.imsave", "numpy.squeeze", "numpy....
[((549, 598), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['image_center', 'angle', '(1.0)'], {}), '(image_center, angle, 1.0)\n', (572, 598), False, 'import sys, math, cv2\n'), ((937, 1008), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'rotation_matrix', '(rotated_width, rotated_height)'], {}), '(image, rotation_matrix, (rotated_width, rotated_height))\n', (951, 1008), False, 'import sys, math, cv2\n'), ((1297, 1329), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': '(99999)'}), '(0, high=99999)\n', (1314, 1329), True, 'import numpy as np\n'), ((3620, 3645), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3643, 3645), False, 'import argparse\n'), ((1078, 1090), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1088, 1090), True, 'import tensorflow as tf\n'), ((1605, 1621), 'scipy.misc.imread', 'misc.imread', (['Dir'], {}), '(Dir)\n', (1616, 1621), False, 'from scipy import misc\n'), ((1037, 1047), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1045, 1047), True, 'import tensorflow as tf\n'), ((1962, 1987), 'numpy.asarray', 'np.asarray', (['im_rote.shape'], {}), '(im_rote.shape)\n', (1972, 1987), True, 'import numpy as np\n'), ((2182, 2287), 'numpy.vstack', 'np.vstack', (['[(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:, 3]) / 2 -\n img_center[0]]'], {}), '([(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:,\n 3]) / 2 - img_center[0]])\n', (2191, 2287), True, 'import numpy as np\n'), ((2372, 2428), 'numpy.argmax', 'np.argmax', (['(bounding_box_size - offset_dist_squared * 2.0)'], {}), '(bounding_box_size - offset_dist_squared * 2.0)\n', (2381, 2428), True, 'import numpy as np\n'), ((2661, 2676), 'numpy.squeeze', 'np.squeeze', (['det'], {}), '(det)\n', (2671, 2676), True, 'import numpy as np\n'), ((2702, 2729), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (2710, 2729), True, 'import numpy as np\n'), ((2758, 2797), 'numpy.maximum', 'np.maximum', (['(det[0] - args.margin / 2)', '(0)'], {}), '(det[0] - args.margin / 2, 0)\n', (2768, 2797), True, 'import numpy as np\n'), ((2822, 2861), 'numpy.maximum', 'np.maximum', (['(det[1] - args.margin / 2)', '(0)'], {}), '(det[1] - args.margin / 2, 0)\n', (2832, 2861), True, 'import numpy as np\n'), ((2886, 2935), 'numpy.minimum', 'np.minimum', (['(det[2] + args.margin / 2)', 'img_size[1]'], {}), '(det[2] + args.margin / 2, img_size[1])\n', (2896, 2935), True, 'import numpy as np\n'), ((2960, 3009), 'numpy.minimum', 'np.minimum', (['(det[3] + args.margin / 2)', 'img_size[0]'], {}), '(det[3] + args.margin / 2, img_size[0])\n', (2970, 3009), True, 'import numpy as np\n'), ((3335, 3402), 'scipy.misc.imsave', 'misc.imsave', (["(args.output_dir + '/' + f_name + '/' + Im_name)", 'scaled'], {}), "(args.output_dir + '/' + f_name + '/' + Im_name, scaled)\n", (3346, 3402), False, 'from scipy import misc\n'), ((2319, 2341), 'numpy.power', 'np.power', (['offsets', '(2.0)'], {}), '(offsets, 2.0)\n', (2327, 2341), True, 'import numpy as np\n'), ((2568, 2583), 'numpy.squeeze', 'np.squeeze', (['det'], {}), '(det)\n', (2578, 2583), True, 'import numpy as np\n'), ((3207, 3253), 'os.path.exists', 'os.path.exists', (["(args.output_dir + '/' + f_name)"], {}), "(args.output_dir + '/' + f_name)\n", (3221, 3253), False, 'import os\n'), ((3275, 3318), 'os.makedirs', 'os.makedirs', (["(args.output_dir + '/' + f_name)"], {}), "(args.output_dir + '/' + f_name)\n", (3286, 3318), False, 'import os\n')]
"""Utility functions for converting relative and specific humidity. CAUTION: after the refactoring these have not been tested. """ import numpy as np EPSILON = 0.62198 # ratio of water vapour to dry air molecular weights def calc_saturation_vapour_pressure(air_temperature): """Convert air temperature to saturation vapour pressure. This uses the simple Magnus formula of Alduchov and Eskridge _[1]. Parameters ---------- air_temperature : array_like air temperature, K Returns ------- es : array_like saturation vapour pressure, Pa References ---------- .. [1] <NAME>. & <NAME>. (1996). Improved Magnus Form Approximation of Saturation Vapor Pressure, Journal of Applied Meteorology and Climatology, 35 (4), 601-609, doi.org/10.1175/1520-0450(1996)035<0601:IMFAOS>2.0.CO;2 """ # allow list input: convert to array # integers to negative powers not allowed, ensure float air_temperature = np.asarray(air_temperature).astype(float) return 610.94 * np.exp( 17.625 * (air_temperature - 273.15) / (air_temperature - 30.11) ) def calc_saturation_mixing_ratio(air_temperature, pressure): """Calculate saturation mixing ratio. Parameters ---------- air_temperature : array_like Air temperature (K) pressure : array_like Air pressure (Pa) Returns ------- saturation_mixing_ratio : array_like Saturation mixing ratio, dimensionless """ saturation_vapour_pressure = calc_saturation_vapour_pressure(air_temperature) saturation_mixing_ratio = ( EPSILON * saturation_vapour_pressure / ( np.maximum(pressure, saturation_vapour_pressure) - (1 - EPSILON) * saturation_vapour_pressure ) ) return saturation_mixing_ratio def specific_to_relative( specific_humidity, pressure=101325, air_temperature=288.15, rh_percent=False, ): """Convert specific humidity to relative humidity. Parameters ---------- specific_humidity : array_like Specific humidity (kg/kg) pressure : array_like Air pressure (Pa) air_temperature : array_like Air temperature (K) rh_percent : bool, default=False True to return relative humidity in %, False if 0-1 scale Returns ------- relative_humidity : array_like relative humidity """ saturation_mixing_ratio = calc_saturation_mixing_ratio(air_temperature, pressure) relative_humidity = specific_humidity / saturation_mixing_ratio if rh_percent: relative_humidity = relative_humidity * 100 return relative_humidity def relative_to_specific( relative_humidity, pressure=101325, air_temperature=288.15, rh_percent=False, ): """Convert relative humidity to specific humidity. Parameters ---------- relative_humidity : array_like Relative humidity, in either percent or 0-1 scale (see `rh_percent`) pressure : array_like Air pressure (Pa) air_temperature : array_like Air temperature (K) rh_percent : bool, default=False True if relative humidity is given in percent, False if 0-1 scale Returns ------- specific_humidity: array_like specific humidity (kg/kg) """ if rh_percent: relative_humidity = relative_humidity / 100 saturation_mixing_ratio = calc_saturation_mixing_ratio(air_temperature, pressure) specific_humidity = relative_humidity * saturation_mixing_ratio return specific_humidity
[ "numpy.asarray", "numpy.maximum", "numpy.exp" ]
[((1070, 1141), 'numpy.exp', 'np.exp', (['(17.625 * (air_temperature - 273.15) / (air_temperature - 30.11))'], {}), '(17.625 * (air_temperature - 273.15) / (air_temperature - 30.11))\n', (1076, 1141), True, 'import numpy as np\n'), ((1007, 1034), 'numpy.asarray', 'np.asarray', (['air_temperature'], {}), '(air_temperature)\n', (1017, 1034), True, 'import numpy as np\n'), ((1741, 1789), 'numpy.maximum', 'np.maximum', (['pressure', 'saturation_vapour_pressure'], {}), '(pressure, saturation_vapour_pressure)\n', (1751, 1789), True, 'import numpy as np\n')]
import os import numpy as np from typing import TextIO, Tuple, Mapping, Dict, List, Sequence import chardet from . import ri, trains, agf, PROPERTIES_DIR # Folder containing supplied (public domain) AGF files. SUPPLIED_AGFS_DIR = os.path.join(PROPERTIES_DIR, 'agfs') # Translate from Zemax glass database to ri module. #glasses = {'PMMA':ri.PMMA_Zemax, 'F_SILICA':ri.fused_silica, 'BK7':ri.N_BK7, 'K-VC89':ri.KVC89} SUPPLIED_GLASS_CATALOG_PATHS = { 'HOYA': os.path.join(SUPPLIED_AGFS_DIR, 'HOYA20200314_include_obsolete.agf'), 'SCHOTT': os.path.join(SUPPLIED_AGFS_DIR, 'schottzemax-20180601.agf'), 'OHARA': os.path.join(SUPPLIED_AGFS_DIR, 'OHARA_200306_CATALOG.agf'), 'SUMITA': os.path.join(SUPPLIED_AGFS_DIR, 'sumita-opt-dl-data-20200511235805.agf'), 'NIKON': os.path.join(SUPPLIED_AGFS_DIR, 'NIKON-HIKARI_201911.agf'), 'HIKARI': os.path.join(SUPPLIED_AGFS_DIR, 'NIKON-HIKARI_201911.agf') } default_glass_catalog_paths = SUPPLIED_GLASS_CATALOG_PATHS.copy() def read_glass_catalog_dir(dir: str) -> Dict[str, str]: paths = {} dir = os.path.expanduser(dir) for name in os.listdir(dir): path = os.path.join(dir, name) if not os.path.isfile(path): continue root, ext = os.path.splitext(name) if ext.lower() != '.agf': continue paths[root.upper()] = path return paths class GlassNotInCatalogError(Exception): def __init__(self, glasses: Sequence[str]): Exception.__init__(self, f"Glass {glasses} not in catalog.") self.glasses = glasses def read_interface(file:TextIO, n1, catalog: Dict[str, agf.Record], temperature: float, try_n_prefix: bool = False) -> Tuple[trains.Interface, float, float]: commands = {} parms = {} while True: pos = file.tell() line = file.readline() words = line.split() if len(words) > 0: if line[:2] != ' ': file.seek(pos) break if words[0] == 'PARM': parm_index = int(words[1]) parm_value = float(words[2]) assert len(words) == 3 parms[parm_index] = parm_value else: commands[words[0]]=words[1:] if 'GLAS' in commands: glass = commands['GLAS'][0] try: record = catalog[glass] except KeyError as ex: if try_n_prefix: nglass = 'N-' + glass try: record = catalog[nglass] except KeyError: raise GlassNotInCatalogError((glass, nglass)) else: raise GlassNotInCatalogError([glass]) from ex n2 = record.fix_temperature(temperature) else: n2 = ri.air thickness = float(commands['DISZ'][0])*1e-3 clear_semi_dia = float(commands['DIAM'][0])*1e-3 chip_zone = float(commands.get('OEMA', ['0'])[0])*1e-3 clear_radius = clear_semi_dia + chip_zone with np.errstate(divide='ignore'): roc = np.divide(1e-3,float(commands['CURV'][0])) kappa = float(commands.get('CONI', [0])[0]) + 1 surface_type = commands['TYPE'][0] if surface_type == 'STANDARD' and np.isclose(kappa,1): inner_surface = trains.SphericalSurface(roc, clear_radius) elif surface_type in ('STANDARD','EVENASPH'): alphas = [] for parm_index, parm_value in parms.items(): # Term is (2*parm_index)th-order coefficient, so the (2*parm_index-2)th element of alphas. order = 2*parm_index index = order-2 if parm_value != 0: assert index >= 0 alphas += [0]*(index - len(alphas) + 1) alphas[index] = parm_value*(1e3)**(order - 1) inner_surface = trains.ConicSurface(roc, clear_radius, kappa, alphas) else: raise ValueError('Unknown surface type %s.'%surface_type) if 'MEMA' in commands: mech_semi_dia = float(commands['MEMA'][0])*1e-3 else: mech_semi_dia = clear_radius if mech_semi_dia - clear_radius > 1e-6: # TODO tidy this up - get rid of rt first? # Somehow need to offset this surface (in z). No way of describing this at present. Could add an offset # attribute to Surface. Then would need an offset in Profile. outer_surface = trains.SphericalSurface(np.inf, mech_semi_dia - clear_radius) outer_sag = inner_surface.calc_sag(clear_radius) surface = trains.SegmentedSurface((inner_surface, outer_surface), (0, outer_sag)) else: surface = inner_surface interface = surface.to_interface(n1, n2) return interface, n2, thickness class GlassNotFoundError(Exception): def __init__(self, glasses: Sequence[str], sources: List[Tuple[str, str]], surface_num: int): Exception.__init__(self, f"Glass {glasses} of surface {surface_num} not found in the following catalogs: {sources}.") class NoCatalogError(Exception): def __init__(self, name: str): Exception.__init__(self, f'Catalog {name} not known.') self.name = name def read_train(filename:str, n: ri.Index = ri.air, encoding: str = None, temperature: float = None, glass_catalog_paths: Dict[str, str] = None, try_n_prefix: bool = False) -> trains.Train: """Read optical train from Zemax file. The given refractive index defines the surrounding medium. If encoding is not given it is detected automatically.""" if encoding is None: with open(filename, 'rb') as file: raw = file.read() encoding = chardet.detect(raw)['encoding'] if glass_catalog_paths is None: glass_catalog_paths = default_glass_catalog_paths surface_num = 0 spaces = [0] interfaces = [] full_catalog = {} full_catalog_sources = [] with open(filename, 'rt', encoding=encoding) as file: while True: line = file.readline() if not line: break words = line.split() if words[0] == 'SURF': assert int(words[1]) == surface_num try: interface, n, space = read_interface(file, n, full_catalog, temperature, try_n_prefix) except GlassNotInCatalogError as ex: raise GlassNotFoundError(ex.glasses, full_catalog_sources, surface_num) from ex except Exception as e: raise ValueError(f'Exception reading SURF {surface_num}.') from e interfaces.append(interface) spaces.append(space) surface_num += 1 elif words[0] == 'GCAT': for name in line.split()[1:]: try: catalog_path = glass_catalog_paths[name] except KeyError as e: raise NoCatalogError(name) from e full_catalog_sources.append((name, catalog_path)) catalog = agf.load_catalog(catalog_path) full_catalog.update(catalog) return trains.Train(interfaces, spaces)
[ "os.path.join", "numpy.errstate", "numpy.isclose", "os.path.isfile", "chardet.detect", "os.path.splitext", "os.path.expanduser", "os.listdir" ]
[((232, 268), 'os.path.join', 'os.path.join', (['PROPERTIES_DIR', '"""agfs"""'], {}), "(PROPERTIES_DIR, 'agfs')\n", (244, 268), False, 'import os\n'), ((465, 533), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""HOYA20200314_include_obsolete.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'HOYA20200314_include_obsolete.agf')\n", (477, 533), False, 'import os\n'), ((549, 608), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""schottzemax-20180601.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'schottzemax-20180601.agf')\n", (561, 608), False, 'import os\n'), ((623, 682), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""OHARA_200306_CATALOG.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'OHARA_200306_CATALOG.agf')\n", (635, 682), False, 'import os\n'), ((698, 770), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""sumita-opt-dl-data-20200511235805.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'sumita-opt-dl-data-20200511235805.agf')\n", (710, 770), False, 'import os\n'), ((785, 843), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""NIKON-HIKARI_201911.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'NIKON-HIKARI_201911.agf')\n", (797, 843), False, 'import os\n'), ((859, 917), 'os.path.join', 'os.path.join', (['SUPPLIED_AGFS_DIR', '"""NIKON-HIKARI_201911.agf"""'], {}), "(SUPPLIED_AGFS_DIR, 'NIKON-HIKARI_201911.agf')\n", (871, 917), False, 'import os\n'), ((1074, 1097), 'os.path.expanduser', 'os.path.expanduser', (['dir'], {}), '(dir)\n', (1092, 1097), False, 'import os\n'), ((1114, 1129), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (1124, 1129), False, 'import os\n'), ((1146, 1169), 'os.path.join', 'os.path.join', (['dir', 'name'], {}), '(dir, name)\n', (1158, 1169), False, 'import os\n'), ((1236, 1258), 'os.path.splitext', 'os.path.splitext', (['name'], {}), '(name)\n', (1252, 1258), False, 'import os\n'), ((2975, 3003), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (2986, 3003), True, 'import numpy as np\n'), ((3191, 3211), 'numpy.isclose', 'np.isclose', (['kappa', '(1)'], {}), '(kappa, 1)\n', (3201, 3211), True, 'import numpy as np\n'), ((1185, 1205), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (1199, 1205), False, 'import os\n'), ((5582, 5601), 'chardet.detect', 'chardet.detect', (['raw'], {}), '(raw)\n', (5596, 5601), False, 'import chardet\n')]
import axelrod as axl import numpy as np import csv download_dir = "axelrod-tournament.csv" #where file will go csv = open(download_dir, "w") #allow writing to file columnTitleRow= 'Strategy Name, Average Pay-off\n' csv.write(columnTitleRow) # players = [s() for s in axl.basic_strategies] players = [s() for s in axl.strategies] # players = [axl.Cooperator(),axl.Alternator(),axl.TitForTat(), axl.Random(), axl.Defector()] tournament = axl.Tournament(players,repetitions=1,turns=1) results=tournament.play() for i in range(len(players)): player_name = players[i].name player_score = np.mean(results.normalised_scores[i]) print(player_name + ' ' + str(player_score)) csv.write(player_name + ',' + str(player_score) + '\n')
[ "csv.write", "numpy.mean", "axelrod.Tournament" ]
[((219, 244), 'csv.write', 'csv.write', (['columnTitleRow'], {}), '(columnTitleRow)\n', (228, 244), False, 'import csv\n'), ((441, 488), 'axelrod.Tournament', 'axl.Tournament', (['players'], {'repetitions': '(1)', 'turns': '(1)'}), '(players, repetitions=1, turns=1)\n', (455, 488), True, 'import axelrod as axl\n'), ((596, 633), 'numpy.mean', 'np.mean', (['results.normalised_scores[i]'], {}), '(results.normalised_scores[i])\n', (603, 633), True, 'import numpy as np\n')]
import os import os.path as osp import numpy as np import pickle from PIL import Image from tqdm import tqdm import glob import yaml import torch import open3d as o3d from xmuda.data.semantic_kitti import splits from xmuda.data.semantic_kitti.preprocess import DummyDataset from xmuda.data.utils.preprocess import create_img_grid, create_voxel_grid def depth_to_3d_indices(img_grid, depth, T_inv, K_inv, scene_lower_bound, output_voxel_size, downsample): w, h = img_grid img_grid = (w // downsample, h // downsample) img_grid_homo = np.hstack( [img_grid, np.ones((img_grid.shape[0], 1))]) points_3d_cam = K_inv @ (img_grid_homo * depth).T points_3d_cam = points_3d_cam.T # (N, 3) points_3d_cam_homo = np.hstack( [points_3d_cam, np.ones((points_3d_cam.shape[0], 1))]) # (N, 4) points_3d_lidar_homo = T_inv @ points_3d_cam_homo.T points_3d_lidar_homo = points_3d_lidar_homo.T # (N, 4) points_3d_lidar = points_3d_lidar_homo[:, :3] # only keep points inside the interested area keep_idx = (points_3d_lidar[:, 0] > 0) & \ (points_3d_lidar[:, 1] > -25.6) & \ (points_3d_lidar[:, 2] > -2) & \ (points_3d_lidar[:, 0] < 51.2) & \ (points_3d_lidar[:, 1] < 25.6) & \ (points_3d_lidar[:, 2] < 4.4) points_3d_lidar = points_3d_lidar[keep_idx] voxel_indices = (points_3d_lidar - scene_lower_bound) / output_voxel_size voxel_indices = voxel_indices.astype(np.int32) # the the resolution of the image is halved when feed to the network img_indices = (img_grid_homo[keep_idx, :2] / downsample).astype(np.int32) # # Enforce each voxel is passed by only 1 ray # values, indices, counts = np.unique( # voxel_indices, # return_index=True, # return_counts=True, # axis=0) # # print(voxel_indices.shape, img_indices.shape) # voxel_indices = voxel_indices[indices] # img_indices = img_indices[indices] # print(voxel_indices.shape, img_indices.shape) return { "voxel_indices": voxel_indices, "img_indices": img_indices } def compute_2d_depths_to_3d_voxel_indices(root_dir, out_dir, img_size=(1220, 370), output_voxel_size=0.8, downsample=8, max_pixels_per_voxel=64, num_voxelized_depth_classes=64): depth_voxel_size = 51.2 / num_voxelized_depth_classes scene_lower_bound = np.array([0, -25.6, -2]).reshape(1, -1) split_train = getattr(splits, "train") split_test = getattr(splits, "test") split_val = getattr(splits, "val") split_hidden_test = getattr(splits, "hidden_test") scenes = split_train + split_test + split_val + split_hidden_test img_grid = create_img_grid(img_size, downsample=downsample) data_dict = {} for scene in scenes: calib = DummyDataset.read_calib( osp.join(root_dir, 'dataset', 'sequences', scene, 'calib.txt')) P = calib['P2'] T_velo_2_cam = calib['Tr'] K_intrinsic = P[0:3, 0:3] K_inv = np.linalg.inv(K_intrinsic) T_inv = np.linalg.inv(T_velo_2_cam) voxel_indices_all = [] img_indices_all = [] for depth_class in range(num_voxelized_depth_classes): depth = depth_voxel_size / 2.0 + depth_voxel_size * depth_class res = depth_to_3d_indices(img_grid, depth, T_inv, K_inv, scene_lower_bound, output_voxel_size, downsample) voxel_indices = res["voxel_indices"] img_indices = res["img_indices"] depth_idx = np.ones((voxel_indices.shape[0], 1)) * depth_class voxel_indices = np.hstack([voxel_indices, depth_idx]) img_indices = np.hstack([img_indices, depth_idx]) voxel_indices_all.append(voxel_indices) img_indices_all.append(img_indices) voxel_indices = np.vstack(voxel_indices_all) img_indices = np.vstack(img_indices_all) # Enforce each voxel is passed by only 1 ray voxel_indices, indices, inverse = np.unique( voxel_indices, return_index=True, return_inverse=True, axis=0) voxel_to_pixel_indices_mapping = [] for i, index in tqdm(enumerate(indices)): pixel_indices = np.where(inverse == i)[0] if len(pixel_indices) > max_pixels_per_voxel: pixel_indices = pixel_indices[:max_pixels_per_voxel] else: pad_widths = (0, int(max_pixels_per_voxel - len(pixel_indices))) pixel_indices = np.pad(pixel_indices, pad_widths , 'edge') # print(len(pixel_indices)) voxel_to_pixel_indices_mapping.append(pixel_indices) voxel_to_pixel_indices_mapping = np.array(voxel_to_pixel_indices_mapping) print(voxel_indices.shape, img_indices.shape, voxel_to_pixel_indices_mapping.shape) data_dict[scene] = { "voxel_indices": voxel_indices, "img_indices": img_indices, "voxel_to_pixel_indices": voxel_to_pixel_indices_mapping } # data_dict[scene] = { # "voxel_indices": voxel_indices, # "img_indices": img_indices # } # print(data_dict['01']['voxel_incdices'][0].shape, data_dict['01']['img_indices'][0].shape) save_dir = osp.join(out_dir, 'preprocess') os.makedirs(save_dir, exist_ok=True) save_path = osp.join(save_dir, 'unproject_{}_{}.pkl'.format( num_voxelized_depth_classes, max_pixels_per_voxel)) with open(save_path, 'wb') as f: pickle.dump(data_dict, f, pickle.HIGHEST_PROTOCOL) print('Wrote unprojected data to ' + save_path) if __name__ == '__main__': # root_dir = '/datasets_master/semantic_kitti' # out_dir = '/datasets_local/datasets_acao/semantic_kitti_preprocess' root_dir = '/gpfswork/rech/xqt/uyl37fq/data/semantic_kitti' out_dir = root_dir + '/preprocess' scenes = getattr(splits, "train") scenes += getattr(splits, "val") scenes += getattr(splits, "test") for num_voxelized_depth_classes in [16, 32]: compute_2d_depths_to_3d_voxel_indices( root_dir, out_dir, num_voxelized_depth_classes=num_voxelized_depth_classes)
[ "numpy.pad", "pickle.dump", "os.makedirs", "numpy.unique", "numpy.ones", "xmuda.data.utils.preprocess.create_img_grid", "numpy.hstack", "numpy.where", "numpy.linalg.inv", "numpy.array", "os.path.join", "numpy.vstack" ]
[((3010, 3058), 'xmuda.data.utils.preprocess.create_img_grid', 'create_img_grid', (['img_size'], {'downsample': 'downsample'}), '(img_size, downsample=downsample)\n', (3025, 3058), False, 'from xmuda.data.utils.preprocess import create_img_grid, create_voxel_grid\n'), ((5736, 5767), 'os.path.join', 'osp.join', (['out_dir', '"""preprocess"""'], {}), "(out_dir, 'preprocess')\n", (5744, 5767), True, 'import os.path as osp\n'), ((5772, 5808), 'os.makedirs', 'os.makedirs', (['save_dir'], {'exist_ok': '(True)'}), '(save_dir, exist_ok=True)\n', (5783, 5808), False, 'import os\n'), ((3329, 3355), 'numpy.linalg.inv', 'np.linalg.inv', (['K_intrinsic'], {}), '(K_intrinsic)\n', (3342, 3355), True, 'import numpy as np\n'), ((3372, 3399), 'numpy.linalg.inv', 'np.linalg.inv', (['T_velo_2_cam'], {}), '(T_velo_2_cam)\n', (3385, 3399), True, 'import numpy as np\n'), ((4259, 4287), 'numpy.vstack', 'np.vstack', (['voxel_indices_all'], {}), '(voxel_indices_all)\n', (4268, 4287), True, 'import numpy as np\n'), ((4310, 4336), 'numpy.vstack', 'np.vstack', (['img_indices_all'], {}), '(img_indices_all)\n', (4319, 4336), True, 'import numpy as np\n'), ((4433, 4505), 'numpy.unique', 'np.unique', (['voxel_indices'], {'return_index': '(True)', 'return_inverse': '(True)', 'axis': '(0)'}), '(voxel_indices, return_index=True, return_inverse=True, axis=0)\n', (4442, 4505), True, 'import numpy as np\n'), ((5168, 5208), 'numpy.array', 'np.array', (['voxel_to_pixel_indices_mapping'], {}), '(voxel_to_pixel_indices_mapping)\n', (5176, 5208), True, 'import numpy as np\n'), ((5979, 6029), 'pickle.dump', 'pickle.dump', (['data_dict', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(data_dict, f, pickle.HIGHEST_PROTOCOL)\n', (5990, 6029), False, 'import pickle\n'), ((649, 680), 'numpy.ones', 'np.ones', (['(img_grid.shape[0], 1)'], {}), '((img_grid.shape[0], 1))\n', (656, 680), True, 'import numpy as np\n'), ((844, 880), 'numpy.ones', 'np.ones', (['(points_3d_cam.shape[0], 1)'], {}), '((points_3d_cam.shape[0], 1))\n', (851, 880), True, 'import numpy as np\n'), ((2706, 2730), 'numpy.array', 'np.array', (['[0, -25.6, -2]'], {}), '([0, -25.6, -2])\n', (2714, 2730), True, 'import numpy as np\n'), ((3156, 3218), 'os.path.join', 'osp.join', (['root_dir', '"""dataset"""', '"""sequences"""', 'scene', '"""calib.txt"""'], {}), "(root_dir, 'dataset', 'sequences', scene, 'calib.txt')\n", (3164, 3218), True, 'import os.path as osp\n'), ((4033, 4070), 'numpy.hstack', 'np.hstack', (['[voxel_indices, depth_idx]'], {}), '([voxel_indices, depth_idx])\n', (4042, 4070), True, 'import numpy as np\n'), ((4097, 4132), 'numpy.hstack', 'np.hstack', (['[img_indices, depth_idx]'], {}), '([img_indices, depth_idx])\n', (4106, 4132), True, 'import numpy as np\n'), ((3954, 3990), 'numpy.ones', 'np.ones', (['(voxel_indices.shape[0], 1)'], {}), '((voxel_indices.shape[0], 1))\n', (3961, 3990), True, 'import numpy as np\n'), ((4678, 4700), 'numpy.where', 'np.where', (['(inverse == i)'], {}), '(inverse == i)\n', (4686, 4700), True, 'import numpy as np\n'), ((4962, 5003), 'numpy.pad', 'np.pad', (['pixel_indices', 'pad_widths', '"""edge"""'], {}), "(pixel_indices, pad_widths, 'edge')\n", (4968, 5003), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright Toolkit Authors from abc import ABC import cv2 from flatdict import FlatDict import numpy as np from pandas import DataFrame import re import ros_numpy import rosbag import rospy import sensor_msgs.msg import yaml from pydtk.models import BaseModel, register_model @register_model(priority=1) class GenericRosbagModel(BaseModel, ABC): """A generic model for a rosbag file.""" _content_type = 'application/rosbag' _data_type = None # allow any data-type _file_extensions = ['.bag'] _contents = { '.*': { 'msg_type': '.*' } } _config = { 'keys_to_exclude': [ 'header.seq', 'header.stamp.secs', 'header.stamp.nsecs', 'header.frame_id' ] } def __init__(self, **kwargs): super(GenericRosbagModel, self).__init__(**kwargs) def _load(self, path, contents=None, start_timestamp=None, end_timestamp=None, target_frame_rate=None, **kwargs): """Load a rosbag file. Args: path (str): path to a rosbag file contents (str or dict): topic name to load start_timestamp (float): timestamp to start loading (not supported) end_timestamp (float): timestamp to end loading (not supported) """ topic = None if isinstance(contents, str): topic = contents if isinstance(contents, dict): topic = next(iter(contents)) if topic is None: raise ValueError('Topic name must be specified by the argument "contents"') start_time = rospy.Time(start_timestamp) if start_timestamp else start_timestamp end_time = rospy.Time(end_timestamp) if end_timestamp else end_timestamp timestamps, data = [], [] with rosbag.Bag(path, 'r') as bag: if target_frame_rate: timestamps = self.load_timestamps(bag, topic, start_time, end_time) timestamps = self.downsample_timestamps(timestamps, target_frame_rate=target_frame_rate) idx = 0 for topic, msg, t in bag.read_messages(topics=[topic], start_time=start_time, end_time=end_time): timestamp = self.msg_to_timestamp(msg, t).to_sec() if target_frame_rate: if timestamp == timestamps[idx]: data.append(self.msg_to_data(msg, config=self._config, **kwargs)) idx += 1 if idx == len(timestamps): break continue timestamps.append(timestamp) data.append(self.msg_to_data(msg, config=self._config, **kwargs)) self.data = {'timestamps': timestamps, 'data': data} def _load_as_generator(self, path, contents=None, start_timestamp=None, end_timestamp=None, target_frame_rate=None, **kwargs): """Load a rosbag file for each sample. Args: path (str): path to a rosbag file contents (str or dict): topic name to load start_timestamp (float): timestamp to start loading (not supported) end_timestamp (float): timestamp to end loading (not supported) """ topic = None if isinstance(contents, str): topic = contents if isinstance(contents, dict): topic = next(iter(contents)) if topic is None: raise ValueError('Topic name must be specified by the argument "contents"') start_time = rospy.Time(start_timestamp) if start_timestamp else start_timestamp end_time = rospy.Time(end_timestamp) if end_timestamp else end_timestamp timestamps = [] with rosbag.Bag(path, 'r') as bag: if target_frame_rate: timestamps = self.load_timestamps(bag, topic, start_time, end_time) timestamps = self.downsample_timestamps(timestamps, target_frame_rate=target_frame_rate) idx = 0 for topic, msg, t in bag.read_messages(topics=[topic], start_time=start_time, end_time=end_time): timestamp = self.msg_to_timestamp(msg, t).to_sec() if target_frame_rate: if timestamp == timestamps[idx]: yield { 'timestamps': [timestamp], 'data': [self.msg_to_data(msg, config=self._config, **kwargs)] } idx += 1 if idx == len(timestamps): break continue yield { 'timestamps': [timestamp], 'data': [self.msg_to_data(msg, config=self._config, **kwargs)] } def _save(self, path, contents=None, **kwargs): """Save ndarray data to a csv file. Args: path (str): path to the output csv file contents (str or dict): topic name """ pass def to_dataframe(self): """Return data as a Pandas DataFrame. Returns: (DataFrame): data """ df = DataFrame.from_dict(self.data['data']) return df def to_ndarray(self): """Return data as ndarray.""" df = self.to_dataframe() return df.to_numpy() def load_timestamps(self, bag, topic, start_time, end_time): """Load only timestamps.""" timestamps = [] for topic, msg, t in bag.read_messages(topics=[topic], start_time=start_time, end_time=end_time): timestamps.append(self.msg_to_timestamp(msg, t).to_sec()) return timestamps @property def timestamps(self): """Return timestamps as ndarray.""" return np.array(self.data['timestamps']) @property def columns(self): """Return columns.""" if self._columns is not None: return self._columns if self.data is not None: if len(self.data['data']) > 0: return list(self.data['data'][0].keys()) return [] @staticmethod def msg_to_data(msg, **kwargs): """Convert a message to data. Args: msg (a ROS message): message Returns: (object): data """ keys_to_exclude = [] if 'config' in kwargs.keys() and 'keys_to_exclude' in kwargs['config'].keys(): keys_to_exclude = kwargs['config']['keys_to_exclude'] return {k: v for k, v in dict(FlatDict(yaml.safe_load(str(msg)), delimiter='.')).items() if k not in keys_to_exclude} @staticmethod def msg_to_timestamp(msg, t): """Extract timestamp from a message. Args: msg (a ROS message): message t (rospy.Time): timestamp read from rosbag Returns: (rospy.Time): timestamp """ if hasattr(msg, 'header'): if msg.header.stamp.is_zero(): return t return msg.header.stamp else: return t @classmethod def generate_contents_meta(cls, path, content_key='content'): """Generate contents metadata. Args: path (str): File path content_key (str): Key of content Returns: (dict): contents metadata """ # Load file contents = {} with rosbag.Bag(path, "r") as bag: # get topic names topic_info = bag.get_type_and_topic_info() topics = [topic for topic in topic_info[1].keys()] topics.sort() # Generate metadata for topic in topics: contents[topic] = {} contents[topic]["msg_type"] = topic_info[1][topic].msg_type contents[topic]["msg_md5sum"] = topic_info[0][topic_info[1][topic].msg_type] contents[topic]["count"] = topic_info[1][topic].message_count contents[topic]["frequency"] = topic_info[1][topic].frequency contents[topic]["tags"] = re.split('[_/-]', topic[1:]) return contents @classmethod def generate_timestamp_meta(cls, path): """Generate contents metadata. Args: path (str): File path Returns: (list): [start_timestamp, end_timestamp] """ with rosbag.Bag(path, "r") as bag: start_time = bag.get_start_time() end_time = bag.get_end_time() return [start_time, end_time] @register_model(priority=2) class SensorMsgsCompressedImageRosbagModel(GenericRosbagModel, ABC): """A model for a rosbag file containing sensor_msgs/Range.""" _contents = {'.*': {'msg_type': 'sensor_msgs/CompressedImage'}} _columns = ['red', 'green', 'blue'] @staticmethod def msg_to_data(msg, resize_rate=1.0, **kwargs): """Convert a message to data.""" jpg = np.fromstring(msg.data, np.uint8) image = cv2.imdecode(jpg, cv2.IMREAD_COLOR) if resize_rate != 1.0: image = cv2.resize(image, dsize=None, fx=resize_rate, fy=resize_rate, interpolation=cv2.INTER_LINEAR) image = image[:, :, ::-1] # Convert BGR to RGB image = image.transpose((2, 0, 1)) # Reshape: [H, W, C] -> [C, H, W] return image def to_ndarray(self): """Return data as ndarray.""" return np.array(self.data['data']) @register_model(priority=2) class SensorMsgsPointCloud2RosbagModel(GenericRosbagModel, ABC): """A model for a rosbag file containing sensor_msgs/PointCloud2.""" _contents = {'.*': {'msg_type': 'sensor_msgs/PointCloud2'}} _config = {'fields': ('x', 'y', 'z')} def __init__(self, fields=('x', 'y', 'z'), **kwargs): super(SensorMsgsPointCloud2RosbagModel, self).__init__(**kwargs) self._config['fields'] = fields def msg_to_data(self, msg, **kwargs): """Convert a message to data.""" if msg.__class__.__name__ == "_sensor_msgs__PointCloud2": msg.__class__ = sensor_msgs.msg._PointCloud2.PointCloud2 points = ros_numpy.numpify(msg)[list(self._config['fields'])] pointcloud = np.array(points.tolist()) if 'intensity' in self._config['fields']: pointcloud[:, self._config['fields'].index('intensity')] /= 255.0 # scale to [0, 1] return pointcloud def to_ndarray(self): """Return data as ndarray.""" return np.array(self.data['data'], dtype="object") @property def columns(self): """Return columns.""" return list(self._config['fields'])
[ "re.split", "pandas.DataFrame.from_dict", "rosbag.Bag", "ros_numpy.numpify", "cv2.imdecode", "rospy.Time", "numpy.array", "pydtk.models.register_model", "numpy.fromstring", "cv2.resize" ]
[((330, 356), 'pydtk.models.register_model', 'register_model', ([], {'priority': '(1)'}), '(priority=1)\n', (344, 356), False, 'from pydtk.models import BaseModel, register_model\n'), ((8974, 9000), 'pydtk.models.register_model', 'register_model', ([], {'priority': '(2)'}), '(priority=2)\n', (8988, 9000), False, 'from pydtk.models import BaseModel, register_model\n'), ((9900, 9926), 'pydtk.models.register_model', 'register_model', ([], {'priority': '(2)'}), '(priority=2)\n', (9914, 9926), False, 'from pydtk.models import BaseModel, register_model\n'), ((5571, 5609), 'pandas.DataFrame.from_dict', 'DataFrame.from_dict', (["self.data['data']"], {}), "(self.data['data'])\n", (5590, 5609), False, 'from pandas import DataFrame\n'), ((6230, 6263), 'numpy.array', 'np.array', (["self.data['timestamps']"], {}), "(self.data['timestamps'])\n", (6238, 6263), True, 'import numpy as np\n'), ((9372, 9405), 'numpy.fromstring', 'np.fromstring', (['msg.data', 'np.uint8'], {}), '(msg.data, np.uint8)\n', (9385, 9405), True, 'import numpy as np\n'), ((9422, 9457), 'cv2.imdecode', 'cv2.imdecode', (['jpg', 'cv2.IMREAD_COLOR'], {}), '(jpg, cv2.IMREAD_COLOR)\n', (9434, 9457), False, 'import cv2\n'), ((9869, 9896), 'numpy.array', 'np.array', (["self.data['data']"], {}), "(self.data['data'])\n", (9877, 9896), True, 'import numpy as np\n'), ((10932, 10975), 'numpy.array', 'np.array', (["self.data['data']"], {'dtype': '"""object"""'}), "(self.data['data'], dtype='object')\n", (10940, 10975), True, 'import numpy as np\n'), ((1700, 1727), 'rospy.Time', 'rospy.Time', (['start_timestamp'], {}), '(start_timestamp)\n', (1710, 1727), False, 'import rospy\n'), ((1787, 1812), 'rospy.Time', 'rospy.Time', (['end_timestamp'], {}), '(end_timestamp)\n', (1797, 1812), False, 'import rospy\n'), ((1897, 1918), 'rosbag.Bag', 'rosbag.Bag', (['path', '"""r"""'], {}), "(path, 'r')\n", (1907, 1918), False, 'import rosbag\n'), ((3823, 3850), 'rospy.Time', 'rospy.Time', (['start_timestamp'], {}), '(start_timestamp)\n', (3833, 3850), False, 'import rospy\n'), ((3910, 3935), 'rospy.Time', 'rospy.Time', (['end_timestamp'], {}), '(end_timestamp)\n', (3920, 3935), False, 'import rospy\n'), ((4010, 4031), 'rosbag.Bag', 'rosbag.Bag', (['path', '"""r"""'], {}), "(path, 'r')\n", (4020, 4031), False, 'import rosbag\n'), ((7880, 7901), 'rosbag.Bag', 'rosbag.Bag', (['path', '"""r"""'], {}), "(path, 'r')\n", (7890, 7901), False, 'import rosbag\n'), ((8514, 8542), 're.split', 're.split', (['"""[_/-]"""', 'topic[1:]'], {}), "('[_/-]', topic[1:])\n", (8522, 8542), False, 'import re\n'), ((8815, 8836), 'rosbag.Bag', 'rosbag.Bag', (['path', '"""r"""'], {}), "(path, 'r')\n", (8825, 8836), False, 'import rosbag\n'), ((9509, 9607), 'cv2.resize', 'cv2.resize', (['image'], {'dsize': 'None', 'fx': 'resize_rate', 'fy': 'resize_rate', 'interpolation': 'cv2.INTER_LINEAR'}), '(image, dsize=None, fx=resize_rate, fy=resize_rate, interpolation\n =cv2.INTER_LINEAR)\n', (9519, 9607), False, 'import cv2\n'), ((10579, 10601), 'ros_numpy.numpify', 'ros_numpy.numpify', (['msg'], {}), '(msg)\n', (10596, 10601), False, 'import ros_numpy\n')]
import importlib from typing import Any import numpy as np import collections import torch from collections import OrderedDict # https://github.com/quantumblacklabs/kedro/blob/9809bd7ca0556531fa4a2fc02d5b2dc26cf8fa97/kedro/utils.py def load_obj(obj_path: str, default_obj_path: str = "") -> Any: """Extract an object from a given path. Args: obj_path: Path to an object to be extracted, including the object name. default_obj_path: Default object path. Returns: Extracted object. Raises: AttributeError: When the object does not have the given named attribute. """ obj_path_list = obj_path.rsplit(".", 1) obj_path = obj_path_list.pop(0) if len(obj_path_list) > 1 else default_obj_path obj_name = obj_path_list[0] module_obj = importlib.import_module(obj_path) if not hasattr(module_obj, obj_name): raise AttributeError(f"Object `{obj_name}` cannot be loaded from `{obj_path}`.") return getattr(module_obj, obj_name) def preds_rounder(test_preds, num_class): # print(np.floor(np.clip(test_preds + 0.5, 0, num_class))) test_preds = np.floor(np.clip(test_preds + 0.5, 0, num_class - 1)) return test_preds def flatten_dict(d, parent_key="", sep="/"): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.MutableMapping): items.extend(flatten_dict(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) def load_pytorch_model(ckpt_name, model): state_dict = torch.load(ckpt_name)["state_dict"] new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k if name.startswith("model."): name = name.replace("model.", "") # remove `model.` new_state_dict[name] = v model.load_state_dict(new_state_dict) return model
[ "collections.OrderedDict", "torch.load", "importlib.import_module", "numpy.clip" ]
[((825, 858), 'importlib.import_module', 'importlib.import_module', (['obj_path'], {}), '(obj_path)\n', (848, 858), False, 'import importlib\n'), ((1696, 1709), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1707, 1709), False, 'from collections import OrderedDict\n'), ((1164, 1207), 'numpy.clip', 'np.clip', (['(test_preds + 0.5)', '(0)', '(num_class - 1)'], {}), '(test_preds + 0.5, 0, num_class - 1)\n', (1171, 1207), True, 'import numpy as np\n'), ((1639, 1660), 'torch.load', 'torch.load', (['ckpt_name'], {}), '(ckpt_name)\n', (1649, 1660), False, 'import torch\n')]
""" Linear Regression ----------------- Performs linear regression using descent and closed forms methods. Includes L1/L2 regularization. """ import numpy as np from utils import normalize from batch_gradient_descent import batch_gradient_descent class LinearRegression(object): """Class for performing linear regression.""" def __init__(self): """ Attributes: fitted (bool): whether or not the model has been fit theta (np.ndarray): vector of weights with size [n_features, 1] """ self.fitted = False self.theta = np.NaN def gradient(self, X, y, theta): """ Computes the gradient of the cost function (MSE). J(theta) = 1/(2*m) * (y - X*theta)^2 grad(J(Theta)) = 1/m * (y - X*theta) * X Args: X (np.ndarray): training data with shape [n_samples, n_features] y (np.ndarray): target values with shape [n_samples, 1] theta (np.ndarray): an array of weights with shape [n_features, 1] Returns: np.ndarray: the gradient of the MSE cost function """ m = len(y) gradient = 1./m * X.T.dot(np.subtract(X.dot(theta), y)) return gradient def fit(self, X, y, normalize_data=False, descent=True, regularization=None): """ Fits the model based on the training data. Args: X (np.ndarray): training data with shape [n_samples, n_features] y (np.ndarray): target values with shape [n_samples, 1] normalize_data (bool): whether or not to normalize input data descent (bool): whether to solve using a descent or normal equations method regularization (str): type of regularization to use (L1/L2) """ if normalize_data: X = normalize(X) X = np.insert(X, 0, 1, axis=1) if descent: self.theta = batch_gradient_descent(X, y, self.gradient) else: self.theta = np.dot(np.linalg.pinv(X.T.dot(X)), X.T.dot(y)) self.fitted = True def predict(self, X): """ Predicts an output for a given input vector based on the fitted model. Args: X (np.ndarray): input data with shape [n_samples, n_features] Returns: np.ndarray: predicted output with shape [n_samples, 1] Raise: ValueError: if model is not fit. """ if not self.fit: raise ValueError('Model must be fit before predicting.') X = np.insert(X, 0, 1, axis=1) return X.dot(self.theta)
[ "utils.normalize", "batch_gradient_descent.batch_gradient_descent", "numpy.insert" ]
[((1613, 1639), 'numpy.insert', 'np.insert', (['X', '(0)', '(1)'], {'axis': '(1)'}), '(X, 0, 1, axis=1)\n', (1622, 1639), True, 'import numpy as np\n'), ((2192, 2218), 'numpy.insert', 'np.insert', (['X', '(0)', '(1)'], {'axis': '(1)'}), '(X, 0, 1, axis=1)\n', (2201, 2218), True, 'import numpy as np\n'), ((1594, 1606), 'utils.normalize', 'normalize', (['X'], {}), '(X)\n', (1603, 1606), False, 'from utils import normalize\n'), ((1670, 1713), 'batch_gradient_descent.batch_gradient_descent', 'batch_gradient_descent', (['X', 'y', 'self.gradient'], {}), '(X, y, self.gradient)\n', (1692, 1713), False, 'from batch_gradient_descent import batch_gradient_descent\n')]
from os import urandom from numpy import prod, sum from nibabel.parrec import parse_PAR_header def create_random_rec(par_file): hdr, image = parse_PAR_header(par_file.open()) n_bytes = sum(prod(image['recon resolution'], axis=1) * image['image pixel size'] / 8) with par_file.with_suffix('.REC').open('wb') as f: f.write(urandom(int(n_bytes)))
[ "numpy.prod" ]
[((199, 238), 'numpy.prod', 'prod', (["image['recon resolution']"], {'axis': '(1)'}), "(image['recon resolution'], axis=1)\n", (203, 238), False, 'from numpy import prod, sum\n')]
import time import numpy as np with open("input.txt") as f: lines = f.readlines() S = lines.pop(0).strip() lines.pop(0) print(S) rules = {} for r in lines: s = r.strip().split(" -> ") rules[s[0]] = s[1] t = time.process_time() # For each rule, build out 20 iterations iterated_rules = {} for rule in rules.keys(): E = rule print(E) for step in range(20): E = E[0] + "".join(list(map(lambda x,y: rules[x+y] + y, E[0:-1], E[1:]))) iterated_rules[rule] = E print ("Time to expand 20 iterations of each rule: ", time.process_time() - t) # Find all unique characters that need to be in histogram chars = set() for v in iterated_rules.values(): chars.update(v) hist_indices = {} i=0 for c in chars: hist_indices[c] = i i += 1 num_bins = len(hist_indices) # Create histogram vector for each 20-level expanded seed pair # Don't count first character iterated_histogram = {} for key,val in iterated_rules.items(): H = np.zeros(num_bins) for c,i in hist_indices.items(): H[i] = val[1:].count(c) iterated_histogram[key] = H print ("Time to histogram each 20-iterated rule: ", time.process_time() - t) final_histogram = np.zeros(num_bins) final_histogram[hist_indices[iterated_rules[S[0:2]][0]]] += 1 #Iterated histograms omit first char to avoid doudle count for i in range(len(S)-1): print(i) seed_pair = S[i:i+2] hip = iterated_rules[seed_pair] # Half iterated pair for j in range(len(hip)-1): final_histogram += iterated_histogram[hip[j:j+2]] print ("Time to sum 40-deep histograms:", time.process_time() - t) print(max(final_histogram) - min(final_histogram))
[ "time.process_time", "numpy.zeros" ]
[((232, 251), 'time.process_time', 'time.process_time', ([], {}), '()\n', (249, 251), False, 'import time\n'), ((1202, 1220), 'numpy.zeros', 'np.zeros', (['num_bins'], {}), '(num_bins)\n', (1210, 1220), True, 'import numpy as np\n'), ((987, 1005), 'numpy.zeros', 'np.zeros', (['num_bins'], {}), '(num_bins)\n', (995, 1005), True, 'import numpy as np\n'), ((558, 577), 'time.process_time', 'time.process_time', ([], {}), '()\n', (575, 577), False, 'import time\n'), ((1155, 1174), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1172, 1174), False, 'import time\n'), ((1592, 1611), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1609, 1611), False, 'import time\n')]
from ceo.segmentPistonSensor import SegmentPistonSensor from ceo import constants, Telescope, cuFloatArray import numpy as np from scipy.optimize import leastsq from skimage.feature import blob_log from scipy.ndimage.interpolation import rotate class DispersedFringeSensor(SegmentPistonSensor): """ A class for the GMT Dispersed Fringe Sensor. This class inherits from the SegmentPistonSensor class. Parameters ---------- Same parameters as in SegmentPistonSensor class. Attributes ---------- INIT_ALL_ATTRIBUTES : bool ; Default: False If True, additional attributes (mainly for display and debugging) will be created. See list of Additional Attributes below. fftlet_rotation : float ; vector with 12xN_SRC elements The angle of the line joining the center of the three lobes of the fftlet image. Init by calibrate() method. lobe_detection : string ; default: 'gaussfit' Algorithm for lobe detection, either 'gaussfit' for 2D gaussian fit, or 'peak_value' for peak detection. spsmask : bool Data cube containing the masks (one for each fftlet) required to isolate the "detection blob", i.e. the upper-most lobe from which the measurement will be computed. Init by calibrate() method. measurement : float Dispersed Fringe Sensor output measurement vector; y-coordinate of the detection blob in the rotated reference frame (i.e. the reference frame having the x-axis passing through the three lobe peaks on a fftlet image, and the y-axis perpendicular to it. Units: pixels in the fftlet image plane. Attributes (Additional) ----------------------- blob_data : float fftlet peak detection data; blob_data is a matrix containing the (x,y,radius) of the three lobes on each fftlet image. Init by calibrate() method. pl_m, pl_b : float Slope and y-intercept of the line passing through the three lobe peaks on a fftlet image. Init by calibrate() method. pp_m, pp_b : float Slope and y-intercept of the perpendicular line to the line above, passing between the central and the "detection blob" in a ffltlet image. Init by calibrate() method. fftlet_fit_params : float Gaussian fit parameters of detection blobs (Amplitude normalized to central lobe peak, y, x, width_y, width_x, rotation). Init by process() method. fftlet_fit_images : float Data cube containing best-fit 2D gaussians of detection blobs. Init by process() method. measurement_ortho : float x-coordinate of the detection blob in the rotated reference frame (i.e. the reference frame having the x-axis passing through the three lobe peaks on a fftlet image, and the y-axis perpendicular to it. Init by process() method. See also -------- SegmentPistonSensor : the super class IdealSegmentPistonSensor : the class for an idealized segment piston sensor GMT_M1 : the class for GMT M1 model Source : a class for astronomical sources cuFloatArray : an interface class between GPU host and device data for floats """ def __init__(self, M1, src, lenslet_size=1.5, dispersion=5.0, field_of_view=3.0, nyquist_factor=1.0,BIN_IMAGE=2, MALLOC_DFT=True, middle_mask_width=0.0): SegmentPistonSensor.__init__(self) self._N_SRC = src.N_SRC self.INIT_ALL_ATTRIBUTES = False self.lobe_detection = 'gaussfit' def init_detector_mask(self, mask_size): """ Defines the circular mask to be applied over each fringe image. Parameters ---------- mask_size: float Diameter of mask in arcseconds. """ mask_size_px = mask_size / (self.pixel_scale * constants.RAD2ARCSEC) print("Size of DFS detector mask [pix]: %d"%(np.round(mask_size_px)) ) N_PX_FRINGE_IMAGE = self.camera.N_PX_IMAGE // self.camera.BIN_IMAGE scale = mask_size_px / N_PX_FRINGE_IMAGE circ = Telescope(N_PX_FRINGE_IMAGE, 1, scale=scale) circ_m = circ.f.host(shape=(N_PX_FRINGE_IMAGE,N_PX_FRINGE_IMAGE)) big_circ_m = np.tile(np.tile(circ_m,self.camera.N_SIDE_LENSLET).T,self.camera.N_SIDE_LENSLET) gpu_big_circ_m = cuFloatArray(host_data=big_circ_m) self.fft_mask.alter(gpu_big_circ_m) def gaussian_func(self, height, center_x, center_y, width_x, width_y, rotation): """ Returns a gaussian function G(x,y) to produce a 2D Gaussian with the given parameters Parameters ---------- height : float Amplitude of the Gaussian center_x : float x-coordinates of the Gaussian's center in pixels. center_y : float y-coordinates of the Gaussian's center in pixels. width_x : float standard deviation in the x-direction in pixels. width_y : float standard deviation in the y-direction in pixels. rotation : float angle of rotation of the Gaussian (x,y) axes in degrees. """ width_x = float(np.absolute(width_x)) width_y = float(np.absolute(width_y)) rotation = np.deg2rad(rotation) def rotgauss(x,y): xp = (x-center_x) * np.cos(rotation) - (y-center_y) * np.sin(rotation) + center_x yp = (x-center_x) * np.sin(rotation) + (y-center_y) * np.cos(rotation) + center_y g = height*np.exp( -(((center_x-xp)/width_x)**2+ ((center_y-yp)/width_y)**2)/2.) return g return rotgauss def fitgaussian(self, data): """ Fits a 2D Gaussian to the input data, and returns the Gaussian fit parameters: (amplidute, x, y, width_x, width_y, rotation) Parameters ---------- data : numpy 2D ndarray The array containing the image (i.e. the detection blob) to be fitted with a 2D Gaussian """ def moments(): total = data.sum() X, Y = np.indices(data.shape) x = (X*data).sum()/total y = (Y*data).sum()/total col = data[:, int(y)] width_x = np.sqrt(abs((np.arange(col.size)-y)**2*col).sum()/col.sum()) row = data[int(x), :] width_y = np.sqrt(abs((np.arange(row.size)-x)**2*row).sum()/row.sum()) height = data.max() return height, x, y, width_x, width_y, 0.0 params = moments() errorfunction = lambda p: np.ravel(self.gaussian_func(*p)(*np.indices(data.shape)) - data) p, success = leastsq(errorfunction, params) return p def get_data_cube(self, data_type='fftlet'): """ Returns the DFS data (either fringe or fftlet images) in cube format Parameters ---------- data_type : string. (default: fftlet) Set to "camera" to return fringes; Set to "fftlet" to return fftlet images; Set to "pupil_masks" to return the sub-aperture masks; Set to "phase" to return the phase on each sub-aperture. """ assert data_type=='fftlet' or data_type=='camera' or data_type=='pupil_masks' or data_type=='phase', "data_type should be either 'fftlet', 'camera', or 'pupil_masks', or 'phase'" n_lenslet = self.camera.N_SIDE_LENSLET if data_type == 'fftlet': data = self.fftlet.host() n_px = self.camera.N_PX_IMAGE elif data_type == 'camera': data = self.camera.frame.host() n_px = self.camera.N_PX_IMAGE//2 elif data_type == 'pupil_masks': data = self.W.amplitude.host() n_px = (data.shape)[0] // n_lenslet elif data_type == 'phase': data = self.W.phase.host() n_px = (data.shape)[0] // n_lenslet dataCube = np.zeros((n_px, n_px, self._N_SRC*12)) k = 0 for j in range(n_lenslet): for i in range(n_lenslet): dataCube[:,:,k] = data[i*n_px:(i+1)*n_px, j*n_px:(j+1)*n_px] k += 1 if k == self._N_SRC*12: break if k == self._N_SRC*12: break return dataCube def calibrate(self, src): """ Perform the following calibrations tasks: 1) Calibrates the lobe detection masks (spsmask). 2) Computes and stores the reference slopen null vector for a flat WF Parameters ---------- src : Source The Source object used for piston sensing """ self.reset() self.propagate(src) self.fft() dataCube = self.get_data_cube(data_type='fftlet') ### Essential data self.fftlet_rotation = np.zeros(src.N_SRC*12) self.spsmask = np.zeros((self.camera.N_PX_IMAGE,self.camera.N_PX_IMAGE,src.N_SRC*12), dtype='bool') ### Additional data for visualization and debugging if self.INIT_ALL_ATTRIBUTES == True: self.blob_data = np.zeros((src.N_SRC*12, 3, 3)) self.pl_m = np.zeros((src.N_SRC*12)) self.pl_b = np.zeros((src.N_SRC*12)) self.pp_m = np.zeros((src.N_SRC*12)) self.pp_b = np.zeros((src.N_SRC*12)) for k in range(src.N_SRC*12): ### Find center coordinates of three lobes (i.e. central and two lateral ones) on each imagelet. blob_data = blob_log(dataCube[:,:,k], min_sigma=5, max_sigma=10, overlap=1, threshold=0.005*np.max(dataCube[:,:,k])) assert blob_data.shape == (3,3), "lobe detection failed" blob_data = blob_data[np.argsort(blob_data[:,0])] #order data in asceding y-coord ### The code below does the following: ### 1) Fit a line passing through the centers of the three lobes (aka pl line). ### y = pl_m * x + pl_b ### 2) Find the perpendicular to the pl line (aka pp line) passing through a point lying between ### the central and uppermost lobe (aka BORDER POINT). ### y = pp_m * x + pp_b ### BORDER POINT coordinates (pp_x, pp,y) ### separation tweaking: 0.5 will select BORDER POINT equidistant to the two lobes. separation_tweaking = 0.6 pp_py, pp_px = blob_data[1,0:2] + separation_tweaking*(blob_data[2,0:2] - blob_data[1,0:2]) if np.all(blob_data[:,1] == blob_data[0,1]): # pl line is VERTICAL pp_m = 0. self.fftlet_rotation[k] = 0. pl_m = float('inf') else: pl_m, pl_b = np.polyfit(blob_data[:,1], blob_data[:,0], 1) # pl line fitting pp_m = -1.0 / pl_m fftlet_rotation = np.arctan(pl_m) ### We know that the rotation angles are [-90, -30, 30, 90]. apriori_angles = np.array([-90,-30,30,90]) fftlet_rotation = (np.pi/180)*min(apriori_angles, key=lambda aa:abs(aa-fftlet_rotation*180/np.pi)) self.fftlet_rotation[k] = fftlet_rotation pp_m = -1.0/ np.tan(fftlet_rotation) pp_b = pp_py - pp_m * pp_px ### Define the SPS masks as the region y > pp line u = np.arange(self.camera.N_PX_IMAGE) v = np.arange(self.camera.N_PX_IMAGE) xx,yy = np.meshgrid(u,v) self.spsmask[:,:,k] = yy > xx*pp_m+pp_b if self.INIT_ALL_ATTRIBUTES == True: self.blob_data[k,:,:] = blob_data self.pl_m[k] = pl_m self.pl_b[k] = pl_b self.pp_m[k] = pp_m self.pp_b[k] = pp_b ### Compute reference measurement vector (for flat WF) self.process() self._ref_measurement = self.measurement.copy() def set_reference_measurement(self, src): """ Calibrates the reference measurement vector """ self.reset() self.analyze(src) self._ref_measurement = self.measurement.copy() def reset(self): """ Resets both the SPS detector frame and the fftlet buffer to zero. """ self.camera.reset() self.fftlet.reset() def process(self): """ Processes the Dispersed Fringe Sensor detector frame """ dataCube = self.get_data_cube(data_type='fftlet') self.measurement = np.zeros(self._N_SRC*12) if self.INIT_ALL_ATTRIBUTES == True: self.fftlet_fit_params = np.zeros((6,self._N_SRC*12)) self.measurement_ortho = np.zeros(self._N_SRC*12) if self.lobe_detection == 'gaussfit': self.fftlet_fit_images = np.zeros((self.camera.N_PX_IMAGE,self.camera.N_PX_IMAGE,self._N_SRC*12)) for k in range(self._N_SRC*12): mylobe = dataCube[:,:,k] * self.spsmask[:,:,k] centralpeak = np.max(dataCube[:,:,k]) if self.lobe_detection == 'gaussfit': params = self.fitgaussian(mylobe) (height, y, x, width_y, width_x, rot) = params elif self.lobe_detection == 'peak_value': mylobe = rotate(mylobe,self.fftlet_rotation[k]*180/np.pi, reshape=False) height = np.max(mylobe) height_pos = np.argmax(mylobe) y, x = np.unravel_index(height_pos, mylobe.shape) if y < (mylobe.shape[0]-1) and x < (mylobe.shape[1]-1): dx = 0.5*(mylobe[y,x-1] - mylobe[y,x+1]) / (mylobe[y,x-1]+mylobe[y,x+1]-2*height+1e-6) dy = 0.5*(mylobe[y-1,x] - mylobe[y+1,x]) / (mylobe[y-1,x]+mylobe[y+1,x]-2*height+1e-6) x += dx y += dy width_x, width_y, rot = 0,0,0 #x1 = x * np.cos(-self.fftlet_rotation[k]) - y * np.sin(-self.fftlet_rotation[k]) #y1 = x * np.sin(-self.fftlet_rotation[k]) + y * np.cos(-self.fftlet_rotation[k]) y1 = y x1 = x self.measurement[k] = y1 if self.INIT_ALL_ATTRIBUTES == True: self.measurement_ortho[k] = x1 self.fftlet_fit_params[:,k] = (height / centralpeak, y, x, width_y, width_x, rot) if self.lobe_detection == 'gaussfit': fftlet_shape = (self.camera.N_PX_IMAGE,self.camera.N_PX_IMAGE) self.fftlet_fit_images[:,:,k] = self.gaussian_func(*params)(*np.indices(fftlet_shape)) def analyze(self, src): """ Propagates the guide star to the SPS detector (noiseless) and processes the frame Parameters ---------- src : Source The piston sensing guide star object """ self.propagate(src) self.fft() self.process() def piston(self, src): """ Return M1 differential piston. This method was created to provide compatibility with the IdealSegmentPistonSensor Piston method. Parameters ---------- src : Source The piston sensing guide star object Return ------ p : numpy ndarray A 12 element differential piston vector """ self.analyze(src) p = self.get_measurement() return p.reshape(-1,12) @property def Data(self): return self.get_measurement() def get_measurement(self): """ Returns the measurement vector minus reference vector. """ return self.measurement - self._ref_measurement def get_measurement_size(self): """ Returns the size of the measurement vector """ return self._N_SRC*12 def get_ref_measurement(self): return self._ref_measurement
[ "numpy.absolute", "numpy.polyfit", "numpy.argmax", "ceo.segmentPistonSensor.SegmentPistonSensor.__init__", "scipy.optimize.leastsq", "numpy.argsort", "numpy.sin", "numpy.arange", "numpy.tile", "numpy.exp", "numpy.round", "numpy.meshgrid", "ceo.Telescope", "numpy.max", "numpy.tan", "ceo...
[((3321, 3355), 'ceo.segmentPistonSensor.SegmentPistonSensor.__init__', 'SegmentPistonSensor.__init__', (['self'], {}), '(self)\n', (3349, 3355), False, 'from ceo.segmentPistonSensor import SegmentPistonSensor\n'), ((4016, 4060), 'ceo.Telescope', 'Telescope', (['N_PX_FRINGE_IMAGE', '(1)'], {'scale': 'scale'}), '(N_PX_FRINGE_IMAGE, 1, scale=scale)\n', (4025, 4060), False, 'from ceo import constants, Telescope, cuFloatArray\n'), ((4262, 4296), 'ceo.cuFloatArray', 'cuFloatArray', ([], {'host_data': 'big_circ_m'}), '(host_data=big_circ_m)\n', (4274, 4296), False, 'from ceo import constants, Telescope, cuFloatArray\n'), ((5196, 5216), 'numpy.deg2rad', 'np.deg2rad', (['rotation'], {}), '(rotation)\n', (5206, 5216), True, 'import numpy as np\n'), ((6606, 6636), 'scipy.optimize.leastsq', 'leastsq', (['errorfunction', 'params'], {}), '(errorfunction, params)\n', (6613, 6636), False, 'from scipy.optimize import leastsq\n'), ((7810, 7850), 'numpy.zeros', 'np.zeros', (['(n_px, n_px, self._N_SRC * 12)'], {}), '((n_px, n_px, self._N_SRC * 12))\n', (7818, 7850), True, 'import numpy as np\n'), ((8690, 8714), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12)'], {}), '(src.N_SRC * 12)\n', (8698, 8714), True, 'import numpy as np\n'), ((8736, 8828), 'numpy.zeros', 'np.zeros', (['(self.camera.N_PX_IMAGE, self.camera.N_PX_IMAGE, src.N_SRC * 12)'], {'dtype': '"""bool"""'}), "((self.camera.N_PX_IMAGE, self.camera.N_PX_IMAGE, src.N_SRC * 12),\n dtype='bool')\n", (8744, 8828), True, 'import numpy as np\n'), ((12376, 12402), 'numpy.zeros', 'np.zeros', (['(self._N_SRC * 12)'], {}), '(self._N_SRC * 12)\n', (12384, 12402), True, 'import numpy as np\n'), ((5109, 5129), 'numpy.absolute', 'np.absolute', (['width_x'], {}), '(width_x)\n', (5120, 5129), True, 'import numpy as np\n'), ((5155, 5175), 'numpy.absolute', 'np.absolute', (['width_y'], {}), '(width_y)\n', (5166, 5175), True, 'import numpy as np\n'), ((6040, 6062), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (6050, 6062), True, 'import numpy as np\n'), ((8955, 8987), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12, 3, 3)'], {}), '((src.N_SRC * 12, 3, 3))\n', (8963, 8987), True, 'import numpy as np\n'), ((9010, 9034), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12)'], {}), '(src.N_SRC * 12)\n', (9018, 9034), True, 'import numpy as np\n'), ((9059, 9083), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12)'], {}), '(src.N_SRC * 12)\n', (9067, 9083), True, 'import numpy as np\n'), ((9108, 9132), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12)'], {}), '(src.N_SRC * 12)\n', (9116, 9132), True, 'import numpy as np\n'), ((9157, 9181), 'numpy.zeros', 'np.zeros', (['(src.N_SRC * 12)'], {}), '(src.N_SRC * 12)\n', (9165, 9181), True, 'import numpy as np\n'), ((10366, 10408), 'numpy.all', 'np.all', (['(blob_data[:, 1] == blob_data[0, 1])'], {}), '(blob_data[:, 1] == blob_data[0, 1])\n', (10372, 10408), True, 'import numpy as np\n'), ((11220, 11253), 'numpy.arange', 'np.arange', (['self.camera.N_PX_IMAGE'], {}), '(self.camera.N_PX_IMAGE)\n', (11229, 11253), True, 'import numpy as np\n'), ((11270, 11303), 'numpy.arange', 'np.arange', (['self.camera.N_PX_IMAGE'], {}), '(self.camera.N_PX_IMAGE)\n', (11279, 11303), True, 'import numpy as np\n'), ((11324, 11341), 'numpy.meshgrid', 'np.meshgrid', (['u', 'v'], {}), '(u, v)\n', (11335, 11341), True, 'import numpy as np\n'), ((12484, 12515), 'numpy.zeros', 'np.zeros', (['(6, self._N_SRC * 12)'], {}), '((6, self._N_SRC * 12))\n', (12492, 12515), True, 'import numpy as np\n'), ((12550, 12576), 'numpy.zeros', 'np.zeros', (['(self._N_SRC * 12)'], {}), '(self._N_SRC * 12)\n', (12558, 12576), True, 'import numpy as np\n'), ((12865, 12890), 'numpy.max', 'np.max', (['dataCube[:, :, k]'], {}), '(dataCube[:, :, k])\n', (12871, 12890), True, 'import numpy as np\n'), ((3850, 3872), 'numpy.round', 'np.round', (['mask_size_px'], {}), '(mask_size_px)\n', (3858, 3872), True, 'import numpy as np\n'), ((4164, 4207), 'numpy.tile', 'np.tile', (['circ_m', 'self.camera.N_SIDE_LENSLET'], {}), '(circ_m, self.camera.N_SIDE_LENSLET)\n', (4171, 4207), True, 'import numpy as np\n'), ((5456, 5545), 'numpy.exp', 'np.exp', (['(-(((center_x - xp) / width_x) ** 2 + ((center_y - yp) / width_y) ** 2) / 2.0)'], {}), '(-(((center_x - xp) / width_x) ** 2 + ((center_y - yp) / width_y) ** \n 2) / 2.0)\n', (5462, 5545), True, 'import numpy as np\n'), ((9595, 9622), 'numpy.argsort', 'np.argsort', (['blob_data[:, 0]'], {}), '(blob_data[:, 0])\n', (9605, 9622), True, 'import numpy as np\n'), ((10587, 10634), 'numpy.polyfit', 'np.polyfit', (['blob_data[:, 1]', 'blob_data[:, 0]', '(1)'], {}), '(blob_data[:, 1], blob_data[:, 0], 1)\n', (10597, 10634), True, 'import numpy as np\n'), ((10721, 10736), 'numpy.arctan', 'np.arctan', (['pl_m'], {}), '(pl_m)\n', (10730, 10736), True, 'import numpy as np\n'), ((10847, 10875), 'numpy.array', 'np.array', (['[-90, -30, 30, 90]'], {}), '([-90, -30, 30, 90])\n', (10855, 10875), True, 'import numpy as np\n'), ((12666, 12742), 'numpy.zeros', 'np.zeros', (['(self.camera.N_PX_IMAGE, self.camera.N_PX_IMAGE, self._N_SRC * 12)'], {}), '((self.camera.N_PX_IMAGE, self.camera.N_PX_IMAGE, self._N_SRC * 12))\n', (12674, 12742), True, 'import numpy as np\n'), ((11075, 11098), 'numpy.tan', 'np.tan', (['fftlet_rotation'], {}), '(fftlet_rotation)\n', (11081, 11098), True, 'import numpy as np\n'), ((13132, 13200), 'scipy.ndimage.interpolation.rotate', 'rotate', (['mylobe', '(self.fftlet_rotation[k] * 180 / np.pi)'], {'reshape': '(False)'}), '(mylobe, self.fftlet_rotation[k] * 180 / np.pi, reshape=False)\n', (13138, 13200), False, 'from scipy.ndimage.interpolation import rotate\n'), ((13221, 13235), 'numpy.max', 'np.max', (['mylobe'], {}), '(mylobe)\n', (13227, 13235), True, 'import numpy as np\n'), ((13265, 13282), 'numpy.argmax', 'np.argmax', (['mylobe'], {}), '(mylobe)\n', (13274, 13282), True, 'import numpy as np\n'), ((13306, 13348), 'numpy.unravel_index', 'np.unravel_index', (['height_pos', 'mylobe.shape'], {}), '(height_pos, mylobe.shape)\n', (13322, 13348), True, 'import numpy as np\n'), ((5277, 5293), 'numpy.cos', 'np.cos', (['rotation'], {}), '(rotation)\n', (5283, 5293), True, 'import numpy as np\n'), ((5311, 5327), 'numpy.sin', 'np.sin', (['rotation'], {}), '(rotation)\n', (5317, 5327), True, 'import numpy as np\n'), ((5371, 5387), 'numpy.sin', 'np.sin', (['rotation'], {}), '(rotation)\n', (5377, 5387), True, 'import numpy as np\n'), ((5405, 5421), 'numpy.cos', 'np.cos', (['rotation'], {}), '(rotation)\n', (5411, 5421), True, 'import numpy as np\n'), ((9467, 9492), 'numpy.max', 'np.max', (['dataCube[:, :, k]'], {}), '(dataCube[:, :, k])\n', (9473, 9492), True, 'import numpy as np\n'), ((6553, 6575), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (6563, 6575), True, 'import numpy as np\n'), ((14413, 14437), 'numpy.indices', 'np.indices', (['fftlet_shape'], {}), '(fftlet_shape)\n', (14423, 14437), True, 'import numpy as np\n'), ((6206, 6225), 'numpy.arange', 'np.arange', (['col.size'], {}), '(col.size)\n', (6215, 6225), True, 'import numpy as np\n'), ((6323, 6342), 'numpy.arange', 'np.arange', (['row.size'], {}), '(row.size)\n', (6332, 6342), True, 'import numpy as np\n')]
import math import matplotlib.pyplot as plt import numpy as np import scipy as sp from scipy.optimize import leastsq steps = [] distance = [] def load_data(filename): # read RandomWalk data from file f = open(filename) for line in f.readlines(): line = line.strip().split() steps.append(int(line[0])) distance.append(float(line[1])) def viz(): # plot the distance-steps relationship plt.ion() plt.figure(figsize=(8, 8)) # 可视化 plt.plot(steps, distance) plt.title("distance-steps relationship") plt.xlabel("steps") plt.ylabel("distance") plt.show() plt.pause(0) plt.ioff() def cal_by_lse(): def func(p, x): # guess the function format should be y = k * x + b via the graph k, b = p return k * x + b def error(p, x, y): return func(p, x) - y # calculate the expression via LSE(least squares method) xi = np.asarray(steps) yi = np.asarray(distance) p0 = np.asarray([1 / 25.0, 2.5]) # guess the init value of k via the graph p = leastsq(error, p0, args=(xi, yi)) k, b = p[0][0], p[0][1] return k, b def viz_with_line(k, b): # plot the distance-steps relationship plt.ion() plt.figure(figsize=(8, 8)) # 可视化 plt.plot(steps, distance) x = range(1, 5002, 1000) y = k * x + b plt.plot(x, y) plt.title("distance-steps relationship") plt.xlabel("steps") plt.ylabel("distance") plt.show() plt.pause(0) plt.ioff() def cal_by_lse_2(): def func(p, x): # guess the function format should be y = k * sqrt(x) via the graph k = p return k * np.sqrt(x) def error(p, x, y): return func(p, x) - y # calculate the expression via LSE(least squares method) xi = np.asarray(steps) yi = np.asarray(distance) p0 = np.asarray([1 / 25.0]) # guess the init value of k via the graph p = leastsq(error, p0, args=(xi, yi)) k = p[0][0] return k def viz_with_line_2(k): # plot the distance-steps relationship plt.ion() plt.figure(figsize=(8, 8)) # 可视化 plt.plot(steps, distance) x = range(1, 5002, 100) y = k * np.sqrt(x) plt.plot(x, y, linewidth=3) plt.title("distance-steps relationship") plt.xlabel("steps") plt.ylabel("distance") plt.show() plt.pause(0) plt.ioff() if __name__ == '__main__': load_data("./result.csv") # viz() # K, b = cal_by_lse() # print("result expression: distance =", K, "* steps + ", b) K = cal_by_lse_2() print("result expression: distance =", K, "* sqrt(steps)") viz_with_line_2(K)
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ioff", "numpy.asarray", "scipy.optimize.leastsq", "matplotlib.pyplot.ion", "matplotlib.pyplot.figure", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.pause", "numpy.sqr...
[((434, 443), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (441, 443), True, 'import matplotlib.pyplot as plt\n'), ((448, 474), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (458, 474), True, 'import matplotlib.pyplot as plt\n'), ((486, 511), 'matplotlib.pyplot.plot', 'plt.plot', (['steps', 'distance'], {}), '(steps, distance)\n', (494, 511), True, 'import matplotlib.pyplot as plt\n'), ((516, 556), 'matplotlib.pyplot.title', 'plt.title', (['"""distance-steps relationship"""'], {}), "('distance-steps relationship')\n", (525, 556), True, 'import matplotlib.pyplot as plt\n'), ((561, 580), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""steps"""'], {}), "('steps')\n", (571, 580), True, 'import matplotlib.pyplot as plt\n'), ((585, 607), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""distance"""'], {}), "('distance')\n", (595, 607), True, 'import matplotlib.pyplot as plt\n'), ((612, 622), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (620, 622), True, 'import matplotlib.pyplot as plt\n'), ((627, 639), 'matplotlib.pyplot.pause', 'plt.pause', (['(0)'], {}), '(0)\n', (636, 639), True, 'import matplotlib.pyplot as plt\n'), ((644, 654), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (652, 654), True, 'import matplotlib.pyplot as plt\n'), ((937, 954), 'numpy.asarray', 'np.asarray', (['steps'], {}), '(steps)\n', (947, 954), True, 'import numpy as np\n'), ((964, 984), 'numpy.asarray', 'np.asarray', (['distance'], {}), '(distance)\n', (974, 984), True, 'import numpy as np\n'), ((994, 1021), 'numpy.asarray', 'np.asarray', (['[1 / 25.0, 2.5]'], {}), '([1 / 25.0, 2.5])\n', (1004, 1021), True, 'import numpy as np\n'), ((1075, 1108), 'scipy.optimize.leastsq', 'leastsq', (['error', 'p0'], {'args': '(xi, yi)'}), '(error, p0, args=(xi, yi))\n', (1082, 1108), False, 'from scipy.optimize import leastsq\n'), ((1228, 1237), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1235, 1237), True, 'import matplotlib.pyplot as plt\n'), ((1242, 1268), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (1252, 1268), True, 'import matplotlib.pyplot as plt\n'), ((1280, 1305), 'matplotlib.pyplot.plot', 'plt.plot', (['steps', 'distance'], {}), '(steps, distance)\n', (1288, 1305), True, 'import matplotlib.pyplot as plt\n'), ((1358, 1372), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (1366, 1372), True, 'import matplotlib.pyplot as plt\n'), ((1378, 1418), 'matplotlib.pyplot.title', 'plt.title', (['"""distance-steps relationship"""'], {}), "('distance-steps relationship')\n", (1387, 1418), True, 'import matplotlib.pyplot as plt\n'), ((1423, 1442), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""steps"""'], {}), "('steps')\n", (1433, 1442), True, 'import matplotlib.pyplot as plt\n'), ((1447, 1469), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""distance"""'], {}), "('distance')\n", (1457, 1469), True, 'import matplotlib.pyplot as plt\n'), ((1474, 1484), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1482, 1484), True, 'import matplotlib.pyplot as plt\n'), ((1489, 1501), 'matplotlib.pyplot.pause', 'plt.pause', (['(0)'], {}), '(0)\n', (1498, 1501), True, 'import matplotlib.pyplot as plt\n'), ((1506, 1516), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (1514, 1516), True, 'import matplotlib.pyplot as plt\n'), ((1805, 1822), 'numpy.asarray', 'np.asarray', (['steps'], {}), '(steps)\n', (1815, 1822), True, 'import numpy as np\n'), ((1832, 1852), 'numpy.asarray', 'np.asarray', (['distance'], {}), '(distance)\n', (1842, 1852), True, 'import numpy as np\n'), ((1862, 1884), 'numpy.asarray', 'np.asarray', (['[1 / 25.0]'], {}), '([1 / 25.0])\n', (1872, 1884), True, 'import numpy as np\n'), ((1938, 1971), 'scipy.optimize.leastsq', 'leastsq', (['error', 'p0'], {'args': '(xi, yi)'}), '(error, p0, args=(xi, yi))\n', (1945, 1971), False, 'from scipy.optimize import leastsq\n'), ((2075, 2084), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (2082, 2084), True, 'import matplotlib.pyplot as plt\n'), ((2089, 2115), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (2099, 2115), True, 'import matplotlib.pyplot as plt\n'), ((2127, 2152), 'matplotlib.pyplot.plot', 'plt.plot', (['steps', 'distance'], {}), '(steps, distance)\n', (2135, 2152), True, 'import matplotlib.pyplot as plt\n'), ((2209, 2236), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'linewidth': '(3)'}), '(x, y, linewidth=3)\n', (2217, 2236), True, 'import matplotlib.pyplot as plt\n'), ((2242, 2282), 'matplotlib.pyplot.title', 'plt.title', (['"""distance-steps relationship"""'], {}), "('distance-steps relationship')\n", (2251, 2282), True, 'import matplotlib.pyplot as plt\n'), ((2287, 2306), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""steps"""'], {}), "('steps')\n", (2297, 2306), True, 'import matplotlib.pyplot as plt\n'), ((2311, 2333), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""distance"""'], {}), "('distance')\n", (2321, 2333), True, 'import matplotlib.pyplot as plt\n'), ((2338, 2348), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2346, 2348), True, 'import matplotlib.pyplot as plt\n'), ((2353, 2365), 'matplotlib.pyplot.pause', 'plt.pause', (['(0)'], {}), '(0)\n', (2362, 2365), True, 'import matplotlib.pyplot as plt\n'), ((2370, 2380), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (2378, 2380), True, 'import matplotlib.pyplot as plt\n'), ((2194, 2204), 'numpy.sqrt', 'np.sqrt', (['x'], {}), '(x)\n', (2201, 2204), True, 'import numpy as np\n'), ((1668, 1678), 'numpy.sqrt', 'np.sqrt', (['x'], {}), '(x)\n', (1675, 1678), True, 'import numpy as np\n')]
import numpy as np import xarray as xr import math from datetime import datetime from sentinelhub import CRS, BBox from ._common import ProcessEOTask, ProcessArgumentInvalid, ProcessArgumentRequired class create_cubeEOTask(ProcessEOTask): """ This process generates an xarray from input data. It is useful for writing tests, because it allows us to generate synthetic data, which we can then process and compare to expected (again synthetic) result. """ def process(self, arguments): data_as_list = self.validate_parameter(arguments, "data", required=True, allowed_types=[list]) dims = self.validate_parameter(arguments, "dims", required=True, allowed_types=[list]) coords = self.validate_parameter(arguments, "coords", allowed_types=[dict], default={}) if "t" in coords: coords["t"] = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in coords["t"]] data = xr.DataArray( np.array(data_as_list, dtype=np.float), coords=coords, dims=dims, attrs={ "band_aliases": {}, "bbox": BBox((12.0, 45.0, 13.0, 46.0,), CRS(4326)), }, ) self.logger.info(data) return data
[ "sentinelhub.CRS", "datetime.datetime.strptime", "numpy.array" ]
[((976, 1014), 'numpy.array', 'np.array', (['data_as_list'], {'dtype': 'np.float'}), '(data_as_list, dtype=np.float)\n', (984, 1014), True, 'import numpy as np\n'), ((870, 911), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(d, '%Y-%m-%d %H:%M:%S')\n", (887, 911), False, 'from datetime import datetime\n'), ((1178, 1187), 'sentinelhub.CRS', 'CRS', (['(4326)'], {}), '(4326)\n', (1181, 1187), False, 'from sentinelhub import CRS, BBox\n')]
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.ticker import AutoMinorLocator from matplotlib.ticker import MultipleLocator from matplotlib.ticker import LogLocator import importlib import math import sys import scipy.io if not '../aux/' in sys.path: sys.path.append('../aux/') import paths; importlib.reload(paths) import spec; importlib.reload(spec) import phys; importlib.reload(phys) import nessy; importlib.reload(nessy) import auxsys; importlib.reload(auxsys) import auxplt; importlib.reload(auxplt) prefix0 = paths.it0f prefix1 = paths.it1f #1 - NESSY LTE #2 - NESSY NLTE #3 - ATLAS #4 - NESSY LTE FAL #5 - NESSY NLTE FAL #wn, Q1h = nessy.read_spec(prefix0 + 'var/Q/kur_cardsdef', wvl1 = 1005, wvl2 = 16000) #wn, F1h = nessy.read_spec(prefix0 + 'var/F/kur_cardsdef', wvl1 = 1005, wvl2 = 16000) #wn, Q2h = nessy.read_spec(prefix1 + 'var/Q/kur_cardsdef', wvl1 = 1005, wvl2 = 16000) #wn, F2h = nessy.read_spec(prefix1 + 'var/F/kur_cardsdef', wvl1 = 1005, wvl2 = 16000) #wn, Q4h = nessy.read_spec(prefix0 + 'var/Q/fal_cardsdef', wvl1 = 1005, wvl2 = 16000) wn, Q4h = nessy.read_spec(prefix0 + 'VAR/Q_kur_old', wvl1 = 1005, wvl2 = 16000) #wn, F4h = nessy.read_spec(prefix0 + 'var/F/fal_cardsdef', wvl1 = 1005, wvl2 = 16000) #wn, Q5h = nessy.read_spec(prefix1 + 'var/Q/fal_cardsdef', wvl1 = 1005, wvl2 = 16000) wn, Q5h = nessy.read_spec(prefix1 + 'VAR/Q_kur_old', wvl1 = 1005, wvl2 = 16000) #wn, F5h = nessy.read_spec(prefix1 + 'var/F/fal_cardsdef', wvl1 = 1005, wvl2 = 16000) wn = wn / 10.0 #wns, Q1 = spec.mean_within_delta(wn, Q1h, 10) #wns, F1 = spec.mean_within_delta(wn, F1h, 10) #wns, Q2 = spec.mean_within_delta(wn, Q2h, 10) #wns, F2 = spec.mean_within_delta(wn, F2h, 10) wns, Q4 = spec.mean_within_delta(wn, Q4h, 10) #wns, F4 = spec.mean_within_delta(wn, F4h, 10) wns, Q5 = spec.mean_within_delta(wn, Q5h, 10) #wns, F5 = spec.mean_within_delta(wn, F5h, 10) np.savez(paths.npz + 'spec_var_whi_fallte_C_new', w = wns, # q1 = Q1,\ # f1 = F1,\ # q2 = Q2,\ # f2 = F2,\ q4 = Q4,\ # f4 = F4,\ q5 = Q5)\ # f5 = F5,) contr = np.load(paths.npz + 'spec_var_whi_fallte_C_new.npz') w = contr['w'] #Q1 = contr['q1'] #F1 = contr['f1'] #Q2 = contr['q2'] #F2 = contr['f2'] Q4 = contr['q4'] #F4 = contr['f4'] Q5 = contr['q5'] #F5 = contr['f5'] plt.close('all') #fig, ax = plt.subplots(nrows = 3, ncols = 1, figsize = (6.0, 12.06)) fig, ax = plt.subplots(nrows = 2, ncols = 1, figsize = (6.0, 8.00)) bbox = dict(boxstyle = 'round', ec = (1.0, 0.5, 0.5), fc = (1.0, 0.8, 0.8),) auxplt.figpar(3, 3, 20) fig.tight_layout() plt.subplots_adjust(hspace = 0.15) ls = ':' lw = 1.0 #ax[0].plot(w, Q1, color = 'm', linewidth = lw, label = 'NESSY (LTE, U99)') #ax[0].plot(w, Q2, color = 'g', linewidth = lw, label = 'NESSY (NLTE, U99)') ax[0].plot(w, Q4, color = 'k', linewidth = lw, label = 'NESSY (LTE, FAL99)', linestyle = '--') ax[0].plot(w, Q5, color = 'k', linewidth = lw, label = 'NESSY (NLTE, FAL99)') #ax[0].text(720, 1.62, 'Quiet Sun', bbox = bbox) #ax[1].plot(w, F1, color = 'm', linewidth = lw, label = 'NESSY (LTE, U99)') #ax[1].plot(w, F2, color = 'g', linewidth = lw, label = 'NESSY (NLTE, U99)') #ax[0].plot(w, F4, color = 'r', linewidth = lw, label = 'NESSY (LTE, FAL99)', linestyle = '--') #ax[0].plot(w, F5, color = 'r', linewidth = lw, label = 'NESSY (NLTE, FAL99)') #ax[0].text(700, 1.80, 'Facula', bbox = bbox) #ax[1].plot(w, Q2 / Q1, label = 'Quiet Sun, U99', color = 'orange') ax[1].plot(w, Q5 / Q4, label = 'Quiet Sun, FAL99', color = 'k') #ax[1].plot(w, F2 / F1, label = 'Facula, U99', linestyle = '--', color = 'orange') #ax[1].plot(w, F5 / F4, label = 'Facula, FAL99', color = 'r') ax[1].axhline(y = 1.0, color = 'k') ax[1].set_xlim(170, 1600) ax[1].set_ylim(0.84, 1.22) ax[0].set_ylim(bottom = 0.0) ax[1].xaxis.set_major_locator(MultipleLocator(300)) #ax[1].xaxis.set_minor_locator(AutoMinorLocator(5)) ax[1].yaxis.set_minor_locator(AutoMinorLocator(5)) ax[1].set_ylabel('NLTE / LTE') for i in [0, 1]: ax[i].set_xlim(170, 1600) ax[i].xaxis.set_major_locator(MultipleLocator(300)) # ax[i].xaxis.set_minor_locator(AutoMinorLocator(5)) ax[i].yaxis.set_minor_locator(AutoMinorLocator(5)) ax[0].set_ylabel(r'Flux, [W / m$^2$ / nm]', fontsize = 20) ax[1].set_xlabel('Wavelength, [nm]', fontsize = 20) #leg0 = ax[0].legend(framealpha = 1, loc = 3, bbox_to_anchor = (0.539, 0.03), handletextpad = 1, prop = {'size': 22.0}) #leg2 = ax[2].legend(framealpha = 1, loc = 1, handletextpad = 1, prop = {'size': 22.0}) #for obj in leg0.legendHandles: obj.set_linewidth(5.0) #for obj in leg2.legendHandles: obj.set_linewidth(5.0) auxplt.savepdf('var/Q_kur_old')
[ "sys.path.append", "numpy.load", "spec.mean_within_delta", "matplotlib.pyplot.close", "auxplt.figpar", "importlib.reload", "matplotlib.ticker.AutoMinorLocator", "matplotlib.pyplot.subplots_adjust", "matplotlib.ticker.MultipleLocator", "numpy.savez", "matplotlib.pyplot.subplots", "auxplt.savepd...
[((379, 402), 'importlib.reload', 'importlib.reload', (['paths'], {}), '(paths)\n', (395, 402), False, 'import importlib\n'), ((418, 440), 'importlib.reload', 'importlib.reload', (['spec'], {}), '(spec)\n', (434, 440), False, 'import importlib\n'), ((456, 478), 'importlib.reload', 'importlib.reload', (['phys'], {}), '(phys)\n', (472, 478), False, 'import importlib\n'), ((494, 517), 'importlib.reload', 'importlib.reload', (['nessy'], {}), '(nessy)\n', (510, 517), False, 'import importlib\n'), ((533, 557), 'importlib.reload', 'importlib.reload', (['auxsys'], {}), '(auxsys)\n', (549, 557), False, 'import importlib\n'), ((573, 597), 'importlib.reload', 'importlib.reload', (['auxplt'], {}), '(auxplt)\n', (589, 597), False, 'import importlib\n'), ((1168, 1233), 'nessy.read_spec', 'nessy.read_spec', (["(prefix0 + 'VAR/Q_kur_old')"], {'wvl1': '(1005)', 'wvl2': '(16000)'}), "(prefix0 + 'VAR/Q_kur_old', wvl1=1005, wvl2=16000)\n", (1183, 1233), False, 'import nessy\n'), ((1421, 1486), 'nessy.read_spec', 'nessy.read_spec', (["(prefix1 + 'VAR/Q_kur_old')"], {'wvl1': '(1005)', 'wvl2': '(16000)'}), "(prefix1 + 'VAR/Q_kur_old', wvl1=1005, wvl2=16000)\n", (1436, 1486), False, 'import nessy\n'), ((1794, 1829), 'spec.mean_within_delta', 'spec.mean_within_delta', (['wn', 'Q4h', '(10)'], {}), '(wn, Q4h, 10)\n', (1816, 1829), False, 'import spec\n'), ((1888, 1923), 'spec.mean_within_delta', 'spec.mean_within_delta', (['wn', 'Q5h', '(10)'], {}), '(wn, Q5h, 10)\n', (1910, 1923), False, 'import spec\n'), ((1972, 2042), 'numpy.savez', 'np.savez', (["(paths.npz + 'spec_var_whi_fallte_C_new')"], {'w': 'wns', 'q4': 'Q4', 'q5': 'Q5'}), "(paths.npz + 'spec_var_whi_fallte_C_new', w=wns, q4=Q4, q5=Q5)\n", (1980, 2042), True, 'import numpy as np\n'), ((2478, 2530), 'numpy.load', 'np.load', (["(paths.npz + 'spec_var_whi_fallte_C_new.npz')"], {}), "(paths.npz + 'spec_var_whi_fallte_C_new.npz')\n", (2485, 2530), True, 'import numpy as np\n'), ((2694, 2710), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2703, 2710), True, 'import matplotlib.pyplot as plt\n'), ((2792, 2842), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(1)', 'figsize': '(6.0, 8.0)'}), '(nrows=2, ncols=1, figsize=(6.0, 8.0))\n', (2804, 2842), True, 'import matplotlib.pyplot as plt\n'), ((2929, 2952), 'auxplt.figpar', 'auxplt.figpar', (['(3)', '(3)', '(20)'], {}), '(3, 3, 20)\n', (2942, 2952), False, 'import auxplt\n'), ((2974, 3006), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.15)'}), '(hspace=0.15)\n', (2993, 3006), True, 'import matplotlib.pyplot as plt\n'), ((5057, 5088), 'auxplt.savepdf', 'auxplt.savepdf', (['"""var/Q_kur_old"""'], {}), "('var/Q_kur_old')\n", (5071, 5088), False, 'import auxplt\n'), ((336, 362), 'sys.path.append', 'sys.path.append', (['"""../aux/"""'], {}), "('../aux/')\n", (351, 362), False, 'import sys\n'), ((4215, 4235), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(300)'], {}), '(300)\n', (4230, 4235), False, 'from matplotlib.ticker import MultipleLocator\n'), ((4320, 4339), 'matplotlib.ticker.AutoMinorLocator', 'AutoMinorLocator', (['(5)'], {}), '(5)\n', (4336, 4339), False, 'from matplotlib.ticker import AutoMinorLocator\n'), ((4457, 4477), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(300)'], {}), '(300)\n', (4472, 4477), False, 'from matplotlib.ticker import MultipleLocator\n'), ((4570, 4589), 'matplotlib.ticker.AutoMinorLocator', 'AutoMinorLocator', (['(5)'], {}), '(5)\n', (4586, 4589), False, 'from matplotlib.ticker import AutoMinorLocator\n')]
from sciope.utilities.epsilonselectors.epsilon_selector import * import numpy as np class RelativeEpsilonSelector(EpsilonSelector): """ Creates an epsilon selector based on a relative percentile. For each round, it computes the new epsilon as the epsilon-percentile of the last set of ABC distances. """ def __init__(self, epsilon_percentile, max_rounds = None): """ Parameters ---------- epsilon_percentile : float [0, 100] The percentile of the distances to use in each round. Specified as a percent between 0 and 100. max_rounds : int The maximum number of rounds before stopping. If None, doesn't end. """ self.epsilon_percentile = epsilon_percentile self.max_rounds = max_rounds def get_initial_epsilon(self): """ Gets the initial epsilon, interpreted as a percentile Returns ------- epsilon : float The epsilon percentile, because there is no initial epsilon without history percentile : bool Whether the epsilon should be interpreted as a percentile has_more : bool Whether there are more epsilons after this one """ return self.epsilon_percentile, True, self.max_rounds == 0 def get_epsilon(self, round, abc_history): """Returns the new epsilon based on the n-th round. Parameters ---------- round : int the n-th round of the sequence abc_history : type A list of dictionaries with keys `accepted_samples` and `distances` representing the history of all ABC runs up to this point. Returns ------- epsilon : float The epsilon value for ABC-SMC percentile : bool Whether the epsilon should be interpreted as a percentile terminate : bool Whether to stop after this epsilon """ if round > len(abc_history): t = np.percentile(abc_history[-1]['distances'], self.epsilon_percentile) else: t = np.percentile(abc_history[round - 1]['distances'], self.epsilon_percentile) return t, False, self.max_rounds and round + 1 == self.max_rounds
[ "numpy.percentile" ]
[((2056, 2124), 'numpy.percentile', 'np.percentile', (["abc_history[-1]['distances']", 'self.epsilon_percentile'], {}), "(abc_history[-1]['distances'], self.epsilon_percentile)\n", (2069, 2124), True, 'import numpy as np\n'), ((2155, 2230), 'numpy.percentile', 'np.percentile', (["abc_history[round - 1]['distances']", 'self.epsilon_percentile'], {}), "(abc_history[round - 1]['distances'], self.epsilon_percentile)\n", (2168, 2230), True, 'import numpy as np\n')]
# prepare_data_DCE.py # init # from scipy import io as sio import matplotlib import numpy as np import os,sys import matplotlib.pyplot as plt from scipy import io as sio import h5py from PIL import Image # dir # dir_data_DCE = '/Users/enhao/Documents/Research/MRI/GANCS/data_MRI/processed_data' # dir_mask_DCE = '/Users/enhao/Documents/Research/MRI/GANCS/data_MRI/sampling_pattern/' # dir_image_DCE='/home/enhaog/GANCS/srez/dataset_MRI/abdominal_DCE' dir_data_DCE = '/mnt/raid2/morteza/abdominal_DCE_processed/processed_data' dir_mask_DCE = '/mnt/raid2/morteza/abdominal_DCE_processed/sampling_pattern' dir_image_DCE='/home/enhaog/GANCS/srez/dataset_MRI/abdominal_DCE' # import data list_filename_data = [x for x in os.listdir(dir_data_DCE) if x.endswith('.mat')] print(list_filename_data) # generate slice images try: os.mkdir(dir_image_DCE) print('directory {0} created'.format(dir_image_DCE)) except: print('directory {0} exists'.format(dir_image_DCE)) # generate images indexes_slice=xrange(0,151) for filename_data in list_filename_data: # load data filepath_data = os.path.join(dir_data_DCE, filename_data) content_mat = sio.loadmat(filepath_data) key_mat=[x for x in content_mat.keys() if not x.startswith('_')] try: data=content_mat[key_mat[0]] assert(np.ndim(data)==3) except: continue print('image load from {0}, size {1}'.format(filename_data, data.shape)) # scale data=data/(np.max(data[:])+1e-6) # each slice num_slice=data.shape[0] indexes_slice=xrange(num_slice) for index_slice in indexes_slice: data_slice = np.squeeze(data[index_slice,:,:]) # save to image obj = Image.fromarray((data_slice*255).astype('uint8')) filename_image = '{0}_slice{1:03d}.jpg'.format(filename_data.split('.mat')[0],index_slice) obj.save(os.path.join(dir_image_DCE, filename_image)) if index_slice%100 == 0: print('save to {}'.format(filename_image)) print('DCE data generated to images to folder:{0}'.format( dir_image_DCE))
[ "os.mkdir", "scipy.io.loadmat", "numpy.ndim", "numpy.max", "numpy.squeeze", "os.path.join", "os.listdir" ]
[((826, 849), 'os.mkdir', 'os.mkdir', (['dir_image_DCE'], {}), '(dir_image_DCE)\n', (834, 849), False, 'import os, sys\n'), ((1095, 1136), 'os.path.join', 'os.path.join', (['dir_data_DCE', 'filename_data'], {}), '(dir_data_DCE, filename_data)\n', (1107, 1136), False, 'import os, sys\n'), ((1155, 1181), 'scipy.io.loadmat', 'sio.loadmat', (['filepath_data'], {}), '(filepath_data)\n', (1166, 1181), True, 'from scipy import io as sio\n'), ((718, 742), 'os.listdir', 'os.listdir', (['dir_data_DCE'], {}), '(dir_data_DCE)\n', (728, 742), False, 'import os, sys\n'), ((1629, 1664), 'numpy.squeeze', 'np.squeeze', (['data[index_slice, :, :]'], {}), '(data[index_slice, :, :])\n', (1639, 1664), True, 'import numpy as np\n'), ((1312, 1325), 'numpy.ndim', 'np.ndim', (['data'], {}), '(data)\n', (1319, 1325), True, 'import numpy as np\n'), ((1463, 1478), 'numpy.max', 'np.max', (['data[:]'], {}), '(data[:])\n', (1469, 1478), True, 'import numpy as np\n'), ((1867, 1910), 'os.path.join', 'os.path.join', (['dir_image_DCE', 'filename_image'], {}), '(dir_image_DCE, filename_image)\n', (1879, 1910), False, 'import os, sys\n')]
#%% import tensorflow as tf import numpy as np from data_prepare import * from Network_structure import * from loss_function import * from train_method import * from save_method import * import os #sys.path.append('../') from Novel_CNN import * # EEGdenoiseNet V2 # Author: <NAME> # Here is the main part of the denoising neurl network, We can adjust all the parameter in the user-defined area. #####################################################自定义 user-defined ######################################################## #%% epochs = 1#50 # training epoch batch_size = 40 # training batch size combin_num = 10 # combin EEG and noise ? times denoise_network = 'Novel_CNN' # fcNN & Simple_CNN & Complex_CNN & RNN_lstm & Novel_CNN noise_type = 'EMG' result_location = r'E:/GoogleDriveBB/Program/EEGdenoiseNet/saved models/' # Where to export network results ############ change it to your own location ######### foldername = '50_40_10_SCNN_EMG' # the name of the target folder (should be change when we want to train a new network) os.environ['CUDA_VISIBLE_DEVICES']='0' save_train = True save_vali = True save_test = True ################################################## optimizer adjust parameter #################################################### rmsp=tf.optimizers.RMSprop(lr=0.00005, rho=0.9) adam=tf.optimizers.Adam(lr=0.00005, beta_1=0.5, beta_2=0.9, epsilon=1e-08) sgd=tf.optimizers.SGD(lr=0.0002, momentum=0.9, decay=0.0, nesterov=False) optimizer = rmsp if noise_type == 'EOG': datanum = 512 elif noise_type == 'EMG': datanum = 1024 #%% # We have reserved an example of importing an existing network ''' path = os.path.join(result_location, foldername, "denoised_model") denoiseNN = tf.keras.models.load_model(path) ''' #%% #################################################### 数据输入 Import data ##################################################### file_location = 'E:/GoogleDriveBB/Program/EEGdenoiseNet/data/' ############ change it to your own location ######### if noise_type == 'EOG': EEG_all = np.load( file_location + 'EEG_all_epochs.npy') noise_all = np.load( file_location + 'EOG_all_epochs.npy') elif noise_type == 'EMG': EEG_all = np.load( file_location + 'EEG_all_epochs_512hz.npy') noise_all = np.load( file_location + 'EMG_all_epochs_512hz.npy') #%% ############################################################# Running ############################################################# #for i in range(10): i = 1 # We run each NN for 10 times to increase the statistical power of our results noiseEEG_train, EEG_train, noiseEEG_val, EEG_val, noiseEEG_test, EEG_test, test_std_VALUE = prepare_data(EEG_all = EEG_all, noise_all = noise_all, combin_num = 10, train_per = 0.8, noise_type = noise_type) #%% if denoise_network == 'fcNN': model = fcNN(datanum) elif denoise_network == 'Simple_CNN': model = simple_CNN(datanum) elif denoise_network == 'Complex_CNN': model = Complex_CNN(datanum) elif denoise_network == 'RNN_lstm': model = RNN_lstm(datanum) elif denoise_network == 'Novel_CNN': model = Novel_CNN(datanum) else: print('NN name arror') saved_model, history = train(model, noiseEEG_train, EEG_train, noiseEEG_val, EEG_val, epochs, batch_size,optimizer, denoise_network, result_location, foldername , train_num = str(i)) #%% #denoised_test, test_mse = test_step(saved_model, noiseEEG_test, EEG_test) #%% # save signal save_eeg(saved_model, result_location, foldername, save_train, save_vali, save_test, noiseEEG_train, EEG_train, noiseEEG_val, EEG_val, noiseEEG_test, EEG_test, str(i), denoise_network, datanum) if not os.path.exists(result_location +'/'+ foldername + '/' + str(i) + '/' +'nn_output'): os.makedirs(result_location +'/'+ foldername + '/' + str(i) + '/'+ 'nn_output' ) np.save(result_location +'/'+ foldername + '/'+ str(i) +'/'+ "nn_output" + '/'+ 'loss_history.npy', history) #%% #save model if saved_model is not None: path = os.path.join(result_location, foldername, str(i), "denoise_model") tf.keras.models.save_model(saved_model, path) else: print("Model not saved, since None.")
[ "numpy.load", "tensorflow.optimizers.RMSprop", "tensorflow.optimizers.Adam", "tensorflow.keras.models.save_model", "tensorflow.optimizers.SGD" ]
[((1296, 1336), 'tensorflow.optimizers.RMSprop', 'tf.optimizers.RMSprop', ([], {'lr': '(5e-05)', 'rho': '(0.9)'}), '(lr=5e-05, rho=0.9)\n', (1317, 1336), True, 'import tensorflow as tf\n'), ((1344, 1411), 'tensorflow.optimizers.Adam', 'tf.optimizers.Adam', ([], {'lr': '(5e-05)', 'beta_1': '(0.5)', 'beta_2': '(0.9)', 'epsilon': '(1e-08)'}), '(lr=5e-05, beta_1=0.5, beta_2=0.9, epsilon=1e-08)\n', (1362, 1411), True, 'import tensorflow as tf\n'), ((1418, 1487), 'tensorflow.optimizers.SGD', 'tf.optimizers.SGD', ([], {'lr': '(0.0002)', 'momentum': '(0.9)', 'decay': '(0.0)', 'nesterov': '(False)'}), '(lr=0.0002, momentum=0.9, decay=0.0, nesterov=False)\n', (1435, 1487), True, 'import tensorflow as tf\n'), ((2080, 2125), 'numpy.load', 'np.load', (["(file_location + 'EEG_all_epochs.npy')"], {}), "(file_location + 'EEG_all_epochs.npy')\n", (2087, 2125), True, 'import numpy as np\n'), ((2171, 2216), 'numpy.load', 'np.load', (["(file_location + 'EOG_all_epochs.npy')"], {}), "(file_location + 'EOG_all_epochs.npy')\n", (2178, 2216), True, 'import numpy as np\n'), ((4211, 4256), 'tensorflow.keras.models.save_model', 'tf.keras.models.save_model', (['saved_model', 'path'], {}), '(saved_model, path)\n', (4237, 4256), True, 'import tensorflow as tf\n'), ((2257, 2308), 'numpy.load', 'np.load', (["(file_location + 'EEG_all_epochs_512hz.npy')"], {}), "(file_location + 'EEG_all_epochs_512hz.npy')\n", (2264, 2308), True, 'import numpy as np\n'), ((2354, 2405), 'numpy.load', 'np.load', (["(file_location + 'EMG_all_epochs_512hz.npy')"], {}), "(file_location + 'EMG_all_epochs_512hz.npy')\n", (2361, 2405), True, 'import numpy as np\n')]
import numpy as np arr = np.arange(0, 11) print(arr[8]) print(arr[1:5]) print(arr[0:5]) print(arr[:6]) print(arr[5:]) arr[0:5] = 100 print(arr) arr = np.arange(0, 11) slice_of_arr = arr[0:6] print(slice_of_arr) print(slice_of_arr[:]) slice_of_arr[:] = 99 print(slice_of_arr) print(arr) arr_copy = arr.copy() print(arr_copy) arr_copy[:] = 100 print(arr_copy) print(arr)
[ "numpy.arange" ]
[((26, 42), 'numpy.arange', 'np.arange', (['(0)', '(11)'], {}), '(0, 11)\n', (35, 42), True, 'import numpy as np\n'), ((152, 168), 'numpy.arange', 'np.arange', (['(0)', '(11)'], {}), '(0, 11)\n', (161, 168), True, 'import numpy as np\n')]
from __future__ import annotations import copy from typing import Tuple, Union, Optional, Any, TYPE_CHECKING import numpy as np import scipy.sparse as sci_sparse from pyNastran.dev.solver.stiffness.shells import build_kbb_cquad4, build_kbb_cquad8 from .utils import lambda1d, DOF_MAP #from pyNastran.bdf.cards.elements.bars import get_bar_vector, get_bar_yz_transform if TYPE_CHECKING: # pragma: no cover from pyNastran.nptyping_interface import NDArrayNNfloat from pyNastran.bdf.bdf import ( BDF, CELAS1, CELAS2, CELAS3, CELAS4, CBAR, PBAR, PBARL, PBEAM, PBEAML, # , CBEAM MAT1, ) def build_Kgg(model: BDF, dof_map: DOF_MAP, ndof: int, ngrid: int, ndof_per_grid: int, idtype: str='int32', fdtype: str='float32') -> Tuple[NDArrayNNfloat, Any]: """[K] = d{P}/dx""" model.log.debug(f'starting build_Kgg') Kbb = sci_sparse.dok_matrix((ndof, ndof), dtype=fdtype) #print(dof_map) #_get_loadid_ndof(model, subcase_id) out = model.get_xyz_in_coord_array(cid=0, fdtype=fdtype, idtype=idtype) nid_cp_cd, xyz_cid0, xyz_cp, unused_icd_transform, unused_icp_transform = out all_nids = nid_cp_cd[:, 0] del xyz_cp, nid_cp_cd nelements = 0 # TODO: I think these need to be in the global frame nelements += _build_kbb_celas1(model, Kbb, dof_map) nelements += _build_kbb_celas2(model, Kbb, dof_map) nelements += _build_kbb_celas3(model, Kbb, dof_map) nelements += _build_kbb_celas4(model, Kbb, dof_map) nelements += _build_kbb_conrod(model, Kbb, dof_map) nelements += _build_kbb_crod(model, Kbb, dof_map) nelements += _build_kbb_ctube(model, Kbb, dof_map) nelements += _build_kbb_cbar(model, Kbb, dof_map) nelements += _build_kbb_cbeam(model, Kbb, dof_map, all_nids, xyz_cid0, idtype='int32', fdtype='float64') nelements += build_kbb_cquad4(model, Kbb, dof_map, all_nids, xyz_cid0, idtype='int32', fdtype='float64') nelements += build_kbb_cquad8(model, Kbb, dof_map, all_nids, xyz_cid0, idtype='int32', fdtype='float64') assert nelements > 0, nelements Kbb2 = Kbb.tocsc() #Kgg = Kbb_to_Kgg(model, Kbb, ngrid, ndof_per_grid, inplace=False) Kgg = Kbb_to_Kgg(model, Kbb2, ngrid, ndof_per_grid) model.log.debug(f'end of build_Kgg') return Kgg def _build_kbb_celas1(model: BDF, Kbb, dof_map: DOF_MAP) -> None: """fill the CELAS1 Kbb matrix""" eids = model._type_to_id_map['CELAS1'] for eid in eids: elem = model.elements[eid] ki = elem.K() #print(elem, ki) #print(elem.get_stats()) _build_kbbi_celas12(Kbb, dof_map, elem, ki) return len(eids) def _build_kbb_celas2(model: BDF, Kbb, dof_map: DOF_MAP) -> int: """fill the CELAS2 Kbb matrix""" eids = model._type_to_id_map['CELAS2'] #celas3s = model._type_to_id_map['CELAS3'] #celas4s = model._type_to_id_map['CELAS4'] for eid in eids: elem = model.elements[eid] ki = elem.K() #print(elem, ki) #print(elem.get_stats()) _build_kbbi_celas12(Kbb, dof_map, elem, ki) return len(eids) def _build_kbb_celas3(model: BDF, Kbb, dof_map: DOF_MAP) -> None: """fill the CELAS3 Kbb matrix""" eids = model._type_to_id_map['CELAS3'] for eid in eids: elem = model.elements[eid] ki = elem.K() #print(elem, ki) #print(elem.get_stats()) _build_kbbi_celas34(Kbb, dof_map, elem, ki) return len(eids) def _build_kbb_celas4(model: BDF, Kbb, dof_map: DOF_MAP) -> None: """fill the CELAS4 Kbb matrix""" eids = model._type_to_id_map['CELAS4'] for eid in eids: elem = model.elements[eid] ki = elem.K() #print(elem, ki) #print(elem.get_stats()) _build_kbbi_celas34(Kbb, dof_map, elem, ki) return len(eids) def _build_kbbi_celas12(Kbb, dof_map: DOF_MAP, elem: Union[CELAS1, CELAS2], ki: float) -> None: """fill the CELASx Kbb matrix""" nid1, nid2 = elem.nodes c1, c2 = elem.c1, elem.c2 i = dof_map[(nid1, c1)] j = dof_map[(nid2, c2)] k = ki * np.array([[1, -1,], [-1, 1]]) ibe = [ (i, 0), (j, 1), ] for ib1, ie1 in ibe: for ib2, ie2 in ibe: Kbb[ib1, ib2] += k[ie1, ie2] #Kbb[j, i] += ki #Kbb[i, j] += ki #del i, j, ki, nid1, nid2, c1, c2 def _build_kbbi_celas34(Kbb, dof_map: DOF_MAP, elem: Union[CELAS3, CELAS4], ki: float) -> None: """fill the CELASx Kbb matrix""" nid1, nid2 = elem.nodes #print(dof_map) i = dof_map[(nid1, 0)] j = dof_map[(nid2, 0)] k = ki * np.array([[1, -1,], [-1, 1]]) ibe = [ (i, 0), (j, 1), ] for ib1, ie1 in ibe: for ib2, ie2 in ibe: Kbb[ib1, ib2] += k[ie1, ie2] #Kbb[j, i] += ki #Kbb[i, j] += ki #del i, j, ki, nid1, nid2, c1, c2 def _build_kbb_cbar(model, Kbb, dof_map: DOF_MAP, fdtype: str='float64') -> int: """fill the CBAR Kbb matrix using an Euler-Bernoulli beam""" eids = model._type_to_id_map['CBAR'] nelements = len(eids) if nelements == 0: return nelements for eid in eids: elem = model.elements[eid] # type: CBAR nid1, nid2 = elem.nodes is_passed, K = ke_cbar(model, elem, fdtype=fdtype) assert is_passed i1 = dof_map[(nid1, 1)] i2 = dof_map[(nid2, 1)] n_ijv = [ i1, i1 + 1, i1 + 2, i1 + 3, i1 + 4, i1 + 5, i2, i2 + 1, i2 + 2, i2 + 3, i2 + 4, i2 + 5, ] for i, i1 in enumerate(n_ijv): for j, i2 in enumerate(n_ijv): ki = K[i, j] if abs(ki) > 0.: Kbb[i1, i2] += ki return nelements def ke_cbar(model: BDF, elem: CBAR, fdtype: str='float64'): """get the elemental stiffness matrix in the basic frame""" pid_ref = elem.pid_ref mat = pid_ref.mid_ref #is_passed, (wa, wb, ihat, jhat, khat) = elem.get_axes(model) #T = np.vstack([ihat, jhat, khat]) #z = np.zeros((3, 3), dtype='float64') prop = elem.pid_ref mat = prop.mid_ref I1 = prop.I11() I2 = prop.I22() unused_I12 = prop.I12() pa = elem.pa pb = elem.pb #J = prop.J() #E = mat.E() #G = mat.G() z = np.zeros((3, 3), dtype='float64') T = z #unused_Teb = np.block([ #[T, z], #[z, T], #]) is_failed, (wa, wb, ihat, jhat, khat) = elem.get_axes(model) assert is_failed is False #print(wa, wb) xyz1 = elem.nodes_ref[0].get_position() + wa xyz2 = elem.nodes_ref[1].get_position() + wb dxyz = xyz2 - xyz1 L = np.linalg.norm(dxyz) pid_ref = elem.pid_ref mat = pid_ref.mid_ref T = np.vstack([ihat, jhat, khat]) z = np.zeros((3, 3), dtype=fdtype) Teb = np.block([ [T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T], ]) k1 = pid_ref.k1 k2 = pid_ref.k2 Ke = _beami_stiffness(pid_ref, mat, L, I1, I2, k1=k1, k2=k2, pa=pa, pb=pb) K = Teb.T @ Ke @ Teb is_passed = not is_failed return is_passed, K def _build_kbb_crod(model: BDF, Kbb, dof_map: DOF_MAP) -> None: """fill the CROD Kbb matrix""" eids = model._type_to_id_map['CROD'] for eid in eids: elem = model.elements[eid] pid_ref = elem.pid_ref mat = pid_ref.mid_ref _build_kbbi_conrod_crod(Kbb, dof_map, elem, mat) return len(eids) def _build_kbb_ctube(model: BDF, Kbb, dof_map: DOF_MAP) -> None: """fill the CTUBE Kbb matrix""" ctubes = model._type_to_id_map['CTUBE'] for eid in ctubes: elem = model.elements[eid] pid_ref = elem.pid_ref mat = pid_ref.mid_ref _build_kbbi_conrod_crod(Kbb, dof_map, elem, mat) return len(ctubes) def _build_kbb_conrod(model: BDF, Kbb, dof_map: DOF_MAP) -> int: """fill the CONROD Kbb matrix""" eids = model._type_to_id_map['CONROD'] for eid in eids: elem = model.elements[eid] mat = elem.mid_ref _build_kbbi_conrod_crod(Kbb, dof_map, elem, mat) return len(eids) def _build_kbbi_conrod_crod(Kbb, dof_map: DOF_MAP, elem, mat, fdtype='float64') -> None: """fill the ith rod Kbb matrix""" nid1, nid2 = elem.nodes #mat = elem.mid_ref xyz1 = elem.nodes_ref[0].get_position() xyz2 = elem.nodes_ref[1].get_position() dxyz12 = xyz1 - xyz2 L = np.linalg.norm(dxyz12) E = mat.E G = mat.G() J = elem.J() A = elem.Area() #print(f'A = {A}') E = elem.E() #L = elem.Length() k_axial = A * E / L k_torsion = G * J / L assert isinstance(k_axial, float), k_axial assert isinstance(k_torsion, float), k_torsion #Kbb[i, i] += ki[0, 0] #Kbb[i, j] += ki[0, 1] #Kbb[j, i] = ki[1, 0] #Kbb[j, j] = ki[1, 1] k = np.array([[1., -1.], [-1., 1.]]) # 1D rod Lambda = lambda1d(dxyz12, debug=False) K = Lambda.T @ k @ Lambda #i11 = dof_map[(n1, 1)] #i12 = dof_map[(n1, 2)] #i21 = dof_map[(n2, 1)] #i22 = dof_map[(n2, 2)] nki, nkj = K.shape K2 = np.zeros((nki*2, nkj*2), dtype=fdtype) ni1 = dof_map[(nid1, 1)] nj1 = dof_map[(nid2, 1)] i1 = 0 i2 = 3 # dof_map[(n1, 2)] if k_torsion == 0.0: # axial; 2D or 3D K2 = K * k_axial n_ijv = [ # axial ni1, ni1 + 1, ni1 + 2, # node 1 nj1, nj1 + 1, nj1 + 2, # node 2 ] dofs = np.array([ i1, i1+1, i1+2, i2, i2+1, i2+2, ], dtype='int32') elif k_axial == 0.0: # torsion; assume 3D K2 = K * k_torsion n_ijv = [ # torsion ni1 + 3, ni1 + 4, ni1 + 5, # node 1 nj1 + 3, nj1 + 4, nj1 + 5, # node 2 ] dofs = np.array([ i1, i1+1, i1+2, i2, i2+1, i2+2, ], dtype='int32') else: # axial + torsion; assume 3D # u1fx, u1fy, u1fz, u2fx, u2fy, u2fz K2[:nki, :nki] = K * k_axial # u1mx, u1my, u1mz, u2mx, u2my, u2mz K2[nki:, nki:] = K * k_torsion dofs = np.array([ i1, i1+1, i1+2, i2, i2+1, i2+2, i1+3, i1+4, i1+5, i2+3, i2+4, i2+5, ], dtype='int32') n_ijv = [ # axial ni1, ni1 + 1, ni1 + 2, # node 1 nj1, nj1 + 1, nj1 + 2, # node 2 # torsion ni1 + 3, ni1 + 4, ni1 + 5, # node 1 nj1 + 3, nj1 + 4, nj1 + 5, # node 2 ] for dof1, i1 in zip(dofs, n_ijv): for dof2, i2 in zip(dofs, n_ijv): ki = K2[dof1, dof2] if abs(ki) > 0.: #print(nij1, nij2, f'({i1}, {i2});', (dof1, dof2), ki) Kbb[i1, i2] += ki #print(K2) #print(Kbb) return def _build_kbb_cbeam(model: BDF, Kbb, dof_map: DOF_MAP, all_nids, xyz_cid0, idtype='int32', fdtype='float64') -> int: """TODO: Timoshenko beam, warping, I12""" str(all_nids) str(xyz_cid0) eids = np.array(model._type_to_id_map['CBEAM'], dtype=idtype) nelements = len(eids) if nelements == 0: return nelements for eid in eids: elem = model.elements[eid] nid1, nid2 = elem.nodes xyz1 = elem.nodes_ref[0].get_position() xyz2 = elem.nodes_ref[1].get_position() dxyz = xyz2 - xyz1 L = np.linalg.norm(dxyz) pid_ref = elem.pid_ref mat = pid_ref.mid_ref is_failed, (wa, wb, ihat, jhat, khat) = elem.get_axes(model) #print(wa, wb, ihat, jhat, khat) assert is_failed is False T = np.vstack([ihat, jhat, khat]) z = np.zeros((3, 3), dtype=fdtype) Teb = np.block([ [T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T], ]) Iy = pid_ref.I11() Iz = pid_ref.I22() k1 = pid_ref.k1 k2 = pid_ref.k2 pa = elem.pa pb = elem.pb Ke = _beami_stiffness(pid_ref, mat, L, Iy, Iz, pa, pb, k1=k1, k2=k2) K = Teb.T @ Ke @ Teb i1 = dof_map[(nid1, 1)] j1 = dof_map[(nid2, 1)] n_ijv = [ i1, i1 + 1, i1 + 2, i1 + 3, i1 + 4, i1 + 5, # node 1 j1, j1 + 1, j1 + 2, j1 + 3, j1 + 4, j1 + 5, # node 2 ] for i, i1 in enumerate(n_ijv): for j, i2 in enumerate(n_ijv): ki = K[i, j] if abs(ki) > 0.: Kbb[i1, i2] += ki return nelements def _beami_stiffness(prop: Union[PBAR, PBARL, PBEAM, PBEAML], mat: MAT1, L: float, Iy: float, Iz: float, pa: int, pb: int, k1: Optional[float]=None, k2: Optional[float]=None): """gets the ith Euler-Bernoulli beam stiffness""" E = mat.E() G = mat.G() A = prop.Area() J = prop.J() kaxial = E * A / L ktorsion = G * J / L L2 = L * L if k1 is not None: phiy = 12. * E * Iy / (k1 * G * A * L2) if k2 is not None: phiz = 12. * E * Iy / (k2 * G * A * L2) phiy = 1.0 phiz = 1.0 ky = E * Iy / (L * phiy) kz = E * Iz / (L * phiz) K = np.zeros((12, 12), dtype='float64') # axial K[0, 0] = K[6, 6] = kaxial K[6, 0] = K[0, 6] = -kaxial # torsion K[3, 3] = K[9, 9] = ktorsion K[9, 3] = K[3, 9] = -ktorsion #Fx - 0, 6 #Fy - 1, 7** #Fz - 2, 8 #Mx - 3, 9 #My - 4, 10 #Mz - 5, 11** # bending z (Fy/1/7, Mz/5/11) # 1 5 7 11 # 1 [12 & 6L & -12 & 6L # 5 [6L & 4L^2 & -6L & 2L^2 # 7 [-12 &-6L & 12 & -6L # 11 [6L & 2L^2 & -6L & 4L^2 K[1, 1] = K[7, 7] = 12. * kz K[1, 7] = K[1, 7] = -12. * kz K[1, 5] = K[5, 1] = K[11, 1] = K[1, 11] = 6. * L * kz K[5, 7] = K[7, 5] = K[7, 11] = K[11, 7] = -6. * L * kz K[5, 11] = K[11, 5] = 2. * L2 * kz * (2 - phiz) K[5, 5] = K[11, 11] = 4. * L2 * kz * (4 + phiz) #Fx - 0, 6 #Fy - 1, 7 #Fz - 2, 8** #Mx - 3, 9 #My - 4, 10** #Mz - 5, 11 # bending y (Fz/2/8, My/4/10) # 2 4 8 10 # 2 [12 & 6L & -12 & 6L # 4 [6L & 4L^2 & -6L & 2L^2 # 8 [-12 &-6L & 12 & -6L # 10 [6L & 2L^2 & -6L & 4L^2 K[2, 2] = K[8, 8] = 12. * ky K[2, 8] = K[2, 8] = -12. * ky K[2, 4] = K[4, 2] = K[10, 2] = K[2, 10] = 6. * L * ky K[4, 8] = K[8, 4] = K[8, 10] = K[10, 8] = -6. * L * ky K[4, 10] = K[10, 4] = 2. * L * L * ky * (2. - phiy) K[4, 4] = K[10, 10] = 4. * L * L * ky * (4. + phiy) if pa != 0: assert pa > 0 for pas in str(pa): # 123456 pai = int(pas) - 1 # 012345 (0-5) K[pai, :] = 0 K[:, pai] = 0 if pb != 0: assert pb > 0 for pbs in str(pb): # 123456 pbi = int(pbs) + 5 # (6 - 11) K[pbi, :] = 0 K[:, pbi] = 0 return K def Kbb_to_Kgg(model: BDF, Kbb: NDArrayNNfloat, ngrid: int, ndof_per_grid: int, inplace=True) -> NDArrayNNfloat: """does an in-place transformation""" assert isinstance(Kbb, (np.ndarray, sci_sparse.csc.csc_matrix)), type(Kbb) #assert isinstance(Kbb, (np.ndarray, sci_sparse.csc.csc_matrix, sci_sparse.dok.dok_matrix)), type(Kbb) if not isinstance(Kbb, np.ndarray): Kbb = Kbb.tolil() ndof = Kbb.shape[0] assert ndof > 0, f'ngrid={ngrid} card_count={model.card_count}' nids = model._type_to_id_map['GRID'] Kgg = Kbb if not inplace: Kgg = copy.deepcopy(Kgg) for i, nid in enumerate(nids): node = model.nodes[nid] if node.cd: model.log.debug(f'node {nid} has a CD={node.cd}') cd_ref = node.cd_ref T = cd_ref.beta_n(n=2) i1 = i * ndof_per_grid i2 = (i+1) * ndof_per_grid Ki = Kbb[i1:i2, i1:i2] Kgg[i1:i2, i1:i2] = T.T @ Ki @ T return Kgg
[ "pyNastran.dev.solver.stiffness.shells.build_kbb_cquad8", "copy.deepcopy", "pyNastran.dev.solver.stiffness.shells.build_kbb_cquad4", "numpy.zeros", "numpy.linalg.norm", "numpy.array", "scipy.sparse.dok_matrix", "numpy.vstack", "numpy.block" ]
[((926, 975), 'scipy.sparse.dok_matrix', 'sci_sparse.dok_matrix', (['(ndof, ndof)'], {'dtype': 'fdtype'}), '((ndof, ndof), dtype=fdtype)\n', (947, 975), True, 'import scipy.sparse as sci_sparse\n'), ((1933, 2028), 'pyNastran.dev.solver.stiffness.shells.build_kbb_cquad4', 'build_kbb_cquad4', (['model', 'Kbb', 'dof_map', 'all_nids', 'xyz_cid0'], {'idtype': '"""int32"""', 'fdtype': '"""float64"""'}), "(model, Kbb, dof_map, all_nids, xyz_cid0, idtype='int32',\n fdtype='float64')\n", (1949, 2028), False, 'from pyNastran.dev.solver.stiffness.shells import build_kbb_cquad4, build_kbb_cquad8\n'), ((2076, 2171), 'pyNastran.dev.solver.stiffness.shells.build_kbb_cquad8', 'build_kbb_cquad8', (['model', 'Kbb', 'dof_map', 'all_nids', 'xyz_cid0'], {'idtype': '"""int32"""', 'fdtype': '"""float64"""'}), "(model, Kbb, dof_map, all_nids, xyz_cid0, idtype='int32',\n fdtype='float64')\n", (2092, 2171), False, 'from pyNastran.dev.solver.stiffness.shells import build_kbb_cquad4, build_kbb_cquad8\n'), ((6520, 6553), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': '"""float64"""'}), "((3, 3), dtype='float64')\n", (6528, 6553), True, 'import numpy as np\n'), ((6878, 6898), 'numpy.linalg.norm', 'np.linalg.norm', (['dxyz'], {}), '(dxyz)\n', (6892, 6898), True, 'import numpy as np\n'), ((6960, 6989), 'numpy.vstack', 'np.vstack', (['[ihat, jhat, khat]'], {}), '([ihat, jhat, khat])\n', (6969, 6989), True, 'import numpy as np\n'), ((6998, 7028), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'fdtype'}), '((3, 3), dtype=fdtype)\n', (7006, 7028), True, 'import numpy as np\n'), ((7039, 7105), 'numpy.block', 'np.block', (['[[T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T]]'], {}), '([[T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T]])\n', (7047, 7105), True, 'import numpy as np\n'), ((8632, 8654), 'numpy.linalg.norm', 'np.linalg.norm', (['dxyz12'], {}), '(dxyz12)\n', (8646, 8654), True, 'import numpy as np\n'), ((9048, 9084), 'numpy.array', 'np.array', (['[[1.0, -1.0], [-1.0, 1.0]]'], {}), '([[1.0, -1.0], [-1.0, 1.0]])\n', (9056, 9084), True, 'import numpy as np\n'), ((9328, 9370), 'numpy.zeros', 'np.zeros', (['(nki * 2, nkj * 2)'], {'dtype': 'fdtype'}), '((nki * 2, nkj * 2), dtype=fdtype)\n', (9336, 9370), True, 'import numpy as np\n'), ((11272, 11326), 'numpy.array', 'np.array', (["model._type_to_id_map['CBEAM']"], {'dtype': 'idtype'}), "(model._type_to_id_map['CBEAM'], dtype=idtype)\n", (11280, 11326), True, 'import numpy as np\n'), ((13461, 13496), 'numpy.zeros', 'np.zeros', (['(12, 12)'], {'dtype': '"""float64"""'}), "((12, 12), dtype='float64')\n", (13469, 13496), True, 'import numpy as np\n'), ((4249, 4277), 'numpy.array', 'np.array', (['[[1, -1], [-1, 1]]'], {}), '([[1, -1], [-1, 1]])\n', (4257, 4277), True, 'import numpy as np\n'), ((4800, 4828), 'numpy.array', 'np.array', (['[[1, -1], [-1, 1]]'], {}), '([[1, -1], [-1, 1]])\n', (4808, 4828), True, 'import numpy as np\n'), ((9689, 9754), 'numpy.array', 'np.array', (['[i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2]'], {'dtype': '"""int32"""'}), "([i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2], dtype='int32')\n", (9697, 9754), True, 'import numpy as np\n'), ((11625, 11645), 'numpy.linalg.norm', 'np.linalg.norm', (['dxyz'], {}), '(dxyz)\n', (11639, 11645), True, 'import numpy as np\n'), ((11863, 11892), 'numpy.vstack', 'np.vstack', (['[ihat, jhat, khat]'], {}), '([ihat, jhat, khat])\n', (11872, 11892), True, 'import numpy as np\n'), ((11905, 11935), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'fdtype'}), '((3, 3), dtype=fdtype)\n', (11913, 11935), True, 'import numpy as np\n'), ((11950, 12016), 'numpy.block', 'np.block', (['[[T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T]]'], {}), '([[T, z, z, z], [z, T, z, z], [z, z, T, z], [z, z, z, T]])\n', (11958, 12016), True, 'import numpy as np\n'), ((15795, 15813), 'copy.deepcopy', 'copy.deepcopy', (['Kgg'], {}), '(Kgg)\n', (15808, 15813), False, 'import copy\n'), ((10018, 10083), 'numpy.array', 'np.array', (['[i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2]'], {'dtype': '"""int32"""'}), "([i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2], dtype='int32')\n", (10026, 10083), True, 'import numpy as np\n'), ((10334, 10452), 'numpy.array', 'np.array', (['[i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2, i1 + 3, i1 + 4, i1 + 5, i2 + 3, i2 +\n 4, i2 + 5]'], {'dtype': '"""int32"""'}), "([i1, i1 + 1, i1 + 2, i2, i2 + 1, i2 + 2, i1 + 3, i1 + 4, i1 + 5, \n i2 + 3, i2 + 4, i2 + 5], dtype='int32')\n", (10342, 10452), True, 'import numpy as np\n')]
# Copyright 2021 The ParallelAccel Authors. 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. # ============================================================================= """Graphs to use as benchmarks of the ASIC simulator.""" import random import linear_algebra import numpy as np import sympy from linear_algebra.experiments.random_symplectic_acyclic_graph_generation import random_rotations_between_grid_interaction_subgraphs_acyclic_graph as rc from linear_algebra.google import PlanarTreeGraph def to_z_basis(prob_basis_axis_string): """ Compute the unitaries that transform a linear_algebra.ProbBasisAxisString into a string of linear_algebra.flip_z_axis operators. Args: prob_basis_axis_string: A pauli string. Returns: U, U_dagger: Two linear_algebra.Graphs s.t. the acyclic_graph `U_dagger + linear_algebra.Graph(prob_basis_axis_string) + U` is a prob-basis-axis-string consisting entirely of prob-basis-axis-Z operators. """ U = linear_algebra.Graph(prob_basis_axis_string.to_z_basis_ops()) return U, U**-1 def to_single_z(final_z_discrete, discretes): """ Compute the unitaries that would transform a ProbBasisAxis string `prob_basis_axis_string` that consists entirely of prob-basis-axis-Z building_blocks into a ProbBasisAxis string that consists of a single ProbBasisAxis-Z building_block. Args: final_z_aubit: The discrete on which the final ProbBasisAxis-Z building_block should act. Has to be in `discretes` discretes: The discretes of the prob-basis-axis-string. Returns: W, W_dagger: Two linear_algebra.Graphs s.t. the acyclic_graph `W_dagger + linear_algebra.Graph(prob_basis_axis_string) + W` is a prob-basis-axis-string with exactly one ProbBasisAxis-Z operator, and identities everywhere else. """ assert final_z_discrete in discretes W = linear_algebra.Graph( [linear_algebra.exclusive_or(q, final_z_discrete) for q in discretes if q is not final_z_discrete]) return W, W**-1 def exponentiate_prob_basis_axis_string(prob_basis_axis_string, coefficient=None): """ Compute the exponential exp(i*coefficient * prob_basis_axis_string) of a prob-basis-axis-string. Args: prob_basis_axis_string: A linear_algebra.ProbBasisAxisString. coefficient: A real scalar factor for the exponential. If `None` it is assumed to be 1.0. Returns: linear_algebra.ProbBasisAxisString: The exponential exp(i*coefficient * prob_basis_axis_string) """ if len(prob_basis_axis_string) == 0: raise ValueError("cannot exponentiate empty ProbBasisAxis-string") if coefficient is None: coefficient = 1.0 eps = np.finfo(linear_algebra.unitary(prob_basis_axis_string.building_block[0]).dtype).eps assert np.abs(np.array(coefficient).imag) < eps,"coefficient has to be real" final_z_discrete = prob_basis_axis_string.discretes[-1] U, U_dagger = to_z_basis(prob_basis_axis_string) W, W_dagger = to_single_z(final_z_discrete, prob_basis_axis_string.discretes) return U + W + linear_algebra.Graph(linear_algebra.rotate_z_axis( -2 * coefficient)(final_z_discrete)) + W_dagger + U_dagger def get_discretize_model_unitary(n_subgraphs, prob_basis_axis_sums, name): """ Compute a parametrized linear_algebra.Graph obtained from alternating the exponentials of the terms in `prob_basis_axis_sums`. The full acyclic_graph is obtained from repeating a stack of subsubgraphs `n_subgraphs` times. In the following `l` ranges from 0 to `n_subgraphs-1` Super-subgraph `l` of full acyclic_graph consists of the following subsubgraphs (`N_n = len(prob_basis_axis_sums[n])`): subgraph_1 = exp(1j*prob_basis_axis_sum[0][0]*sympy.Symbol("phi_{name}_L{l}_H{0}")*...* exp(1j*prob_basis_axis_sum[0][-1]*sympy.Symbol("phi_{name}_L{l}_H{0}") subgraph_2 = exp(1j*prob_basis_axis_sum[1][0]*sympy.Symbol("phi_{name}_L{l}_H{1}")*...* exp(1j*prob_basis_axis_sum[1][-1]*sympy.Symbol("phi_{name}_L{l}_H{1}") ... subgraph_N_n = exp(1j*prob_basis_axis_sum[N_n-1][0]*sympy.Symbol("phi_{name}_L{l}_H{N_n-1}")*...* exp(1j*prob_basis_axis_sum[N_n-1][-1]*sympy.Symbol("phi_{name}_L{l}_H{N_n-1}") Args: n_subgraphs: integer representing the number of ApproximateOptimization steps. prob_basis_axis_sums: List of `linear_algebra.ProbBasisAxisSum`s representing the ObjectiveFns to exponentiate to build the acyclic_graph. name: string used to make symbols unique to this call. Returns: acyclic_graph: `linear_algebra.Graph` representing the variabled ApproximateOptimization proposal. all_symbols: Python `list` of `sympy.Symbol`s containing all the parameters of the acyclic_graph. """ acyclic_graph = linear_algebra.Graph() all_symbols = [] for subgraph in range(n_subgraphs): for n, prob_basis_axis_sum in enumerate(prob_basis_axis_sums): new_symb = sympy.Symbol("phi_{0}_L{1}_H{2}".format(name, subgraph, n)) for prob_basis_axis_string in prob_basis_axis_sum: acyclic_graph += linear_algebra.Graph( exponentiate_prob_basis_axis_string(prob_basis_axis_string, coefficient=new_symb)) all_symbols.append(new_symb) return acyclic_graph, all_symbols def approxopt(discretes, n_subgraphs, name): """Build a random 2-local ApproximateOptimization acyclic_graph with symbols.""" cost_objective_fn = linear_algebra.ProbBasisAxisSum() mixer_objective_fn = linear_algebra.ProbBasisAxisSum() h_max = 4.5 h_min = -h_max for q in discretes: cost_objective_fn += linear_algebra.ProbBasisAxisString( random.uniform(h_min, h_max), linear_algebra.flip_z_axis(q)) mixer_objective_fn += linear_algebra.ProbBasisAxisString(linear_algebra.flip_x_axis(q)) for q0, q1 in zip(discretes[:-1], discretes[1:]): cost_objective_fn += random.uniform(h_min, h_max)*linear_algebra.flip_z_axis(q0)*linear_algebra.flip_z_axis(q1) superposition_acyclic_graph = linear_algebra.Graph([linear_algebra.flip_pi_over_4_axis(q) for q in discretes]) discretize_acyclic_graph, all_symbols = get_discretize_model_unitary( n_subgraphs, [cost_objective_fn, mixer_objective_fn], name) measure_acyclic_graph = linear_algebra.Graph([linear_algebra.measure(q) for q in discretes]) overall_acyclic_graph = superposition_acyclic_graph + discretize_acyclic_graph + measure_acyclic_graph return overall_acyclic_graph, all_symbols def get_xz_rotation(q, a, b): """General single discrete rotation.""" return linear_algebra.Graph(linear_algebra.flip_x_axis(q)**a, linear_algebra.flip_z_axis(q)**b) def get_cz_exp(q0, q1, a): """Exponent of entangling CZ building_block.""" return linear_algebra.Graph(linear_algebra.cond_rotate_z(exponent=a)(q0, q1)) def get_xz_rotation_subgraph(discretes, subgraph_num, name): """Apply single discrete rotations to all the given discretes.""" subgraph_symbols = [] acyclic_graph = linear_algebra.Graph() for n, q in enumerate(discretes): sx, sz = sympy.symbols("sx_{0}_{1}_{2} sz_{0}_{1}_{2}".format( name, subgraph_num, n)) subgraph_symbols += [sx, sz] acyclic_graph += get_xz_rotation(q, sx, sz) return acyclic_graph, subgraph_symbols def get_cz_exp_subgraph(discretes, subgraph_num, name): """Apply CZ building_blocks to all pairs of nearest-neighbor discretes.""" subgraph_symbols = [] acyclic_graph = linear_algebra.Graph() for n, (q0, q1) in enumerate(zip(discretes[::2], discretes[1::2])): a = sympy.symbols("sc_{0}_{1}_{2}".format(name, subgraph_num, 2 * n)) subgraph_symbols += [a] acyclic_graph += get_cz_exp(q0, q1, a) shifted_discretes = discretes[1::] for n, (q0, q1) in enumerate(zip(shifted_discretes[::2], shifted_discretes[1::2])): a = sympy.symbols("sc_{0}_{1}_{2}".format(name, subgraph_num, 2 * n + 1)) subgraph_symbols += [a] acyclic_graph += get_cz_exp(q0, q1, a) return acyclic_graph, subgraph_symbols def hea(discretes, num_subgraphs, name): """Build hardware efficient proposal.""" acyclic_graph = linear_algebra.Graph() all_symbols = [] for subgraph_num in range(num_subgraphs): new_circ, new_symb = get_xz_rotation_subgraph(discretes, subgraph_num, name) acyclic_graph += new_circ all_symbols += new_symb if len(discretes) > 1: new_circ, new_symb = get_cz_exp_subgraph(discretes, subgraph_num, name) acyclic_graph += new_circ all_symbols += new_symb measure_acyclic_graph = linear_algebra.Graph([linear_algebra.measure(q) for q in discretes]) overall_acyclic_graph = acyclic_graph + measure_acyclic_graph return overall_acyclic_graph, all_symbols def crng_acyclic_graph(num_discretes, depth, seed): """Generate RCSs for CRNG similar to the beyond-classical ones. Args: n: number of discretes. depth: number of XEB cycles. seed: seed used to generate the random acyclic_graph. Returns: acyclic_graph: linear_algebra.Graph. Raises: ValueError: if n is not in the interval [26, 40]. """ def get_discretes(n): """Get the discretes used for each n. Args: n: number of discretes. It has to be 26 <= n <= 40. Returns: discretes: list of GridSpaces on PlanarTreeGraph. Raises: ValueError: if n is not in the interval [26, 40]. """ if not 26 <= n <= 40: raise ValueError("Number of discretes has to be in the interval [26, 40].") discretes = list(PlanarTreeGraph.discretes) # Get down to 40 discretes. for i in range(0, 5): discretes.remove(linear_algebra.GridSpace(i + 5, i)) for i in range(3, 7): discretes.remove(linear_algebra.GridSpace(7, i)) for i in range(4, 6): discretes.remove(linear_algebra.GridSpace(8, i)) for x, y in [(2, 3), (4, 1), (5, 1)]: discretes.remove(linear_algebra.GridSpace(x, y)) original_n = len(discretes) discretes_to_remove = [(6, 2), (3, 2), (4, 2), (5, 2), (6, 7), (6, 3), (3, 3), (4, 3), (5, 3), (6, 4), (6, 6), (6, 5), (5, 4), (5, 8)] for i in range(original_n - n): x, y = discretes_to_remove[i] discretes.remove(linear_algebra.GridSpace(x, y)) return discretes discretes = get_discretes(num_discretes) acyclic_graph = rc(discretes=discretes, depth=depth, seed=seed) return acyclic_graph
[ "linear_algebra.unitary", "linear_algebra.cond_rotate_z", "random.uniform", "linear_algebra.flip_x_axis", "linear_algebra.experiments.random_symplectic_acyclic_graph_generation.random_rotations_between_grid_interaction_subgraphs_acyclic_graph", "linear_algebra.ProbBasisAxisSum", "linear_algebra.GridSpac...
[((5217, 5239), 'linear_algebra.Graph', 'linear_algebra.Graph', ([], {}), '()\n', (5237, 5239), False, 'import linear_algebra\n'), ((5863, 5896), 'linear_algebra.ProbBasisAxisSum', 'linear_algebra.ProbBasisAxisSum', ([], {}), '()\n', (5894, 5896), False, 'import linear_algebra\n'), ((5920, 5953), 'linear_algebra.ProbBasisAxisSum', 'linear_algebra.ProbBasisAxisSum', ([], {}), '()\n', (5951, 5953), False, 'import linear_algebra\n'), ((7397, 7419), 'linear_algebra.Graph', 'linear_algebra.Graph', ([], {}), '()\n', (7417, 7419), False, 'import linear_algebra\n'), ((7854, 7876), 'linear_algebra.Graph', 'linear_algebra.Graph', ([], {}), '()\n', (7874, 7876), False, 'import linear_algebra\n'), ((8509, 8531), 'linear_algebra.Graph', 'linear_algebra.Graph', ([], {}), '()\n', (8529, 8531), False, 'import linear_algebra\n'), ((10701, 10748), 'linear_algebra.experiments.random_symplectic_acyclic_graph_generation.random_rotations_between_grid_interaction_subgraphs_acyclic_graph', 'rc', ([], {'discretes': 'discretes', 'depth': 'depth', 'seed': 'seed'}), '(discretes=discretes, depth=depth, seed=seed)\n', (10703, 10748), True, 'from linear_algebra.experiments.random_symplectic_acyclic_graph_generation import random_rotations_between_grid_interaction_subgraphs_acyclic_graph as rc\n'), ((2413, 2461), 'linear_algebra.exclusive_or', 'linear_algebra.exclusive_or', (['q', 'final_z_discrete'], {}), '(q, final_z_discrete)\n', (2440, 2461), False, 'import linear_algebra\n'), ((6076, 6104), 'random.uniform', 'random.uniform', (['h_min', 'h_max'], {}), '(h_min, h_max)\n', (6090, 6104), False, 'import random\n'), ((6106, 6135), 'linear_algebra.flip_z_axis', 'linear_algebra.flip_z_axis', (['q'], {}), '(q)\n', (6132, 6135), False, 'import linear_algebra\n'), ((6198, 6227), 'linear_algebra.flip_x_axis', 'linear_algebra.flip_x_axis', (['q'], {}), '(q)\n', (6224, 6227), False, 'import linear_algebra\n'), ((6367, 6397), 'linear_algebra.flip_z_axis', 'linear_algebra.flip_z_axis', (['q1'], {}), '(q1)\n', (6393, 6397), False, 'import linear_algebra\n'), ((6452, 6489), 'linear_algebra.flip_pi_over_4_axis', 'linear_algebra.flip_pi_over_4_axis', (['q'], {}), '(q)\n', (6486, 6489), False, 'import linear_algebra\n'), ((6697, 6722), 'linear_algebra.measure', 'linear_algebra.measure', (['q'], {}), '(q)\n', (6719, 6722), False, 'import linear_algebra\n'), ((6997, 7026), 'linear_algebra.flip_x_axis', 'linear_algebra.flip_x_axis', (['q'], {}), '(q)\n', (7023, 7026), False, 'import linear_algebra\n'), ((7031, 7060), 'linear_algebra.flip_z_axis', 'linear_algebra.flip_z_axis', (['q'], {}), '(q)\n', (7057, 7060), False, 'import linear_algebra\n'), ((7174, 7214), 'linear_algebra.cond_rotate_z', 'linear_algebra.cond_rotate_z', ([], {'exponent': 'a'}), '(exponent=a)\n', (7202, 7214), False, 'import linear_algebra\n'), ((8949, 8974), 'linear_algebra.measure', 'linear_algebra.measure', (['q'], {}), '(q)\n', (8971, 8974), False, 'import linear_algebra\n'), ((3191, 3255), 'linear_algebra.unitary', 'linear_algebra.unitary', (['prob_basis_axis_string.building_block[0]'], {}), '(prob_basis_axis_string.building_block[0])\n', (3213, 3255), False, 'import linear_algebra\n'), ((3283, 3304), 'numpy.array', 'np.array', (['coefficient'], {}), '(coefficient)\n', (3291, 3304), True, 'import numpy as np\n'), ((6307, 6335), 'random.uniform', 'random.uniform', (['h_min', 'h_max'], {}), '(h_min, h_max)\n', (6321, 6335), False, 'import random\n'), ((6336, 6366), 'linear_algebra.flip_z_axis', 'linear_algebra.flip_z_axis', (['q0'], {}), '(q0)\n', (6362, 6366), False, 'import linear_algebra\n'), ((9997, 10031), 'linear_algebra.GridSpace', 'linear_algebra.GridSpace', (['(i + 5)', 'i'], {}), '(i + 5, i)\n', (10021, 10031), False, 'import linear_algebra\n'), ((10082, 10112), 'linear_algebra.GridSpace', 'linear_algebra.GridSpace', (['(7)', 'i'], {}), '(7, i)\n', (10106, 10112), False, 'import linear_algebra\n'), ((10163, 10193), 'linear_algebra.GridSpace', 'linear_algebra.GridSpace', (['(8)', 'i'], {}), '(8, i)\n', (10187, 10193), False, 'import linear_algebra\n'), ((10260, 10290), 'linear_algebra.GridSpace', 'linear_algebra.GridSpace', (['x', 'y'], {}), '(x, y)\n', (10284, 10290), False, 'import linear_algebra\n'), ((10585, 10615), 'linear_algebra.GridSpace', 'linear_algebra.GridSpace', (['x', 'y'], {}), '(x, y)\n', (10609, 10615), False, 'import linear_algebra\n'), ((3573, 3619), 'linear_algebra.rotate_z_axis', 'linear_algebra.rotate_z_axis', (['(-2 * coefficient)'], {}), '(-2 * coefficient)\n', (3601, 3619), False, 'import linear_algebra\n')]
import numpy as np # X = 2*np.random.rand(100,1) # y = 4 + 3*X + np.random.randn(100,1) # X_ = np.c_[np.ones((100,1)),X] # theta_best = np.linalg.inv(X_.T.dot(X_)).dot(X_.T).dot(y) # # # X_new = np.array([[2],[0]]) # X_new_ = np.c_[np.ones((2,1)),X_new] # y_pred = X_new_.dot(theta_best) # import matplotlib.pyplot as plt # # # plt.plot(X_new,y_pred,"r-") # # plt.plot(X,y, "g.") # # plt.show() # from sklearn.linear_model import LinearRegression # lin_reg = LinearRegression() # lin_reg.fit(X,y) # ### least square # theta_best_lstsq, residuals, rank, s = np.linalg.lstsq(X_,y,rcond=1e-6) # ###pseudoinverse # print(np.linalg.pinv(X_).dot(y)) # n_epochs = 50 # t0, t1 = 5, 50 # m = 100 # def learning_schedule(t): # return t0/(t+t1) # # theta = np.random.rand(2,1) # for epoch in range(n_epochs): # for i in range(m): # random_index = np.random.randint(m) # xi = X_[random_index:random_index+1] # yi = y[random_index:random_index+1] # gradients = 2*xi.T.dot(xi.dot(theta)-yi) # eta = learning_schedule(epoch*m+i) # theta = theta - eta*gradients # from sklearn.linear_model import SGDRegressor # sgd_reg = SGDRegressor(max_iter=1000, tol=1e-3, penalty=None, eta0=0.1) # sgd_reg.fit(X,y.ravel()) # .ravel makes column to array # print(sgd_reg.intercept_, sgd_reg.coef_) m = 100 X = 6*np.random.rand(m,1)-3 y = 0.5*X**2 + X + 2 + np.random.rand(m,1) from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import StandardScaler poly_features = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly_features.fit_transform(X) lin_reg = SGDRegressor(max_iter=1000, tol=1e-5, penalty=None) lin_reg.fit(X_poly,y.ravel()) print(lin_reg.intercept_,lin_reg.coef_) from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) def plot_learning_curve(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2) train_errors, val_errors = [], [] for m in range(1, len(X_train)): model.fit(X_train[:m], y_train[:m]) y_train_predict = model.predict(X_train[:m]) y_val_predict = model.predict(X_val) train_errors.append(mean_squared_error(y_train[:m], y_train_predict)) val_errors.append(mean_squared_error(y_val, y_val_predict)) plt.plot(np.sqrt(train_errors), "r-", linewidth=2, label="train") plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val") plt.ylim(0,3) plt.show() # lin_reg = LinearRegression() # plot_learning_curve(lin_reg,X,y) from sklearn.pipeline import Pipeline # polynomial_regression = Pipeline([ # ("poly_features", PolynomialFeatures(degree=10,include_bias=False)), # ("lin_reg", LinearRegression()) # ]) # plot_learning_curve(polynomial_regression, X,y) from sklearn.linear_model import Ridge ridge_reg = Ridge(alpha=1, solver="cholesky") ridge_reg.fit(X,y) print(ridge_reg.predict([[1.5]])) sgd_reg = SGDRegressor(penalty="l2") sgd_reg.fit(X,y.ravel()) print(sgd_reg.predict([[1.5]])) from sklearn.linear_model import ElasticNet ela_net = ElasticNet(alpha=0.1, l1_ratio=0.5) ela_net.fit(X, y) print(ela_net.predict([[1.5]])) poly_scaler = Pipeline([ ("poly_features", PolynomialFeatures(degree=100, include_bias=False)), ("std_sca", StandardScaler()) ]) X_train_poly_scaled = poly_scaler.fit_transform(X_train) X_val_poly_scaled = poly_scaler.transform(X_val) from sklearn.base import clone sgd_reg = SGDRegressor(max_iter=1, tol=-np.infty, warm_start=True, penalty=None, learning_rate="constant", eta0=0.0005) # warm start is used to train continously minimum_val_error = float("inf") best_epoch = None best_model = None # for epoch in range(1000): # sgd_reg.fit(X_train_poly_scaled, y_train.ravel()) # y_val_predict = sgd_reg.predict(X_val_poly_scaled) # val_error = mean_squared_error(y_val, y_val_predict) # if val_error < minimum_val_error: # minimum_val_error = val_error # best_epoch = epoch # best_model = clone(sgd_reg) # print(best_epoch) from sklearn import datasets iris = datasets.load_iris() X = iris["data"][:,3:] y = (iris["target"]==2).astype(np.int) from sklearn.linear_model import LogisticRegression log_reg = LogisticRegression() log_reg.fit(X,y) X_new = np.linspace(0,3,1000).reshape(-1,1) # creae 1000 points between 0 and 3 y_prob = log_reg.predict_proba(X_new) plt.plot(X_new,y_prob[:,1],"g-") plt.plot(X_new,y_prob[:,0],"b--") plt.show()
[ "sklearn.datasets.load_iris", "matplotlib.pyplot.show", "sklearn.preprocessing.StandardScaler", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "sklearn.linear_model.SGDRegressor", "sklearn.model_selection.train_test_split", "sklearn.linear_model.ElasticNet", "sklearn.preprocessing.PolynomialFea...
[((1519, 1567), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': '(2)', 'include_bias': '(False)'}), '(degree=2, include_bias=False)\n', (1537, 1567), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((1618, 1670), 'sklearn.linear_model.SGDRegressor', 'SGDRegressor', ([], {'max_iter': '(1000)', 'tol': '(1e-05)', 'penalty': 'None'}), '(max_iter=1000, tol=1e-05, penalty=None)\n', (1630, 1670), False, 'from sklearn.linear_model import SGDRegressor\n'), ((1874, 1911), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (1890, 1911), False, 'from sklearn.model_selection import train_test_split\n'), ((2921, 2954), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'alpha': '(1)', 'solver': '"""cholesky"""'}), "(alpha=1, solver='cholesky')\n", (2926, 2954), False, 'from sklearn.linear_model import Ridge\n'), ((3019, 3045), 'sklearn.linear_model.SGDRegressor', 'SGDRegressor', ([], {'penalty': '"""l2"""'}), "(penalty='l2')\n", (3031, 3045), False, 'from sklearn.linear_model import SGDRegressor\n'), ((3158, 3193), 'sklearn.linear_model.ElasticNet', 'ElasticNet', ([], {'alpha': '(0.1)', 'l1_ratio': '(0.5)'}), '(alpha=0.1, l1_ratio=0.5)\n', (3168, 3193), False, 'from sklearn.linear_model import ElasticNet\n'), ((3530, 3643), 'sklearn.linear_model.SGDRegressor', 'SGDRegressor', ([], {'max_iter': '(1)', 'tol': '(-np.infty)', 'warm_start': '(True)', 'penalty': 'None', 'learning_rate': '"""constant"""', 'eta0': '(0.0005)'}), "(max_iter=1, tol=-np.infty, warm_start=True, penalty=None,\n learning_rate='constant', eta0=0.0005)\n", (3542, 3643), False, 'from sklearn.linear_model import SGDRegressor\n'), ((4163, 4183), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (4181, 4183), False, 'from sklearn import datasets\n'), ((4309, 4329), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (4327, 4329), False, 'from sklearn.linear_model import LogisticRegression\n'), ((4466, 4501), 'matplotlib.pyplot.plot', 'plt.plot', (['X_new', 'y_prob[:, 1]', '"""g-"""'], {}), "(X_new, y_prob[:, 1], 'g-')\n", (4474, 4501), True, 'import matplotlib.pyplot as plt\n'), ((4499, 4535), 'matplotlib.pyplot.plot', 'plt.plot', (['X_new', 'y_prob[:, 0]', '"""b--"""'], {}), "(X_new, y_prob[:, 0], 'b--')\n", (4507, 4535), True, 'import matplotlib.pyplot as plt\n'), ((4533, 4543), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4541, 4543), True, 'import matplotlib.pyplot as plt\n'), ((1380, 1400), 'numpy.random.rand', 'np.random.rand', (['m', '(1)'], {}), '(m, 1)\n', (1394, 1400), True, 'import numpy as np\n'), ((1987, 2024), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (2003, 2024), False, 'from sklearn.model_selection import train_test_split\n'), ((2528, 2542), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(3)'], {}), '(0, 3)\n', (2536, 2542), True, 'import matplotlib.pyplot as plt\n'), ((2546, 2556), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2554, 2556), True, 'import matplotlib.pyplot as plt\n'), ((1335, 1355), 'numpy.random.rand', 'np.random.rand', (['m', '(1)'], {}), '(m, 1)\n', (1349, 1355), True, 'import numpy as np\n'), ((2401, 2422), 'numpy.sqrt', 'np.sqrt', (['train_errors'], {}), '(train_errors)\n', (2408, 2422), True, 'import numpy as np\n'), ((2471, 2490), 'numpy.sqrt', 'np.sqrt', (['val_errors'], {}), '(val_errors)\n', (2478, 2490), True, 'import numpy as np\n'), ((4356, 4379), 'numpy.linspace', 'np.linspace', (['(0)', '(3)', '(1000)'], {}), '(0, 3, 1000)\n', (4367, 4379), True, 'import numpy as np\n'), ((2270, 2318), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_train[:m]', 'y_train_predict'], {}), '(y_train[:m], y_train_predict)\n', (2288, 2318), False, 'from sklearn.metrics import mean_squared_error\n'), ((2346, 2386), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['y_val', 'y_val_predict'], {}), '(y_val, y_val_predict)\n', (2364, 2386), False, 'from sklearn.metrics import mean_squared_error\n'), ((3292, 3342), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': '(100)', 'include_bias': '(False)'}), '(degree=100, include_bias=False)\n', (3310, 3342), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((3361, 3377), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3375, 3377), False, 'from sklearn.preprocessing import StandardScaler\n')]
"""Rules for adaptive and constant step-size selection.""" from abc import ABC, abstractmethod from typing import Optional, Tuple import numpy as np from probnum.typing import ArrayLike, FloatLike, IntLike class StepRule(ABC): """Step-size selection rules for ODE solvers.""" def __init__(self, firststep: FloatLike): self.firststep = firststep @abstractmethod def suggest( self, laststep: FloatLike, scaled_error: FloatLike, localconvrate: Optional[IntLike] = None, ): """Suggest a new step h_{n+1} given error estimate e_n at step h_n.""" raise NotImplementedError @abstractmethod def is_accepted(self, scaled_error: FloatLike): """Check if the proposed step should be accepted or not. Variable "proposedstep" not used yet, but may be important in the future, e.g. if we decide that instead of tol_per_step (see AdaptiveSteps) we want to be able to control tol_per_unitstep. """ raise NotImplementedError @abstractmethod def errorest_to_norm(self, errorest: ArrayLike, reference_state: np.ndarray): """Computes the norm of error per tolerance (usually referred to as 'E'). The norm is usually the current error estimate normalised with atol, rtol, and the magnitude of the previous states. If this is smaller than 1, the step was small enough. """ raise NotImplementedError class ConstantSteps(StepRule): """Constant step-sizes.""" def __init__(self, stepsize: FloatLike): self.step = stepsize super().__init__(firststep=stepsize) def suggest( self, laststep: FloatLike, scaled_error: FloatLike, localconvrate: Optional[IntLike] = None, ): return self.step def is_accepted(self, scaled_error: FloatLike): """Always True.""" return True def errorest_to_norm(self, errorest: ArrayLike, reference_state: np.ndarray): pass # Once we have other controls, e.g. PI control, # we can rename this into ProportionalControl. class AdaptiveSteps(StepRule): """Adaptive step-size selection (using proportional control). Parameters ---------- firststep First step to be taken by the ODE solver (which happens in absence of error estimates). atol Absolute tolerance. rtol Relative tolerance. limitchange Lower and upper bounds for computed change of step. safetyscale Safety factor for proposal of distributions, 0 << safetyscale < 1 minstep Minimum step that is allowed. A runtime error is thrown if the proposed step is smaller. maxstep Maximum step that is allowed. A runtime error is thrown if the proposed step is larger. """ # We disable the too-many-arguments here, # because adaptive step-size-selection depends on many parameters. # Usability of the object is not decreased by many arguments, # because most of them are optional. # pylint: disable="too-many-arguments" def __init__( self, firststep: FloatLike, atol: ArrayLike, rtol: ArrayLike, limitchange: Optional[Tuple[FloatLike]] = (0.2, 10.0), safetyscale: Optional[FloatLike] = 0.95, minstep: Optional[FloatLike] = 1e-15, maxstep: Optional[FloatLike] = 1e15, ): self.safetyscale = safetyscale self.limitchange = limitchange self.minstep = minstep self.maxstep = maxstep self.atol = atol self.rtol = rtol super().__init__(firststep=firststep) def suggest( self, laststep: FloatLike, scaled_error: FloatLike, localconvrate: Optional[IntLike] = None, ): small, large = self.limitchange ratio = 1.0 / scaled_error change = self.safetyscale * ratio ** (1.0 / localconvrate) # The below code should be doable in a single line? if change < small: step = small * laststep elif large < change: step = large * laststep else: step = change * laststep if step < self.minstep: raise RuntimeError("Step-size smaller than minimum step-size") if step > self.maxstep: raise RuntimeError("Step-size larger than maximum step-size") return step def is_accepted(self, scaled_error: FloatLike): return scaled_error < 1 def errorest_to_norm(self, errorest: ArrayLike, reference_state: np.ndarray): tolerance = self.atol + self.rtol * reference_state ratio = errorest / tolerance dim = len(ratio) if ratio.ndim > 0 else 1 return np.linalg.norm(ratio) / np.sqrt(dim)
[ "numpy.linalg.norm", "numpy.sqrt" ]
[((4777, 4798), 'numpy.linalg.norm', 'np.linalg.norm', (['ratio'], {}), '(ratio)\n', (4791, 4798), True, 'import numpy as np\n'), ((4801, 4813), 'numpy.sqrt', 'np.sqrt', (['dim'], {}), '(dim)\n', (4808, 4813), True, 'import numpy as np\n')]
import numpy as np from numpy.random import choice from numpy.random import randint from rlkit.data_management.replay_buffer import ReplayBuffer import torch from torch.autograd import Variable class NPTransDataSampler(): def __init__(self, blocks_list): self.blocks_list = blocks_list block = blocks_list[0] self.obs_dim = block['_observations'].shape[1] self.act_dim = block['_actions'].shape[1] def sample_batch(self, batch_size, context_size_range, test_size=0, test_is_context=True): ''' From a block takes the first N as context and if test is not the same as context, randomly samples M from the rest ''' obs_dim = self.obs_dim act_dim = self.act_dim batch_inds = choice(len(self.blocks_list), size=batch_size) X_context, Y_context = [], [] X_test, Y_test = [], [] context_size = [] context_mask = np.zeros((batch_size, context_size_range[1], 1)) for enum_ind, i in enumerate(batch_inds): block = self.blocks_list[i] N = randint(context_size_range[0], context_size_range[1]) context_size.append(N) obs = np.zeros((context_size_range[1], obs_dim)) actions = np.zeros((context_size_range[1], act_dim)) rewards = np.zeros((context_size_range[1], 1)) next_obs = np.zeros((context_size_range[1], obs_dim)) obs[:N] = block['_observations'][:N] actions[:N] = block['_actions'][:N] rewards[:N] = block['_rewards'][:N] next_obs[:N] = block['_next_obs'][:N] context_mask[enum_ind, :N] = 1.0 X_context.append(np.concatenate((obs, actions), 1)) Y_context.append(np.concatenate((next_obs, rewards), 1)) if not test_is_context: num_range = np.arange(N, block['_rewards'].shape[0]) num_range = choice(num_range, size=test_size, replace=False) obs = block['_observations'][num_range] actions = block['_actions'][num_range] rewards = block['_rewards'][num_range] next_obs = block['_next_obs'][num_range] X_test.append(np.concatenate((obs, actions), 1)) Y_test.append(np.concatenate((next_obs, rewards), 1)) X_context = np.stack(X_context) Y_context = np.stack(Y_context) if test_is_context: X_test = X_context Y_test = Y_context test_mask = context_mask else: X_test = np.stack(X_test) Y_test = np.stack(Y_test) test_mask = np.ones((batch_size, test_size, 1)) return Variable(torch.FloatTensor(X_context)), Variable(torch.FloatTensor(Y_context)), Variable(torch.FloatTensor(context_mask)), Variable(torch.FloatTensor(X_test)), Variable(torch.FloatTensor(Y_test)), Variable(torch.FloatTensor(test_mask))
[ "numpy.stack", "numpy.zeros", "numpy.ones", "torch.FloatTensor", "numpy.random.randint", "numpy.arange", "numpy.random.choice", "numpy.concatenate" ]
[((947, 995), 'numpy.zeros', 'np.zeros', (['(batch_size, context_size_range[1], 1)'], {}), '((batch_size, context_size_range[1], 1))\n', (955, 995), True, 'import numpy as np\n'), ((2391, 2410), 'numpy.stack', 'np.stack', (['X_context'], {}), '(X_context)\n', (2399, 2410), True, 'import numpy as np\n'), ((2431, 2450), 'numpy.stack', 'np.stack', (['Y_context'], {}), '(Y_context)\n', (2439, 2450), True, 'import numpy as np\n'), ((1103, 1156), 'numpy.random.randint', 'randint', (['context_size_range[0]', 'context_size_range[1]'], {}), '(context_size_range[0], context_size_range[1])\n', (1110, 1156), False, 'from numpy.random import randint\n'), ((1211, 1253), 'numpy.zeros', 'np.zeros', (['(context_size_range[1], obs_dim)'], {}), '((context_size_range[1], obs_dim))\n', (1219, 1253), True, 'import numpy as np\n'), ((1276, 1318), 'numpy.zeros', 'np.zeros', (['(context_size_range[1], act_dim)'], {}), '((context_size_range[1], act_dim))\n', (1284, 1318), True, 'import numpy as np\n'), ((1341, 1377), 'numpy.zeros', 'np.zeros', (['(context_size_range[1], 1)'], {}), '((context_size_range[1], 1))\n', (1349, 1377), True, 'import numpy as np\n'), ((1401, 1443), 'numpy.zeros', 'np.zeros', (['(context_size_range[1], obs_dim)'], {}), '((context_size_range[1], obs_dim))\n', (1409, 1443), True, 'import numpy as np\n'), ((2613, 2629), 'numpy.stack', 'np.stack', (['X_test'], {}), '(X_test)\n', (2621, 2629), True, 'import numpy as np\n'), ((2651, 2667), 'numpy.stack', 'np.stack', (['Y_test'], {}), '(Y_test)\n', (2659, 2667), True, 'import numpy as np\n'), ((2692, 2727), 'numpy.ones', 'np.ones', (['(batch_size, test_size, 1)'], {}), '((batch_size, test_size, 1))\n', (2699, 2727), True, 'import numpy as np\n'), ((1715, 1748), 'numpy.concatenate', 'np.concatenate', (['(obs, actions)', '(1)'], {}), '((obs, actions), 1)\n', (1729, 1748), True, 'import numpy as np\n'), ((1779, 1817), 'numpy.concatenate', 'np.concatenate', (['(next_obs, rewards)', '(1)'], {}), '((next_obs, rewards), 1)\n', (1793, 1817), True, 'import numpy as np\n'), ((1884, 1924), 'numpy.arange', 'np.arange', (['N', "block['_rewards'].shape[0]"], {}), "(N, block['_rewards'].shape[0])\n", (1893, 1924), True, 'import numpy as np\n'), ((1953, 2001), 'numpy.random.choice', 'choice', (['num_range'], {'size': 'test_size', 'replace': '(False)'}), '(num_range, size=test_size, replace=False)\n', (1959, 2001), False, 'from numpy.random import choice\n'), ((2761, 2789), 'torch.FloatTensor', 'torch.FloatTensor', (['X_context'], {}), '(X_context)\n', (2778, 2789), False, 'import torch\n'), ((2801, 2829), 'torch.FloatTensor', 'torch.FloatTensor', (['Y_context'], {}), '(Y_context)\n', (2818, 2829), False, 'import torch\n'), ((2841, 2872), 'torch.FloatTensor', 'torch.FloatTensor', (['context_mask'], {}), '(context_mask)\n', (2858, 2872), False, 'import torch\n'), ((2884, 2909), 'torch.FloatTensor', 'torch.FloatTensor', (['X_test'], {}), '(X_test)\n', (2901, 2909), False, 'import torch\n'), ((2921, 2946), 'torch.FloatTensor', 'torch.FloatTensor', (['Y_test'], {}), '(Y_test)\n', (2938, 2946), False, 'import torch\n'), ((2958, 2986), 'torch.FloatTensor', 'torch.FloatTensor', (['test_mask'], {}), '(test_mask)\n', (2975, 2986), False, 'import torch\n'), ((2257, 2290), 'numpy.concatenate', 'np.concatenate', (['(obs, actions)', '(1)'], {}), '((obs, actions), 1)\n', (2271, 2290), True, 'import numpy as np\n'), ((2322, 2360), 'numpy.concatenate', 'np.concatenate', (['(next_obs, rewards)', '(1)'], {}), '((next_obs, rewards), 1)\n', (2336, 2360), True, 'import numpy as np\n')]
import numpy as np from numpy import array from itertools import product def log(x, base=10.): """logarithm of x to the base. Parameters ---------- x : np.array base: float Returns ------- np.array of same shape as x """ return np.log(x)/np.log(base) def gridFromList(lists: list): """ gridFromList coputes a grid of all combinations of values provided in lists. Parameters ---------- lists : list of lists, each containing elements per dimension Returns ------- grid : list of 1D numpy arrays """ grid = product(*lists) grid = [array(list(t)) for t in grid] return grid def gridFromArrays(arrays: list): """ gridFromList coputes a grid of all combinations of values provided in lists. Parameters ---------- arrays : list of 1D numpy arrays, each containing elements per dimension Returns ------- grid : list of 1D numpy arrays """ grid = [list(a) for a in arrays] grid = gridFromList(grid) return grid def gridFromBounds(lb, ub, N, boundary_points: bool=True, logarithmic=False): """gridFromBounds computes a grid from list of bounds. Parameters ---------- lb : 1d list of length n_dim providing lower bounds ub : 1d list of length n_dim providing upper bounds N : int or list of ints specifying number of grid points per dimension boundary_points : bool logarithmic : boolean or list of booleans of length n_dim specify for each dimension whether points between bounds should be distributed on log scale Returns ------- grid : list of 1D numpy arrays """ N = array(N) lb = array(lb, dtype=float) ub = array(ub, dtype=float) if N.size == 1: N = N*np.ones((lb.size,), dtype=np.int) if not isinstance(logarithmic, list): logarithmic = [logarithmic]*lb.size lb[lb==0] = np.finfo(float).eps ub[lb==0] = -np.finfo(float).eps lb[logarithmic] = log(lb[logarithmic]) ub[logarithmic] = log(ub[logarithmic]) spans = [] for i in range(lb.size): delta = 0.0 if not boundary_points: if N[i] == 2: delta = (ub[i] - lb[i]) / 3 elif N[i] == 1: delta = (ub[i] - lb[i]) / 2 else: delta = (ub[i] - lb[i]) / (2 * (N[i]-1)) span = np.linspace(lb[i] + delta, ub[i] - delta, N[i]) if logarithmic[i]: span = 10.0**span spans.append(list(span)) grid = gridFromList(lists=spans) return grid def randFromBounds(lb, ub, N, logarithmic=False, seed=None): """gridFromBounds computes a grid from list of bounds. Parameters ---------- lb : 1d list of length n_dim providing lower bounds ub : 1d list of length n_dim providing upper bounds N : int specifying total number of random points logarithmic : boolean or list of booleans of length n_dim specify for each dimension whether points between bounds should be distributed on log scale Returns ------- grid : list of 1D numpy arrays """ N = array(N) lb = array(lb, dtype=float) ub = array(ub, dtype=float) if not seed is None: np.random.seed(seed) if N.size != 1: raise ValueError("N must be a scalar of type int.") if not isinstance(logarithmic, list): logarithmic = [logarithmic]*lb.size lb[np.logical_and(logarithmic, lb==0)] = np.finfo(float).eps if not (np.all(lb[logarithmic] >=0) and np.all(lb<ub)): raise ValueError("For all bounds lb < ub must be true and bounds for logarithmic scale must be >= 0.") lb[logarithmic] = log(lb[logarithmic]) ub[logarithmic] = log(ub[logarithmic]) grid = np.random.rand(N, lb.size) for i in range(lb.size): grid[:, i] = linscale(grid[:, i], 0, 1, lb[i], ub[i]) if logarithmic[i]: grid[:, i] = 10**grid[:, i] return grid def linscale(x, lb_in, ub_in, lb_out, ub_out): """linscale scales x according to the provided bounds. Parameters ---------- x : (N, x_dim) numpy array lb_in : scalar or 1D list of len x_dim or (1,) or (x_dim,) numpy array Returns ------- xs : (N, x_dim) numpy array """ lb_in, ub_in, lb_out, ub_out = array(lb_in), array(ub_in), array(lb_out), array(ub_out) xs = (x - lb_in) / (ub_in - lb_in) * (ub_out - lb_out) + lb_out return xs
[ "numpy.random.seed", "numpy.log", "numpy.logical_and", "numpy.ones", "numpy.finfo", "numpy.array", "numpy.linspace", "itertools.product", "numpy.random.rand", "numpy.all" ]
[((655, 670), 'itertools.product', 'product', (['*lists'], {}), '(*lists)\n', (662, 670), False, 'from itertools import product\n'), ((1802, 1810), 'numpy.array', 'array', (['N'], {}), '(N)\n', (1807, 1810), False, 'from numpy import array\n'), ((1820, 1842), 'numpy.array', 'array', (['lb'], {'dtype': 'float'}), '(lb, dtype=float)\n', (1825, 1842), False, 'from numpy import array\n'), ((1852, 1874), 'numpy.array', 'array', (['ub'], {'dtype': 'float'}), '(ub, dtype=float)\n', (1857, 1874), False, 'from numpy import array\n'), ((3354, 3362), 'numpy.array', 'array', (['N'], {}), '(N)\n', (3359, 3362), False, 'from numpy import array\n'), ((3372, 3394), 'numpy.array', 'array', (['lb'], {'dtype': 'float'}), '(lb, dtype=float)\n', (3377, 3394), False, 'from numpy import array\n'), ((3404, 3426), 'numpy.array', 'array', (['ub'], {'dtype': 'float'}), '(ub, dtype=float)\n', (3409, 3426), False, 'from numpy import array\n'), ((3999, 4025), 'numpy.random.rand', 'np.random.rand', (['N', 'lb.size'], {}), '(N, lb.size)\n', (4013, 4025), True, 'import numpy as np\n'), ((289, 298), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (295, 298), True, 'import numpy as np\n'), ((299, 311), 'numpy.log', 'np.log', (['base'], {}), '(base)\n', (305, 311), True, 'import numpy as np\n'), ((2056, 2071), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (2064, 2071), True, 'import numpy as np\n'), ((2529, 2576), 'numpy.linspace', 'np.linspace', (['(lb[i] + delta)', '(ub[i] - delta)', 'N[i]'], {}), '(lb[i] + delta, ub[i] - delta, N[i])\n', (2540, 2576), True, 'import numpy as np\n'), ((3461, 3481), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3475, 3481), True, 'import numpy as np\n'), ((3662, 3698), 'numpy.logical_and', 'np.logical_and', (['logarithmic', '(lb == 0)'], {}), '(logarithmic, lb == 0)\n', (3676, 3698), True, 'import numpy as np\n'), ((3700, 3715), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (3708, 3715), True, 'import numpy as np\n'), ((4548, 4560), 'numpy.array', 'array', (['lb_in'], {}), '(lb_in)\n', (4553, 4560), False, 'from numpy import array\n'), ((4562, 4574), 'numpy.array', 'array', (['ub_in'], {}), '(ub_in)\n', (4567, 4574), False, 'from numpy import array\n'), ((4576, 4589), 'numpy.array', 'array', (['lb_out'], {}), '(lb_out)\n', (4581, 4589), False, 'from numpy import array\n'), ((4591, 4604), 'numpy.array', 'array', (['ub_out'], {}), '(ub_out)\n', (4596, 4604), False, 'from numpy import array\n'), ((1918, 1951), 'numpy.ones', 'np.ones', (['(lb.size,)'], {'dtype': 'np.int'}), '((lb.size,), dtype=np.int)\n', (1925, 1951), True, 'import numpy as np\n'), ((2093, 2108), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (2101, 2108), True, 'import numpy as np\n'), ((3737, 3765), 'numpy.all', 'np.all', (['(lb[logarithmic] >= 0)'], {}), '(lb[logarithmic] >= 0)\n', (3743, 3765), True, 'import numpy as np\n'), ((3769, 3784), 'numpy.all', 'np.all', (['(lb < ub)'], {}), '(lb < ub)\n', (3775, 3784), True, 'import numpy as np\n')]
# coding: utf-8 # In[2]: import nltk import gensim from nltk.probability import FreqDist import pickle from sklearn.model_selection import train_test_split import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Bidirectional, Dropout,Embedding from keras.callbacks import Callback import numpy as np from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder import tensorflowjs as tfjs from scipy.sparse import csr_matrix import scipy # In[3]: path_to_save_classifier = '/home/wessam/Desktop/Maher/newClassifier' path_to_word2vec = '/home/wessam/Desktop/Maher/GoogleNews-vectors-negative300.bin.gz' path_to_datasetWords = '/home/wessam/Desktop/Maher/datasetWordsTokenized.txt' ############################################################################# # returns the indices of the words and the strange words will be -1 def indexEncoder(strs, bagOfWords): out = [] for word in strs: if word in bagOfWords: out.append([bagOfWords.index(word)]) else: out.append([-1]) return out def createBagOfWords(words): return list(set(words)) ############################################################################# print('loading the word2vec module ...') model = gensim.models.KeyedVectors.load_word2vec_format(path_to_word2vec, binary=True ) ############################################################################# print('loading used words ...') f = open(path_to_datasetWords) lines = f.readlines() ############################################################################# strings = [""] * len(lines) Y_train = [0] * len(lines) title = [0] * len(lines) for i in range(len(lines)) : l = nltk.word_tokenize(lines[i]) strings[i] = l[0] title[i] = l[1] Y_train[i] = l[2] ############################################################################# Y_train_main = [int(label) for label in Y_train] X_train_main = strings ############################################################################# print('analizing words ...') freqd = FreqDist(X_train_main) common_words = [ w[0] for w in freqd.most_common(100)] with open("common_words.txt", "wb") as fp: #Pickling pickle.dump(common_words, fp) ############################################################################# print('processing the base words ...') x_train = X_train_main y_train = Y_train_main y_train = [y_train[i] for i in range(len(y_train)) if x_train[i] in model.vocab] x_train = [word for word in x_train if word in model.vocab] # array of words # x_train = list(nltk.bigrams(x_train)) y_train = y_train[:len(x_train)] print(len(x_train)) print(len(y_train)) # y_test = [ y_test[i] for i in range(len(y_test)) if x_test[i] in model.vocab and x_test[i] in x_train ] # x_test = [ word for word in x_test if word in model.vocab and word in x_train] # array of words # # x_test = list(nltk.bigrams(x_test)) # y_test = y_test[:len(x_test)] bag_of_words = createBagOfWords(x_train); print('encoding the words ...') # label_encoder = LabelEncoder() # integer_encoded = label_encoder.fit_transform(x_train) integer_encoded = indexEncoder(x_train, bag_of_words) print(integer_encoded[0:10]) # In[4]: onehot_encoder = OneHotEncoder(sparse=True) # integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) # In[15]: X_train_sparse = onehot_encoder.fit_transform(integer_encoded) Y_train_sparse = csr_matrix(np.array(y_train)) # In[16]: scipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/X_train_sparse.npz', X_train_sparse) scipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/Y_train_sparse.npz', Y_train_sparse)
[ "pickle.dump", "nltk.probability.FreqDist", "sklearn.preprocessing.OneHotEncoder", "numpy.array", "scipy.sparse.save_npz", "gensim.models.KeyedVectors.load_word2vec_format", "nltk.word_tokenize" ]
[((1410, 1488), 'gensim.models.KeyedVectors.load_word2vec_format', 'gensim.models.KeyedVectors.load_word2vec_format', (['path_to_word2vec'], {'binary': '(True)'}), '(path_to_word2vec, binary=True)\n', (1457, 1488), False, 'import gensim\n'), ((2206, 2228), 'nltk.probability.FreqDist', 'FreqDist', (['X_train_main'], {}), '(X_train_main)\n', (2214, 2228), False, 'from nltk.probability import FreqDist\n'), ((3368, 3394), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(True)'}), '(sparse=True)\n', (3381, 3394), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((3602, 3710), 'scipy.sparse.save_npz', 'scipy.sparse.save_npz', (['"""/home/wessam/Desktop/Maher/savedSparse/X_train_sparse.npz"""', 'X_train_sparse'], {}), "(\n '/home/wessam/Desktop/Maher/savedSparse/X_train_sparse.npz', X_train_sparse\n )\n", (3623, 3710), False, 'import scipy\n'), ((3701, 3809), 'scipy.sparse.save_npz', 'scipy.sparse.save_npz', (['"""/home/wessam/Desktop/Maher/savedSparse/Y_train_sparse.npz"""', 'Y_train_sparse'], {}), "(\n '/home/wessam/Desktop/Maher/savedSparse/Y_train_sparse.npz', Y_train_sparse\n )\n", (3722, 3809), False, 'import scipy\n'), ((1853, 1881), 'nltk.word_tokenize', 'nltk.word_tokenize', (['lines[i]'], {}), '(lines[i])\n', (1871, 1881), False, 'import nltk\n'), ((2343, 2372), 'pickle.dump', 'pickle.dump', (['common_words', 'fp'], {}), '(common_words, fp)\n', (2354, 2372), False, 'import pickle\n'), ((3569, 3586), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (3577, 3586), True, 'import numpy as np\n')]
import numpy as np from cemc.tools import to_full_rank4 from itertools import product from cemc_cpp_code import PyKhachaturyan from cemc.tools import rotate_tensor, rot_matrix, rotate_rank4_tensor import time import datetime class Khachaturyan(object): def __init__(self, elastic_tensor=None, uniform_strain=None, misfit_strain=None): self.C = to_full_rank4(elastic_tensor) self.uniform_strain = uniform_strain if self.uniform_strain is None: self.uniform_strain = np.zeros((3, 3)) if misfit_strain is None: raise ValueError("Misfit strain has to be a 3x3 numpy array!") self.misfit_strain = misfit_strain def zeroth_order_green_function(self, nhat): """Calculate the zeroth order Green function (Fourier representation). The prefactor 1/k^2 is omitted. :param np.ndarray nhat: Unit vector in the reciprocal direction """ Q = np.einsum("m,n,lmnp->lp", nhat, nhat, self.C) return np.linalg.inv(Q) def effective_stress(self): """Calculate the stress resulting from the misfit strain. This only to zeroth order (i.e. effects of different elastic constants of the inclusion and the homogeneous strain is not included) """ return np.einsum("ijkl,kl", self.C, self.misfit_strain) def zeroth_order_integral_pure_python(self, ft): freqs = [] for i in range(len(ft.shape)): freqs.append(np.fft.fftfreq(ft.shape[i])) eff = self.effective_stress() indices = [range(len(f)) for f in freqs] for indx in product(*indices): k = np.array([freqs[i][indx[i]] for i in range(len(freqs))]) if np.allclose(k, 0.0): continue khat = k/np.sqrt(k.dot(k)) G = self.zeroth_order_green_function(khat) val = np.einsum("ik,k,ij,jl,l", eff, khat, G, eff, khat) ft[indx[0], indx[1], indx[2]] *= val return np.sum(ft) def strain_energy_voxels(self, shape_function, pure_python=False): """Calculate the strain energy for the given shape function.""" V = np.sum(shape_function) ft = np.abs(np.fft.fftn(shape_function))**2 ft /= np.prod(ft.shape) if pure_python: integral = self.zeroth_order_integral_pure_python(ft) else: pykhach = PyKhachaturyan(ft, self.C, self.misfit_strain) integral = pykhach.zeroth_order_integral() diff = self.misfit_strain - self.uniform_strain energy = 0.5*np.einsum("ijkl,ij,kl", self.C, diff, diff) return energy - 0.5*integral/V def explore_orientations(self, voxels, theta_ax="y", phi_ax="z", step=5, theta_min=0, theta_max=180, phi_min=0, phi_max=360, fname=None): """Explore orientation dependency of the strain energy. :param np.ndarray voxels: Voxel representation of the geometry :param str theta_ax: Rotation axis for theta angle :param str phi_ax: Rotation axis for phi angle :param int step: Angle change in degress :param int theta_min: Start angle for theta :param int theta_max: End angle for theta :param int phi_min: Start angle for phi :param int phi_max: End angle for phi :param fname str: Filename for storing the output result """ th = list(range(theta_min, theta_max, step)) ph = list(range(phi_min, phi_max, step)) misfit_orig = self.misfit_strain.copy() orig_C = self.C.copy() result = [] now = time.time() status_interval = 30 for ang in product(th, ph): if time.time() - now > status_interval: print("Theta: {}, Phi: {}".format(ang[0], ang[1])) now = time.time() seq = [(theta_ax, -ang[0]), (phi_ax, -ang[1])] matrix = rot_matrix(seq) # Rotate the strain tensor self.misfit_strain = rotate_tensor(misfit_orig, matrix) self.C = rotate_rank4_tensor(orig_C.copy(), matrix) energy = self.strain_energy_voxels(voxels) result.append([ang[0], ang[1], energy]) if fname is None: fname = "khacaturyan_orientaions{}.csv".format(timestamp) np.savetxt(fname, np.array(result), delimiter=",", header= "Theta ({}) deg, Phi ({}) deg, Energy (eV)".format(theta_ax, phi_ax)) print("Results of orientation exploration written to {}".format(fname)) def timestamp(): ts = time.time() return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
[ "numpy.sum", "numpy.allclose", "datetime.datetime.fromtimestamp", "numpy.einsum", "numpy.zeros", "numpy.fft.fftn", "time.time", "cemc.tools.rotate_tensor", "numpy.fft.fftfreq", "numpy.linalg.inv", "cemc_cpp_code.PyKhachaturyan", "numpy.array", "itertools.product", "cemc.tools.to_full_rank4...
[((4671, 4682), 'time.time', 'time.time', ([], {}), '()\n', (4680, 4682), False, 'import time\n'), ((375, 404), 'cemc.tools.to_full_rank4', 'to_full_rank4', (['elastic_tensor'], {}), '(elastic_tensor)\n', (388, 404), False, 'from cemc.tools import to_full_rank4\n'), ((963, 1008), 'numpy.einsum', 'np.einsum', (['"""m,n,lmnp->lp"""', 'nhat', 'nhat', 'self.C'], {}), "('m,n,lmnp->lp', nhat, nhat, self.C)\n", (972, 1008), True, 'import numpy as np\n'), ((1024, 1040), 'numpy.linalg.inv', 'np.linalg.inv', (['Q'], {}), '(Q)\n', (1037, 1040), True, 'import numpy as np\n'), ((1333, 1381), 'numpy.einsum', 'np.einsum', (['"""ijkl,kl"""', 'self.C', 'self.misfit_strain'], {}), "('ijkl,kl', self.C, self.misfit_strain)\n", (1342, 1381), True, 'import numpy as np\n'), ((1656, 1673), 'itertools.product', 'product', (['*indices'], {}), '(*indices)\n', (1663, 1673), False, 'from itertools import product\n'), ((2036, 2046), 'numpy.sum', 'np.sum', (['ft'], {}), '(ft)\n', (2042, 2046), True, 'import numpy as np\n'), ((2203, 2225), 'numpy.sum', 'np.sum', (['shape_function'], {}), '(shape_function)\n', (2209, 2225), True, 'import numpy as np\n'), ((2292, 2309), 'numpy.prod', 'np.prod', (['ft.shape'], {}), '(ft.shape)\n', (2299, 2309), True, 'import numpy as np\n'), ((3697, 3708), 'time.time', 'time.time', ([], {}), '()\n', (3706, 3708), False, 'import time\n'), ((3757, 3772), 'itertools.product', 'product', (['th', 'ph'], {}), '(th, ph)\n', (3764, 3772), False, 'from itertools import product\n'), ((524, 540), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (532, 540), True, 'import numpy as np\n'), ((1763, 1782), 'numpy.allclose', 'np.allclose', (['k', '(0.0)'], {}), '(k, 0.0)\n', (1774, 1782), True, 'import numpy as np\n'), ((1921, 1971), 'numpy.einsum', 'np.einsum', (['"""ik,k,ij,jl,l"""', 'eff', 'khat', 'G', 'eff', 'khat'], {}), "('ik,k,ij,jl,l', eff, khat, G, eff, khat)\n", (1930, 1971), True, 'import numpy as np\n'), ((2437, 2483), 'cemc_cpp_code.PyKhachaturyan', 'PyKhachaturyan', (['ft', 'self.C', 'self.misfit_strain'], {}), '(ft, self.C, self.misfit_strain)\n', (2451, 2483), False, 'from cemc_cpp_code import PyKhachaturyan\n'), ((2617, 2660), 'numpy.einsum', 'np.einsum', (['"""ijkl,ij,kl"""', 'self.C', 'diff', 'diff'], {}), "('ijkl,ij,kl', self.C, diff, diff)\n", (2626, 2660), True, 'import numpy as np\n'), ((4007, 4022), 'cemc.tools.rot_matrix', 'rot_matrix', (['seq'], {}), '(seq)\n', (4017, 4022), False, 'from cemc.tools import rotate_tensor, rot_matrix, rotate_rank4_tensor\n'), ((4096, 4130), 'cemc.tools.rotate_tensor', 'rotate_tensor', (['misfit_orig', 'matrix'], {}), '(misfit_orig, matrix)\n', (4109, 4130), False, 'from cemc.tools import rotate_tensor, rot_matrix, rotate_rank4_tensor\n'), ((4434, 4450), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (4442, 4450), True, 'import numpy as np\n'), ((4694, 4729), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['ts'], {}), '(ts)\n', (4725, 4729), False, 'import datetime\n'), ((1519, 1546), 'numpy.fft.fftfreq', 'np.fft.fftfreq', (['ft.shape[i]'], {}), '(ft.shape[i])\n', (1533, 1546), True, 'import numpy as np\n'), ((2246, 2273), 'numpy.fft.fftn', 'np.fft.fftn', (['shape_function'], {}), '(shape_function)\n', (2257, 2273), True, 'import numpy as np\n'), ((3915, 3926), 'time.time', 'time.time', ([], {}), '()\n', (3924, 3926), False, 'import time\n'), ((3789, 3800), 'time.time', 'time.time', ([], {}), '()\n', (3798, 3800), False, 'import time\n')]
import os import sys BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__))))) sys.path.append(BASE_DIR) import torch import torch.nn as nn from simpleAICV.detection.models import backbones from simpleAICV.detection.models.fpn import Yolov3TinyFPNHead, Yolov3FPNHead __all__ = [ 'darknettiny_yolov3', 'darknet19_yolov3', 'darknet53_yolov3', ] class YOLOV3(nn.Module): def __init__(self, backbone_type, backbone_pretrained_path='', act_type='leakyrelu', per_level_num_anchors=3, num_classes=80): super(YOLOV3, self).__init__() assert backbone_type in [ 'darknettinybackbone', 'darknet19backbone', 'darknet53backbone' ] self.per_level_num_anchors = per_level_num_anchors self.num_classes = num_classes self.backbone = backbones.__dict__[backbone_type](**{ 'pretrained_path': backbone_pretrained_path, 'act_type': act_type, }) if backbone_type == 'darknettinybackbone': self.fpn = Yolov3TinyFPNHead( self.backbone.out_channels, per_level_num_anchors=self.per_level_num_anchors, num_classes=self.num_classes, act_type=act_type) elif backbone_type in ['darknet19backbone', 'darknet53backbone']: self.fpn = Yolov3FPNHead( self.backbone.out_channels, per_level_num_anchors=self.per_level_num_anchors, num_classes=self.num_classes, act_type=act_type) def forward(self, inputs): features = self.backbone(inputs) del inputs features = self.fpn(features) obj_reg_cls_heads = [] for feature in features: # feature shape:[B,H,W,3,85] # obj_head:feature[:, :, :, :, 0:1], shape:[B,H,W,3,1] # reg_head:feature[:, :, :, :, 1:5], shape:[B,H,W,3,4] # cls_head:feature[:, :, :, :, 5:], shape:[B,H,W,3,80] obj_reg_cls_heads.append(feature) del features # if input size:[B,3,416,416] # features shape:[[B, 255, 52, 52],[B, 255, 26, 26],[B, 255, 13, 13]] # obj_reg_cls_heads shape:[[B, 52, 52, 3, 85],[B, 26, 26, 3, 85],[B, 13, 13, 3, 85]] return [obj_reg_cls_heads] def _yolov3(backbone_type, backbone_pretrained_path, **kwargs): model = YOLOV3(backbone_type, backbone_pretrained_path=backbone_pretrained_path, **kwargs) return model def darknettiny_yolov3(backbone_pretrained_path='', **kwargs): return _yolov3('darknettinybackbone', backbone_pretrained_path=backbone_pretrained_path, **kwargs) def darknet19_yolov3(backbone_pretrained_path='', **kwargs): return _yolov3('darknet19backbone', backbone_pretrained_path=backbone_pretrained_path, **kwargs) def darknet53_yolov3(backbone_pretrained_path='', **kwargs): return _yolov3('darknet53backbone', backbone_pretrained_path=backbone_pretrained_path, **kwargs) if __name__ == '__main__': import os import random import numpy as np import torch seed = 0 # for hash os.environ['PYTHONHASHSEED'] = str(seed) # for python and numpy random.seed(seed) np.random.seed(seed) # for cpu gpu torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) net = darknettiny_yolov3() image_h, image_w = 640, 640 from thop import profile from thop import clever_format macs, params = profile(net, inputs=(torch.randn(1, 3, image_h, image_w), ), verbose=False) macs, params = clever_format([macs, params], '%.3f') print(f'1111, macs: {macs}, params: {params}') outs = net(torch.autograd.Variable(torch.randn(8, 3, image_h, image_w))) for out in outs: for per_level_out in out: print('2222', per_level_out.shape) net = darknet53_yolov3() image_h, image_w = 640, 640 from thop import profile from thop import clever_format macs, params = profile(net, inputs=(torch.randn(1, 3, image_h, image_w), ), verbose=False) macs, params = clever_format([macs, params], '%.3f') print(f'1111, macs: {macs}, params: {params}') outs = net(torch.autograd.Variable(torch.randn(8, 3, image_h, image_w))) for out in outs: for per_level_out in out: print('2222', per_level_out.shape)
[ "sys.path.append", "os.path.abspath", "numpy.random.seed", "simpleAICV.detection.models.fpn.Yolov3TinyFPNHead", "torch.manual_seed", "simpleAICV.detection.models.fpn.Yolov3FPNHead", "torch.cuda.manual_seed", "torch.randn", "thop.clever_format", "torch.cuda.manual_seed_all", "random.seed" ]
[((141, 166), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (156, 166), False, 'import sys\n'), ((3460, 3477), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (3471, 3477), False, 'import random\n'), ((3482, 3502), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3496, 3502), True, 'import numpy as np\n'), ((3525, 3548), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (3542, 3548), False, 'import torch\n'), ((3553, 3581), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (3575, 3581), False, 'import torch\n'), ((3586, 3618), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (3612, 3618), False, 'import torch\n'), ((3915, 3952), 'thop.clever_format', 'clever_format', (['[macs, params]', '"""%.3f"""'], {}), "([macs, params], '%.3f')\n", (3928, 3952), False, 'from thop import clever_format\n'), ((4477, 4514), 'thop.clever_format', 'clever_format', (['[macs, params]', '"""%.3f"""'], {}), "([macs, params], '%.3f')\n", (4490, 4514), False, 'from thop import clever_format\n'), ((1161, 1310), 'simpleAICV.detection.models.fpn.Yolov3TinyFPNHead', 'Yolov3TinyFPNHead', (['self.backbone.out_channels'], {'per_level_num_anchors': 'self.per_level_num_anchors', 'num_classes': 'self.num_classes', 'act_type': 'act_type'}), '(self.backbone.out_channels, per_level_num_anchors=self.\n per_level_num_anchors, num_classes=self.num_classes, act_type=act_type)\n', (1178, 1310), False, 'from simpleAICV.detection.models.fpn import Yolov3TinyFPNHead, Yolov3FPNHead\n'), ((4043, 4078), 'torch.randn', 'torch.randn', (['(8)', '(3)', 'image_h', 'image_w'], {}), '(8, 3, image_h, image_w)\n', (4054, 4078), False, 'import torch\n'), ((4605, 4640), 'torch.randn', 'torch.randn', (['(8)', '(3)', 'image_h', 'image_w'], {}), '(8, 3, image_h, image_w)\n', (4616, 4640), False, 'import torch\n'), ((111, 136), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (126, 136), False, 'import os\n'), ((1468, 1613), 'simpleAICV.detection.models.fpn.Yolov3FPNHead', 'Yolov3FPNHead', (['self.backbone.out_channels'], {'per_level_num_anchors': 'self.per_level_num_anchors', 'num_classes': 'self.num_classes', 'act_type': 'act_type'}), '(self.backbone.out_channels, per_level_num_anchors=self.\n per_level_num_anchors, num_classes=self.num_classes, act_type=act_type)\n', (1481, 1613), False, 'from simpleAICV.detection.models.fpn import Yolov3TinyFPNHead, Yolov3FPNHead\n'), ((3814, 3849), 'torch.randn', 'torch.randn', (['(1)', '(3)', 'image_h', 'image_w'], {}), '(1, 3, image_h, image_w)\n', (3825, 3849), False, 'import torch\n'), ((4376, 4411), 'torch.randn', 'torch.randn', (['(1)', '(3)', 'image_h', 'image_w'], {}), '(1, 3, image_h, image_w)\n', (4387, 4411), False, 'import torch\n')]
# -*- coding: utf-8 -*- import os import os.path import numpy as np from PIL import Image import torch from torch.utils.data import DataLoader from torchvision import transforms class MNIST(torch.utils.data.Dataset): """`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset. Args: examples (list: [(img, target)...] ) """ training_file = 'training.pt' test_file = 'test.pt' classes = ['0 - zero', '1 - one', '2 - two', '3 - three', '4 - four', '5 - five', '6 - six', '7 - seven', '8 - eight', '9 - nine'] def __init__(self, examples, transform=None, target_transform=None): self.examples = examples self.transform = transform self.target_transform = target_transform def __getitem__(self, index): """ Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ img, target = self.examples[index] target = int(target) # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img, mode='L') if self.transform is not None: img = self.transform(img) if self.target_transform is not None: target = self.target_transform(target) return img, target def __len__(self): return len(self.examples) @property def class_to_idx(self): return {_class: i for i, _class in enumerate(self.classes)} class MNISTData(): """ MNIST allocator. """ training_file = 'training.pt' test_file = 'test.pt' classes = ['0 - zero', '1 - one', '2 - two', '3 - three', '4 - four', '5 - five', '6 - six', '7 - seven', '8 - eight', '9 - nine'] def __init__(self, client_num, sample_rate=-1, data_sharing=False): data_dir = 'dataset/mnist' self.root = os.path.expanduser(data_dir) if not self._check_exists(): print(self.root) raise RuntimeError('Dataset not found.') self.train_dict, total_train = self._read_file(self.training_file) self.test_dict, total_test = self._read_file(self.test_file) self.data_sharing = data_sharing if not 0 < sample_rate <= 1: sample_rate = 1 np.random.shuffle(total_train) np.random.shuffle(total_test) self.share_train = total_train[:int(sample_rate * len(total_train))] self.share_test = total_test[:int(sample_rate * len(total_test))] self.num_local_train = len(total_train) // client_num self.num_local_test = len(total_test) // client_num normalize = transforms.Normalize(mean=[0.131], std=[0.308]) self.train_transform = transforms.Compose([ transforms.RandomResizedCrop(28), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize ]) self.test_transform = transforms.Compose([ transforms.ToTensor(), normalize ]) def create_dataset_for_center(self, batch_size, num_workers): _train_set = MNIST(self.share_train, self.train_transform) _test_set = MNIST(self.share_test, self.test_transform) train_loader = DataLoader(_train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True) test_loader = DataLoader(_test_set, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) return train_loader, test_loader, len(_train_set) def create_dataset_for_client(self, distribution, batch_size, num_workers, subset=tuple(range(10))): """ subset: construct local data set with certain label(s). distribution: the distribution (of label space) to construct local data set. """ distribution = np.asarray(distribution) / np.sum(distribution) def sample_data(data_dict, local_num): local_data = list() for i, p in enumerate(distribution): snum = int(local_num * p) indices = np.random.choice(len(data_dict[i]), snum, replace=False) local_data.extend([(k, i) for k in data_dict[i][indices]]) return local_data local_train, local_test = list(), list() if len(subset) < 10: for i in subset: local_train.extend([(k, i) for k in self.train_dict[i]]) local_test.extend([(k, i) for k in self.test_dict[i]]) else: local_train = sample_data(self.train_dict, self.num_local_train) local_test = sample_data(self.test_dict, self.num_local_test) if self.data_sharing: local_train.extend(self.share_train) local_test.extend(self.share_test) _train_set = MNIST(local_train, self.train_transform) _test_set = MNIST(local_test, self.test_transform) train_loader = DataLoader(_train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True) test_loader = DataLoader(_test_set, batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) return train_loader, test_loader, len(local_train) @property def processed_folder(self): return os.path.join(self.root, 'processed') def _check_exists(self): return os.path.exists(os.path.join(self.processed_folder, self.training_file)) and \ os.path.exists(os.path.join(self.processed_folder, self.test_file)) def _read_file(self, data_file): """ return: data: (dict: {label: array[images, ...]} ) total_data: (list [(image, label), ...] ) """ data = {i: [] for i in range(10)} total_data, total_targets = torch.load(os.path.join(self.processed_folder, data_file)) total_data = [x.numpy() for x in total_data] for k, v in zip(total_data, total_targets): data[int(v)].append(k) for k, v in data.items(): data[k] = np.asarray(v) return data, list(zip(total_data, total_targets)) if __name__ == "__main__": pass
[ "numpy.sum", "os.path.join", "torch.utils.data.DataLoader", "torchvision.transforms.RandomHorizontalFlip", "numpy.asarray", "torchvision.transforms.RandomResizedCrop", "PIL.Image.fromarray", "torchvision.transforms.Normalize", "os.path.expanduser", "numpy.random.shuffle", "torchvision.transforms...
[((1133, 1163), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {'mode': '"""L"""'}), "(img, mode='L')\n", (1148, 1163), False, 'from PIL import Image\n'), ((1933, 1961), 'os.path.expanduser', 'os.path.expanduser', (['data_dir'], {}), '(data_dir)\n', (1951, 1961), False, 'import os\n'), ((2342, 2372), 'numpy.random.shuffle', 'np.random.shuffle', (['total_train'], {}), '(total_train)\n', (2359, 2372), True, 'import numpy as np\n'), ((2381, 2410), 'numpy.random.shuffle', 'np.random.shuffle', (['total_test'], {}), '(total_test)\n', (2398, 2410), True, 'import numpy as np\n'), ((2706, 2753), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.131]', 'std': '[0.308]'}), '(mean=[0.131], std=[0.308])\n', (2726, 2753), False, 'from torchvision import transforms\n'), ((3307, 3413), 'torch.utils.data.DataLoader', 'DataLoader', (['_train_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(_train_set, batch_size=batch_size, shuffle=True, num_workers=\n num_workers, pin_memory=True)\n', (3317, 3413), False, 'from torch.utils.data import DataLoader\n'), ((3465, 3571), 'torch.utils.data.DataLoader', 'DataLoader', (['_test_set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(_test_set, batch_size=batch_size, shuffle=False, num_workers=\n num_workers, pin_memory=True)\n', (3475, 3571), False, 'from torch.utils.data import DataLoader\n'), ((5056, 5162), 'torch.utils.data.DataLoader', 'DataLoader', (['_train_set'], {'batch_size': 'batch_size', 'shuffle': '(True)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(_train_set, batch_size=batch_size, shuffle=True, num_workers=\n num_workers, pin_memory=True)\n', (5066, 5162), False, 'from torch.utils.data import DataLoader\n'), ((5214, 5320), 'torch.utils.data.DataLoader', 'DataLoader', (['_test_set'], {'batch_size': 'batch_size', 'shuffle': '(False)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(_test_set, batch_size=batch_size, shuffle=False, num_workers=\n num_workers, pin_memory=True)\n', (5224, 5320), False, 'from torch.utils.data import DataLoader\n'), ((5470, 5506), 'os.path.join', 'os.path.join', (['self.root', '"""processed"""'], {}), "(self.root, 'processed')\n", (5482, 5506), False, 'import os\n'), ((3960, 3984), 'numpy.asarray', 'np.asarray', (['distribution'], {}), '(distribution)\n', (3970, 3984), True, 'import numpy as np\n'), ((3987, 4007), 'numpy.sum', 'np.sum', (['distribution'], {}), '(distribution)\n', (3993, 4007), True, 'import numpy as np\n'), ((5986, 6032), 'os.path.join', 'os.path.join', (['self.processed_folder', 'data_file'], {}), '(self.processed_folder, data_file)\n', (5998, 6032), False, 'import os\n'), ((6230, 6243), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (6240, 6243), True, 'import numpy as np\n'), ((2818, 2850), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(28)'], {}), '(28)\n', (2846, 2850), False, 'from torchvision import transforms\n'), ((2864, 2897), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (2895, 2897), False, 'from torchvision import transforms\n'), ((2911, 2932), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2930, 2932), False, 'from torchvision import transforms\n'), ((3030, 3051), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3049, 3051), False, 'from torchvision import transforms\n'), ((5567, 5622), 'os.path.join', 'os.path.join', (['self.processed_folder', 'self.training_file'], {}), '(self.processed_folder, self.training_file)\n', (5579, 5622), False, 'import os\n'), ((5657, 5708), 'os.path.join', 'os.path.join', (['self.processed_folder', 'self.test_file'], {}), '(self.processed_folder, self.test_file)\n', (5669, 5708), False, 'import os\n')]
""" cytometer/data.py Functions to load, save and pre-process data related to the cytometer project. Environments: cytometer_tensorflow, cytometer_tensorflow_v2. """ """ This file is part of Cytometer Copyright 2021 Medical Research Council SPDX-License-Identifier: Apache-2.0 Author: <NAME> <<EMAIL>> """ import os import shutil import glob import warnings import pickle import ujson import time from PIL import Image import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np import scipy from scipy import ndimage import scipy.stats import pandas as pd import ast from mahotas import bwperim import pysto.imgproc as pystoim import re import six from svgpathtools import svg2paths import random import colorsys from shapely.geometry import Polygon import pyvips import aicsimageio from aicsimageio.readers.czi_reader import CziReader DEBUG = False def split_images(x, nblocks): """ Splits the rows and columns of a data array with shape (n, rows, cols, channels) into blocks. If necessary, the array is trimmed off so that all blocks have the same size. :param x: numpy.ndarray (images, rows, cols, channels). :param nblocks: scalar with the number of blocks to split the rows and columns into. :return: numpy.ndarray with x split into blocks. """ # compute how many whole blocks fit in the data, and what length of the image they cover _, nrows, ncols, _ = x.shape nrows = int(np.floor(nrows / nblocks) * nblocks) ncols = int(np.floor(ncols / nblocks) * nblocks) # remove the extra bit of the images so that we can split them into equal blocks x = x[:, 0:nrows, 0:ncols, :] # split images into smaller blocks _, x, _ = pystoim.block_split(x, nblocks=(1, nblocks, nblocks, 1), by_reference=True) x = np.concatenate(x, axis=0) return x def split_list(x, idx): """ Split a list into two sublists. :param x: list to be split. :param idx: list of indices. Repeated indices are ignored. :return: x[idx], x[~idx]. Here ~idx stands for the indices not in idx. """ # ignore repeated indices idx = set(idx) # indices for the second sublist idx_2 = list(set(range(len(x))) - idx) idx = list(idx) return list(np.array(x)[idx]), list(np.array(x)[idx_2]) def split_file_list_kfolds(file_list, n_folds, ignore_str='', fold_seed=0, save_filename=None): """ Split file list into k-folds for training and testing a neural network. If there are N files, each fold gets N/k files for testing, and N*(k-1)/k files for training. If N is not divisible by k, the split follows the rules of numpy.array_split(). :param file_list: List of filenames. :param n_folds: Number of folds to split the list into. :param ignore_str: (def '') String. This substring will be ignored when making a list of files to be shuffled. The string format is the one you'd use in re.sub(ignore_str, '', file_list[i]). This is useful if you have several files from the same histology slice, but you want to make sure that the network tests run with data from histology slices that haven't been seen at training. For example, histo_01_win_01.ndpi histo_01_win_02.ndpi histo_02_win_01.ndpi histo_02_win_02.ndpi Using ignore_str='_win_.*' will reduce the file list to histo_01 histo_02 Thus, both files from histo_01 will be assigned together either to the train or test sets. :param fold_seed: Scalar. Seed for the pseudo-random number generator to shuffle the file indices. :param save_filename: (def None). If provided, save results to pickle file (*.pickle). * 'file_list' * 'idx_train' * 'idx_test' * 'fold_seed' :return: * idx_train: list of 1D arrays. idx_train[i] are the train indices for training files in the ith-fold. * idx_test: list of 1D arrays. idx_train[i] are the train indices for test files in the ith-fold. """ # starting file list # # im_1_row_4.ndpi # im_2_row_8.ndpi # im_1_row_2.ndpi # im_2_row_3.ndpi # im_1_row_1.ndpi # create second file list removing the ignore_from* substring # # im_1 # im_2 # im_1 # im_2 # im_1 file_list_reduced = [re.sub(ignore_str, '', x) for x in file_list] # create third file list, without duplicates # # im_1 # im_2 file_list_unique = np.unique(file_list_reduced) # look up table (LUT) to map back to the full list # # [[0, 2, 4], [1, 3]] file_list_lut = [] for i, f in enumerate(file_list_unique): file_list_lut.append(np.array([j for j, f_all in enumerate(file_list_reduced) if f == f_all])) file_list_lut = np.array(file_list_lut) # number of reduced files n_file = len(file_list_unique) # split data into training and testing for k-folds. # Here the indices refer to file_list_unique # # idx_train_all = [[0]] # im_1 # idx_test_all = [[1]] # im_2 random.seed(fold_seed) idx_unique = random.sample(range(n_file), n_file) idx_test_all = np.array_split(idx_unique, n_folds) idx_train_all = [] for k_fold in range(n_folds): # test and training image indices idx_test = idx_test_all[k_fold] idx_train = list(set(idx_unique) - set(idx_test)) random.shuffle(idx_train) idx_train_all.append(np.array(idx_train)) # map reduced indices to full list # Here we change the indices to refer to file_list # # idx_train_all = [[0, 2, 4]] # im_1_* # idx_test_all = [[1, 3]] # im_2_* for i, idx_train in enumerate(idx_train_all): # loop folds # file_list indices idx = np.concatenate(file_list_lut[idx_train]) idx_train_all[i] = idx for i, idx_test in enumerate(idx_test_all): # loop folds # file_list indices idx = np.concatenate(file_list_lut[idx_test]) idx_test_all[i] = idx # check that there's no overlap between training and test datasets, and that each fold contains # all the images for i, idx_train in enumerate(idx_train_all): assert(set(idx_train).intersection(idx_test_all[i]) == set()) assert (len(np.concatenate((idx_test_all[i], idx_train))) == len(file_list)) if save_filename is not None: with open(save_filename, 'wb') as f: x = {'file_list': file_list, 'idx_train': idx_train_all, 'idx_test': idx_test_all, 'fold_seed': fold_seed} pickle.dump(x, f, pickle.HIGHEST_PROTOCOL) return idx_train_all, idx_test_all def change_home_directory(file_list, home_path_from, home_path_to, check_isfile=False): """ Change the home directory in a list of file paths and names. Optionally, it checks that the new paths exist in the system. For example, change_home_directory(file_list, '/home/foo', '/users/project/jsmith') converts the list file_list = ['/home/foo/data/file1.txt', '/home/foo/results/file2.txt'] to ['/users/project/jsmith/data/file1.txt', '/users/project/jsmith/results/file2.txt'] :param file_list: list of strings with file paths and names, all with the same path directory. :param home_path_from: string at the beginning of each path that will be replaced. :param home_path_to: string with the new home directory. :param check_isfile: (def False) check whether files with the new home directory exist. :return: """ if not isinstance(file_list, list): file_list = [file_list] p = re.compile('^' + home_path_from + '[' + os.path.sep + ']') for i, file in enumerate(file_list): file_without_home = p.sub('', file) file_list[i] = os.path.join(home_path_to, file_without_home) if check_isfile and not os.path.isfile(file_list[i]): raise FileExistsError(file_list[i]) return file_list def augment_file_list(file_list, tag_from, tag_to): """ Replace a tag in the filenames of a list, with another tag, and search for files with the new names. This is useful to add filenames of augmented data. For example, if you start with im_file_1_nan.tif im_file_2_nan.tif im_file_3_nan.tif and run augment_file_list(file_list, '_nan_', '_*_'), the new file list will contain filenames of exisiting files that correspond to im_file_1_*.tif im_file_2_*.tif im_file_3_*.tif :param file_list: list of filenames. :param tag_from: The tag that will be replaced for the file search. The tag will only be replaced in file names, not in file paths. :param tag_to: The tag that will replace tag_from in the file search. :return: a new file list that includes the files that match the filenames with the new tags. """ file_list_out = [] for file in file_list: # split the filename into the path and the file name itself file_path, file_basename = os.path.split(file) # replace the tag by the other tag, e.g. '_*_' file_basename = file_basename.replace(tag_from, tag_to) # search for files with the new tag file_list_out += glob.glob(os.path.join(file_path, file_basename)) return file_list_out def load_file_list_to_array(file_list): """ Loads a list of images, all with the same size, into a numpy array (file, row, col, channel). :param file_list: list of strings with filenames. :return: numpy.ndarray. """ if not isinstance(file_list, list): raise ValueError('file_list must be a list') if len(file_list) == 0: return np.empty((1, 0)) # load first image to get the image size im0 = np.array(Image.open(file_list[0])) # allocate memory for the output im_out = np.zeros(shape=(len(file_list),) + im0.shape, dtype=im0.dtype) # read files and copy them to output array for i, file in enumerate(file_list): im_out[i, ...] = np.array(Image.open(file)) if DEBUG: plt.clf() plt.imshow(im_out[i, ...]) # one channel data gets loaded as im_out.shape=(n, rows, cols), but keras requires (n, rows, cols, 1) if im_out.ndim == 3: im_out = im_out.reshape(im_out.shape + (1,)) return im_out def load_datasets(file_list, prefix_from='im', prefix_to=[], nblocks=1, shuffle_seed=None): """ Loads image files and prepare them for training or testing, returning numpy.ndarrays. Image files can be of any type loadable by the PIL module, but they must have the same size. Multiple sets of corresponding images can be loaded using prefix_to. For instance, im_file_1.tif seg_file_1.tif mask_file_1.tif im_file_2.tif seg_file_2.tif mask_file_2.tif im_file_3.tif seg_file_3.tif mask_file_3.tif will return outs['im'] --> numpy.ndarray (3, rows, cols, channels) outs['seg'] --> numpy.ndarray (3, rows, cols, channels) outs['mask'] --> numpy.ndarray (3, rows, cols, channels) This function also provides the following optional functionality: * images can be split into equally-sized blocks (this is useful when full images are too large for training). * images can be shuffled randomly. :param file_list: list of paths and filenames (for one of the datasets). :param prefix_from: (def 'im') string with the prefix (e.g. 'im') in file_list that when changed gives the other datasets. Note that the prefix refers to the name of the file, not its path. :param prefix_to: (def []) list of strings with the prefixes of the datasets that will be loaded. E.g. ['im', 'mask'] will load the datasets from the filenames that start with 'im' and 'mask'. :param nblocks: (def 1) number of equi-sized blocks to split the images into. Note that the edges of the images may need to be trimmed so that splitting creates blocks with the same size. :param shuffle_seed: (def None) If provided, images are shuffled after splitting. :return: out, out_file_list, shuffle_idx: * out: dictionary where out[prefix] contains a numpy.ndarray with the data corresponding to the "prefix" dataset. * out_file_list: list of the filenames for the out[prefix] dataset. * shuffle_idx: list of indices used to shuffle the images after splitting. """ if not isinstance(prefix_to, list): raise TypeError('data_prefixes must be a list of strings') # using prefixes, get list of filenames for the different datasets out_file_list = {} for prefix in prefix_to: out_file_list[prefix] = [] for x in file_list: x_path, x_basename = os.path.split(x) if re.match('^' + prefix_from, x_basename) is None: raise ValueError('Prefix not found in filename: ' + x) prefix_file = os.path.join(x_path, re.sub('^' + prefix_from, prefix, x_basename, count=1)) if not os.path.isfile(prefix_file): raise FileExistsError(prefix_file) out_file_list[prefix].append(prefix_file) # load all datasets out = {} shuffle_idx = {} for prefix in prefix_to: # load dataset out[prefix] = load_file_list_to_array(out_file_list[prefix]) # data type conversions if prefix == 'im' and out[prefix].dtype == 'uint8': out[prefix] = out[prefix].astype(np.float32) out[prefix] /= 255 elif prefix in {'mask', 'dmap'}: out[prefix] = out[prefix].astype(np.float32) elif prefix == 'seg': out[prefix] = out[prefix].astype(np.uint8) # split image into smaller blocks, if requested if nblocks > 1: out[prefix] = split_images(out[prefix], nblocks=nblocks) # create shuffling indices if required if prefix == prefix_to[0] and shuffle_seed is not None: n = out[prefix].shape[0] # number of images shuffle_idx = np.arange(n) np.random.seed(shuffle_seed) np.random.shuffle(shuffle_idx) # shuffle data if shuffle_seed is not None: out[prefix] = out[prefix][shuffle_idx, ...] if DEBUG: i = 5 plt.clf() for pi, prefix in enumerate(prefix_to): plt.subplot(1, len(prefix_to), pi+1) if out[prefix].shape[-1] == 1: plt.imshow(out[prefix][i, :, :, 0]) else: plt.imshow(out[prefix][i, :, :, :]) plt.title('out[' + prefix + ']') return out, out_file_list, shuffle_idx def remove_poor_data(datasets, prefix='mask', threshold=1000): """ Find images where the mask has very few pixels, and remove them from the datasets. Training with them can decrease the performance of the model. :param datasets: dictionary with numpy.ndarray datasets loaded with load_datasets(). :param prefix: (def 'mask') string. The number of pixels will be assessed in datasets[prefix]. :param threshold: (def 1000) integer. Masks :return: """ # indices of masks with a large enough number of pixels==1 idx = np.count_nonzero(datasets[prefix], axis=(1, 2, 3)) > threshold # remove corresponding images from all datasets for prefix in datasets.keys(): datasets[prefix] = datasets[prefix][idx, ...] return datasets def load_watershed_seg_and_compute_dmap(seg_file_list, background_label=1): """ Loads a list of segmentation files and computes distance maps to the objects boundaries/background. The segmentation file is assumed to have one integer label (2, 3, 4, ...) per object. The background has label 1. The boundaries between objects have label 0 (if boundaries exist). Those boundaries==0 are important for this function, because distance maps are computed as the distance of any pixel to the closest pixel=0. As an example, the watershed method will produce boundaries==0 when expanding segmentation labels. :param seg_file_list: list of paths to the files with segmentations, in any format that PIL can load :param background_label: label that will be considered to correspond to the background and not an object :return: (dmap, mask, seg) dmap: np.array with one distance map per segmentation file. It provides the Euclidean distance of each pixel to the closest background/boundary pixel. mask: np.array with one segmentation mask per file. Background pixels = 0. Foreground/boundary pixels = 1. seg: np.array with one segmentation per file. The segmentation labels in the input files. """ if not isinstance(seg_file_list, list): raise ValueError('seg_file_list must be a list') if len(seg_file_list) == 0: return np.empty((1, 0)), np.empty((1, 0)), np.empty((1, 0)) # get size of first segmentation. All segmentations must have the same size seg0 = Image.open(seg_file_list[0]) seg0_dtype = np.array(seg0).dtype # allocate memory for outputs seg = np.zeros(shape=(len(seg_file_list), seg0.height, seg0.width), dtype=seg0_dtype) mask = np.zeros(shape=(len(seg_file_list), seg0.height, seg0.width), dtype='float32') # these will be used as weights dmap = np.zeros(shape=(len(seg_file_list), seg0.height, seg0.width), dtype='float32') # loop segmented files for i, seg_file in enumerate(seg_file_list): # load segmentation seg_aux = np.array(Image.open(seg_file)) # watershed only labels contours between pairs of cells, not where the cell touches the background. # Thus, we compute the missing part of the contours between cells and background im_background = seg_aux == 1 # background points in the labels im_background = bwperim(im_background, n=8, mode='ignore') # perimeter of background areas im_background[0:2, :] = 0 # remove perimeter artifact on the borders of the image im_background[-2:, :] = 0 im_background[:, 0:2] = 0 im_background[:, -2:] = 0 seg_aux[im_background.astype(np.bool)] = 0 # add background contours to segmentation # copy segmentation slice to output seg[i, :, :] = seg_aux # the mask is 0 where we have background pixels, and 1 everywhere else (foreground) mask[i, :, :] = seg_aux != background_label # add the background pixels to the boundaries seg_aux[seg_aux == background_label] = 0 # plot image if DEBUG: plt.clf() plt.subplot(221) plt.imshow(seg_aux, cmap="gray") plt.title('Cell labels') plt.subplot(222) plt.imshow(mask[i, :, :], cmap="gray") plt.title('Training weight') # compute distance map from every pixel to the closest boundary dmap[i, :, :] = ndimage.distance_transform_edt(seg_aux) # plot distance map if DEBUG: plt.subplot(223) plt.imshow(dmap[i, :, :]) plt.title('Distance map') # add a dummy channel dimension to comply with Keras format mask = mask.reshape((mask.shape + (1,))) seg = seg.reshape((seg.shape + (1,))) dmap = dmap.reshape((dmap.shape + (1,))) return dmap, mask, seg def read_paths_from_svg_file(file, tag='Cell', add_offset_from_filename=False, minimum_npoints=3): """ Read a SVG file produced by Gimp that contains paths (contours), and return a list of paths, where each path is a list of (X,Y) point coordinates. Only paths that have a label that starts with the chosen tag are read. This allows having different types of objects in the SVG file (e.g. cells, edge cells, background, etc), but only read one type of objects. :param file: path and name of SVG file. :param tag: (def 'Cell'). Only paths with a label that starts with this tag will be read. The case (upper/lowercase) is ignored. :param add_offset_from_filename: (def False) :param minimum_npoints: (def 3) Contours with less than this number of points will be ignored. :return: [ path0, path1, ...] = [ [(X0,Y0), (X1,Y1), ...], ...] """ # convert tag to lowercase, to avoid differentiating between "Cell" and "cell" tag = tag.lower() # extract contour as a list of (X,Y) coordinates def extract_contour(path, x_offset=0, y_offset=0): contour = [] for pt in path: # (X, Y) for each point contour.append((np.real(pt.start) + x_offset, np.imag(pt.start) + y_offset)) if DEBUG: plt.plot(*zip(*contour)) return contour # extract all paths from the SVG file paths, attributes = svg2paths(file) # add offset to point coordinates from the file name if add_offset_from_filename: file_basename = os.path.basename(file) # remove path from filename file_basename, _ = os.path.splitext(file_basename) # remove extension file_basename = file_basename.split('_') row_i = file_basename.index('row') y_offset = float(file_basename[row_i + 1]) col_i = file_basename.index('col') x_offset = float(file_basename[col_i + 1]) else: x_offset = 0 y_offset = 0 # loop paths paths_out = [] for path, attribute in zip(paths, attributes): # convert the name of the object to lowercase, to avoid differentiating between "Cell" and "cell" attribute_id = attribute['id'].lower() # skip if the contour's name doesn't start with the required tag, e.g. 'Cell' if not attribute_id.startswith(tag): continue # extract contour polygon from the path object contour = extract_contour(path, x_offset=x_offset, y_offset=y_offset) # if the contour has enough points, append to the output if len(contour) >= minimum_npoints: paths_out.append(contour) return paths_out def area2quantile(areas, quantiles=np.linspace(0.0, 1.0, 101)): """ Return function to map from cell areas to quantiles. :param areas: Vector with random sample that is representative of area values in the population. The probability distribution and quantiles are computed from this random sample. :param quantiles: (def np.linspace(0.0, 1.0, 101)) Quantiles values in [0.0, 1.0] at which the function will be linearly interpolated. :return: * f: scipy.interpolate.interpolate.interp1d interpolation function that maps areas values to [0.0, 1.0]. Area values outside the range are mapped to 0.0 (smaller) or 1.0 (larger). """ areas_by_quantiles = scipy.stats.mstats.hdquantiles(areas, prob=quantiles) f_area2quantile = scipy.interpolate.interp1d(areas_by_quantiles.data, quantiles, bounds_error=False, fill_value=(0.0, 1.0)) if DEBUG: plt.clf() fig = plt.hist(areas, bins=50, density=True, histtype='step') for x in areas_by_quantiles.data: plt.plot([x, x], [0, fig[0].max()], 'k') return f_area2quantile def aida_colourmap(): """ Create a colourmap that replicates in plt.imshow() the colours that we obtain in AIDA. This colormap is called 'quantiles_aida'. This colourmap is meant to map area quantiles [0.0, 1.0] to a pastel yellow-green-purple colour scale. This function can be combined with area2quantile() to map areas to colours: import cytometer # variables already assigned manual_areas # vector with a representative random sample of cell areas. The distribution will be computed from these values area_grid # np.float32 2D array with area values interpolated onto a pixel grid area_mask # bool array of the same size that says where there's tissue and where not # compute function to map between cell areas and [0.0, 1.0] f_area2quantile = cytometer.data.area2quantile(manual_areas) # convert area values to quantiles quantiles_grid = f_area2quantile(quantiles_grid) # make background white in the plot quantiles_grid[~areas_mask] = np.nan # load AIDA's colourmap cm = cytometer.data.aida_colourmap() # plot plt.imshow(quantiles_grid, vmin=0.0, vmax=1.0, cmap=cm) :return: * cm: matplotlib.colors.ListedColormap with 101 colours. """ # range of colours in HSL format hue = np.linspace(0, 315 / 360, 101) lightness = 0.69 saturation = 0.44 alpha = 1 # the colourmap only changes the hue linearly, while keeping the saturation and lightness constant cm = [colorsys.hls_to_rgb(h=h, l=lightness, s=saturation) + (alpha,) for h in hue] return ListedColormap(cm, name='quantiles_aida') def aida_contour_items(contours, f_area2quantile, cm='quantiles_aida', xres=1.0, yres=1.0, cell_prob=None): """ Create list of contour items for AIDA. This function computes the area of each contour, it's quantile, and maps it to a colour. :param contours: List [contour_0, contour_1...], where contour_i is an (Ni, 2)-np.array with Ni 2D points. :param f_area2quantile: Function to map areas to quantiles. Compute with cytometer.data.area2quantile(manual_areas). :param cm: (def 'quantiles_aida'). String or matplotlib.colors.ListedColormap to map [0.0, 1.0] to RGB colours. If cm is a string, currently only 'quantiles_aida' is accepted. :param xres: (def 1.0) Pixel size in the x-coordinate. :param yres: (def 1.0) Pixel size in the y-coordinate. :param cell_prob: (def None) Vector with one value per contour. This value is interpreted as the probability of the object being a cell. :return: List of dictionaries, each one with the structure of a contour object. """ def aida_contour_item(contour, rgb_colour, cell_prob=None): """ Create an object that describes a closed contour in AIDA. The user provides the coordinates of the contour points and the colour for the contour. :param contour: np.array or list of points of a contour: [[x0, y0], [x1, y1], ...] :param rgb_colour: (r, g, b) or (r, g, b, alpha). RGB colour for this contour. :param cell_prob: (def None) Scalar in [0.0, 1.0] with the probability of the contour being a cell. :return: item: dictionary with the structure of the contour object. """ if type(contour) != 'numpy.ndarray': contour = list(contour) # convert RGB to HSL hls_colour = colorsys.rgb_to_hls(rgb_colour[0], rgb_colour[1], rgb_colour[2]) # create the item object item = { 'class': '', 'type': 'path', 'color': { 'fill': { 'hue': hls_colour[0] * 360, 'saturation': hls_colour[2], 'lightness': hls_colour[1], 'alpha': 0.7 }, 'stroke': { 'hue': hls_colour[0] * 360, 'saturation': hls_colour[2], 'lightness': hls_colour[1], 'alpha': 1.0 } }, 'segments': [list(x) for x in contour], 'closed': True } if cell_prob is not None: item['cell_prob'] = cell_prob return item ## main function # load colourmap if cm == 'quantiles_aida': cm = aida_colourmap() else: raise ValueError('Only quantiles_aida colourmap is implemented') # compute area of each contour areas = [Polygon(c).area * xres * yres for c in contours] # (um^2) # convert to quantiles q = f_area2quantile(areas) # create the list of contour objects (each item is a contour object) if cell_prob is None: items = [aida_contour_item(contour=contours[i], rgb_colour=cm(q[i])) for i in range(len(contours))] else: items = [aida_contour_item(contour=contours[i], rgb_colour=cm(q[i]), cell_prob=cell_prob[i]) for i in range(len(contours))] return items def aida_rectangle_items(rectangles): """ Create list of rectangle items for AIDA. :param rectangles: List [rectangle_0, rectangle_1...], where rectangle_i is a tuple (x0, y0, width, height). :return: List of dictionaries, each one with the structure of a rectangle object. """ def aida_rectangle_item(rectangle): """ Create an object that describes a rectangle in AIDA. :param rectangle: (x0, y0, width, height). :return: item: dictionary with the structure of the rectangle object. """ # extract rectangle parameters (x0, y0, width, height) = rectangle # convert RGB to HSL hls_colour_black = colorsys.rgb_to_hls(0, 0, 0) hls_colour_white = colorsys.rgb_to_hls(1, 1, 1) item = { 'type': 'rectangle', 'class': '', 'color': { 'fill': { 'hue': hls_colour_black[0] * 360, 'saturation': hls_colour_black[2], 'lightness': hls_colour_black[1], 'alpha': 0.5}, 'stroke': { 'hue': hls_colour_white[0] * 360, 'saturation': hls_colour_white[2], 'lightness': hls_colour_white[1], 'alpha': 1}}, 'x': x0, 'y': y0, 'width': width, 'height': height, 'locked': False } return item ## main function if type(rectangles) != list: raise TypeError('rectangles must be a list, even if it only has one item') # create the list of rectangle objects (each item is a rectangle object) items = [aida_rectangle_item(rectangle=rectangles[i]) for i in range(len(rectangles))] return items def aida_write_new_items(filename, items, mode='append_to_last_layer', indent=0, ensure_ascii=False, double_precision=10, number_of_attempts=1): """ Create a new or update existing AIDA annotations file, adding new items. :param filename: String with path to .json annotations file. :param items: List of items, obtained e.g. with aida_contour_items() or aida_rectangle_items(). :param mode: - 'append_to_last_layer': (def) Append items to the last layer with the same item type. - 'append_new_layer': Create new layer for items. - 'w': Overwrite existing file, or create a new one with only these items. :param indent: (def 0) Number of indentation spaces for pretty print format. By default, 0, everything is saved to one line without spaces. :param ensure_ascii: (def False) Limits output to ASCII and escapes all extended characters above 127. Default is true. If your end format supports UTF-8 setting this option to false is highly recommended to save space. :param double_precision: (def 10) Controls how many decimals to encode for double or decimal values. :param number_of_attempts: (def 1) Number of times we try to write the file if the server returns ConnectionResetError. :return: * None """ if type(items) != list: raise SyntaxError('items must be a list, but is type: ' + type(items)) # get item type item_type = items[0]['type'] # layer name that corresponds to this item type if item_type == 'path': layer_name = 'White adipocyte' elif item_type == 'rectangle': layer_name = 'Blocks' else: raise NotImplementedError('item_type not implemented: ' + item_type) # if an annotations file already exists with the filename path, read it so that we can add to it if mode != 'w' and os.path.isfile(filename): # load existing data with open(filename) as fp: annotations = ujson.load(fp) # check that this file has the expected format if 'name' not in annotations: raise KeyError('Annotations have no \'name\' key') if 'layers' not in annotations: raise KeyError('Annotations have no \'layers\' key') else: # if previous file doesn't exist, create an annotations file from scratch # top-most segmentation object. It contains only one layer annotations = {'name': 'DeepCytometer annotations', 'layers': []} if DEBUG: print('Loaded file: ' + filename) print('Annotations name: ' + annotations['name']) print('Number of layers: ' + str(len(annotations['layers']))) for j in range(len(annotations['layers'])): print(' Layer ' + str(j) + ': ' + annotations['layers'][j]['name'] + '. Number of ' + annotations['layers'][j]['items'][0]['type'] + ' items: ' + str(len(annotations['layers'][j]['items']))) # find the last layer for the current item type, if there's any i_layer = layer_number = [] # in case there isn't any layer of this type for l in range(len(annotations['layers'])): if layer_name in annotations['layers'][l]['name']: # index of layer where we are going to append items i_layer = l # number that we are going to add to the layer name. Note that this, in general, will be different from # the layer's index layer_number = int(annotations['layers'][l]['name'].replace(layer_name, '')) # if no layer exists, we'll need to add a new layer if i_layer == []: mode = 'append_new_layer' layer_number = -1 # if we want to append items to a new layer if mode == 'append_new_layer': # new layer object layer = {'name': layer_name + ' ' + str(layer_number + 1), 'opacity': 1.0, 'items': items} # append layer to current annotations annotations['layers'] += [layer, ] elif mode == 'append_to_last_layer': # append items to currently selected layer annotations['layers'][i_layer]['items'] += items else: raise NotImplementedError('mode not implemented: ' + mode) # if we are trying to save to a network filesystem, the server hosting the filesystem may return a # ConnectionResetError. Because this would corrupt the output file, we let the user try a couple of times, with # with a little wait between tries for attempt in range(number_of_attempts): try: # write annotations to file with open(filename, 'w') as fp: ujson.dump(annotations, fp, indent=indent, ensure_ascii=ensure_ascii) break except ConnectionResetError: print('# ======> ConnectionResetError. Attempt ' + str(attempt) + '/' + str(number_of_attempts) + ' ...') time.sleep(5) # secs except BrokenPipeError: print('# ======> BrokenPipeError. Attempt ' + str(attempt) + '/' + str(number_of_attempts) + ' ...') time.sleep(5) # secs except: raise def aida_get_contours(annotations, layer_name='.*', return_props=False): """ Concatenate items as contours in an AIDA annotations file or dict. Only 'path' and 'rectangle' types implemented. :param annotations: filename or dict with AIDA annotations. :param layer_name: (def '.*', which matches any name). Regular expression (see help for re module) that will be used as the pattern to march against the layer names. For example, layer_name='White adipocyte.*' will match any layer name like 'White adipocyte 0', 'White adipocyte 1', etc. :param return_props: (def False). Return extra output variable with properties of contours. :return: * items: list of concatenated contours from selected layers. [contour_0, contour_1, ...] where contour_i = [[x0, y0], [x1, y1], ...]. * props: dictionary of contour properties. Currently, only implemented output is props['cell_prob'] """ # if filename provided, load annotations if isinstance(annotations, six.string_types): # parse the json file with open(annotations) as fp: annotations = ujson.load(fp) if type(annotations) != dict: raise TypeError('annotations must be type dict') items = [] if return_props: cell_prob = [] for l in range(len(annotations['layers'])): # check whether the regular expression matches the layer name if re.match(layer_name, annotations['layers'][l]['name']) is not None: for i in range(len(annotations['layers'][l]['items'])): if annotations['layers'][l]['items'][i]['type'] == 'path': # add items to list of output items items += [annotations['layers'][l]['items'][i]['segments'],] if return_props: cell_prob += [annotations['layers'][l]['items'][i]['cell_prob'],] elif annotations['layers'][l]['items'][i]['type'] == 'rectangle': # extract rectangle first and last corners x0 = annotations['layers'][l]['items'][i]['x'] y0 = annotations['layers'][l]['items'][i]['y'] xend = x0 + annotations['layers'][l]['items'][i]['width'] - 1 yend = y0 + annotations['layers'][l]['items'][i]['height'] - 1 # 4 corners of the rectangle, with first repeated for closed contour item = [[x0, y0], [xend, y0], [xend, yend], [x0, yend], [x0, y0]] # add items to list of output items items += [item,] else: warnings.warn('Unknown item type found: layer ' + str(l) + ', item ' + str(i) + ': ' + annotations['layers'][l]['items'][i]['type'], SyntaxWarning) if return_props: return items, {'cell_prob':cell_prob} else: return items def read_keras_training_output(filename, every_step=True): """ Read a text file with the keras output of one or multiple trainings. The output from each training is expected to look like this: <FILE> Epoch 1/10 1/1846 [..............................] - ETA: 1:33:38 - loss: 1611.5088 - mean_squared_error: 933.6124 - mean_absolute_error: 17.6664 2/1846 [..............................] - ETA: 53:17 - loss: 1128.0714 - mean_squared_error: 593.7890 - mean_absolute_error: 13.8204 ... 1846/1846 [==============================] - 734s 398ms/step - loss: 273.1249 - mean_squared_error: 385.5759 - mean_absolute_error: 14.7488 - val_loss: 544.2305 - val_mean_squared_error: 285.2719 - val_mean_absolute_error: 11.1605 Epoch 2/10 1/1846 [..............................] - ETA: 11:22 - loss: 638.7009 - mean_squared_error: 241.0196 - mean_absolute_error: 10.6583 ... 1846/1846 [==============================] - 734s 398ms/step - loss: 273.1249 - mean_squared_error: 385.5759 - mean_absolute_error: 14.7488 - val_loss: 544.2305 - val_mean_squared_error: 285.2719 - val_mean_absolute_error: 11.1605 Epoch 2/10 1/1846 [..............................] - ETA: 11:22 - loss: 638.7009 - mean_squared_error: 241.0196 - mean_absolute_error: 10.6583 </FILE> Any lines until the first "Epoch" are ignored. Then, the rest of the training output is put into a pandas.DataFrame like this: epoch ETA loss mean_absolute_error mean_squared_error 0 1 5618 1611.5088 17.6664 933.6124 1 1 3197 1128.0714 13.8204 593.7890 ... 18448 10 0 88.1862 13.6856 453.2228 18449 10 0 88.2152 13.6862 453.2333 [18450 rows x 5 columns] :param filename: string with the path and filename of a text file with the training output from keras :param every_step: (bool def True) The log file contains one line per training step, as opposed to reading only one summary line per epoch :return: list of pandas.DataFrame """ def process_metrics(line, epoch): # remove whitespaces: '1/1846[..............................]-ETA:1:33:38-loss:1611.5088-mean_squared_error:933.6124-mean_absolute_error:17.6664' line = line.strip() # split line into elements: ['1/1846[..............................]', 'ETA:1:33:38', 'loss:1611.5088', 'mean_squared_error:933.6124', 'mean_absolute_error:17.6664'] line = line.split(' - ') # remove first element: ['ETA:1:33:38', 'loss:1611.5088', 'mean_squared_error:933.6124', 'mean_absolute_error:17.6664'] line = line[1:] # add "" around the first :, and at the beginning and end of the element # ['"ETA":"1:33:38"', '"loss":"1611.5088"', '"mean_squared_error":"933.6124"', '"mean_absolute_error":"17.6664"'] line = [x.replace(':', '":"', 1) for x in line] line = ['"' + x + '"' for x in line] # add epoch to collated elements and surround by {} # '{"ETA":"1:33:38", "loss":"1611.5088", "mean_squared_error":"933.6124", "mean_absolute_error":"17.6664"}' line = '{"epoch":' + str(epoch) + ', ' + ', '.join(line) + '}' # convert string to dict # {'ETA': '1:33:38', 'loss': '1611.5088', 'mean_squared_error': '933.6124', 'mean_absolute_error': '17.6664'} line = ast.literal_eval(line) # convert string values to numeric values for key in line.keys(): if key == 'ETA': eta_str = line['ETA'].split(':') if len(eta_str) == 1: # ETA: 45s eta = int(eta_str[-1].replace('s', '')) else: eta = int(eta_str[-1]) if len(eta_str) > 1: # ETA: 1:08 eta += 60 * int(eta_str[-2]) if len(eta_str) > 2: # ETA: 1:1:08 eta += 3600 * int(eta_str[-3]) if len(eta_str) > 3: raise ValueError('ETA format not implemented') line['ETA'] = eta elif key == 'epoch': pass else: line[key] = float(line[key]) return line # end of def process_metrics(): # ignore all lines until we get to the first "Epoch" df_all = [] file = open(filename, 'r') for line in file: if line[0:5] == 'Epoch': data = [] epoch = 1 break # if the user wants to read only the summary line of the training output instead of each step if every_step: # loop until the end of the file while True: if ('Epoch 1/' in line) or not line: # start of new training or end of file if len(data) > 0: # convert list of dictionaries to dataframe df = pd.DataFrame(data) # reorder columns so that epochs go first df = df[(df.columns[df.columns == 'epoch']).append(df.columns[df.columns != 'epoch'])] # add dataframe to output list of dataframes df_all.append(df) if not line: # if we are at the end of the file, we stop reading break else: # reset the variables for the next training data = [] epoch = 1 elif 'Epoch' in line: # new epoch of current training epoch += 1 elif 'ETA:' in line: # convert line into dictionary with different metric values line = process_metrics(line, epoch) # add the dictionary to the output list data.append(line) # read the next line line = file.readline() # we have finished reading the log file else: # read only one summary line by epoch # loop until the end of the file while True: if ('Epoch 1/' in line) or not line: # start of new training or end of file if len(data) > 0: # convert list of dictionaries to dataframe df = pd.DataFrame(data) # reorder columns so that epochs go first df = df[(df.columns[df.columns == 'epoch']).append(df.columns[df.columns != 'epoch'])] # add dataframe to output list of dataframes df_all.append(df) if not line: # if we are at the end of the file, we stop reading break else: # reset the variables for the next training data = [] epoch = 1 elif 'Epoch' in line and not ':' in line: # new epoch of current training epoch += 1 # we want this line # 1748/1748 [==============================] - 188s 108ms/step - loss: 0.3056 - acc: 0.9531 - val_loss: 0.3092 - val_acc: 0.9405 # we don't want this line # '1740/1748 [============================>.] - ETA: 0s - loss: 0.3058 - acc: 0.95312019-06-14 13:08:41.183265: W tensorflow/stream_executor/cuda/cuda_dnn.cc:3472] \n' # we don't want these lines # 2019-06-14 13:08:41.183372: W tensorflow/stream_executor/cuda/cuda_dnn.cc:3217] elif 'loss' in line and '[=====' in line and '=====]' in line: # remove start of line to keep only # loss: 0.3056 - acc: 0.9531 - val_loss: 0.3092 - val_acc: 0.9405 pattern = re.compile('loss:.*') line = pattern.search(line) line = line[0] # add dummy start at beginning of the line that will be removed by process_metrics() line = 'foo: foo - ' + line # convert line into dictionary with different metric values line = process_metrics(line, epoch) # add the dictionary to the output list data.append(line) # read the next line line = file.readline() # we have finished reading the log file # end "if from_summary_line" # close the file file.close() return df_all def tag_values_with_mouse_info(metainfo, s, values=None, values_tag='values', tags_to_keep=None, id_tag='id'): """ If you have a vector with cell areas, values = [4.0 , 7.0 , 9.0 , 7.3], then tag_values_with_mouse_info('meta.csv', s='KLF14-B6NTAC-PAT-37.2g 415-16 C1 - 2016-03-16 11.47.52_row_031860_col_033476.svg', values=[4. , 7. , 9. , 7.3], values_tag='area', tags_to_keep=['id', 'ko', 'sex']) will read the table of metainformation for all mice from file 'meta.csv', it finds which mouse we are dealing with according to s='KLF14-B6NTAC-PAT-37.2g 415-16 C1 - 2016-03-16 11.47.52_row_031860_col_033476.svg' (in this case, mouse '37.2g'), and then it creates a dataframe with one row per value, and the mouse's metainformation repeated in each row, id ko sex area 0 37.4a PAT m 4.0 1 37.4a PAT m 7.0 2 37.4a PAT m 9.0 3 37.4a PAT m 7.3 :param metainfo: List of OrderedDict from read_mouse_csv_info(), or string with CSV filename that contains the metainformation. :param s: String, typically a filename, that identifies an image, containing the mouse id, e.g. 'KLF14-B6NTAC-PAT-37.2g 415-16 C1 - 2016-03-16 11.47.52_row_031860_col_033476.svg' :param values: List or vector of values. Each value creates a row in the output dataframe. :param values_tag: Name of the column with the values in the output dataframe. :param tags_to_keep: (def None = keep all the tags). If not all the metainformation columns are needed, a list of tags can be passed here, e.g. tags_to_keep = ['id', 'ko', 'sex']. :param id_tag: (def 'id') String with the name of the column that contains the animal ID. This ID is also in the filename, and that's how the filename gets matched to a row in the metainfo file. :return: panda.DataFrame with one row per value. """ # if metainfo is provided as CSV filename, read it to memory as a DataFrame if isinstance(metainfo, six.string_types): metainfo = pd.read_csv(metainfo) # list of mouse IDs mouse_ids = metainfo[id_tag] # indices of IDs that can be found in the filename id_in_sid = np.where([x in s for x in mouse_ids])[0] # if more than one ID can be found in the filename, that means that the filename is ambiguous if len(id_in_sid) > 1: raise ValueError('s is ambiguous, and more than one ID can be found in it: ' + s) elif len(id_in_sid) == 0: # no ID found in the filename warnings.warn('Either s has no valid ID, or metainfo is missing a row for that ID: ' + s) metainfo_row = pd.DataFrame(columns=metainfo.columns) else: # row with all the metainfo for the selected mouse metainfo_row = metainfo.loc[id_in_sid, :] # keep only some of the metainformation tags if tags_to_keep: metainfo_row = metainfo_row[tags_to_keep] if values is None or len(values) == 0: return metainfo_row else: # repeat the row once per element in values df = pd.concat([metainfo_row] * len(values), ignore_index=True) df[values_tag] = values return df ## Deprecated functions def write_path_to_aida_json_file(fp, x, hue=170, pretty_print=False): """ DEPRECATED: Use aida_write_new_items() instead. Write single contour to a JSON file in AIDA's annotation format. (This function only writes the XML code only for the contour, not a full JSON file). :param fp: file pointer to text file that is open for writing/appending. :param x: numpy.ndarray with two columns, for (x,y)-coordinates of the points of a polygonal contour. :param hue: (def 170, which is a greenish blue) The hue of the color as a value in degrees between 0 and 360. :param pretty_print: (def False) Boolean. Whether to save the file with '\n' and whitespaces for pretty formatting. :return: None. """ warnings.warn('Use aida_write_new_items() instead', DeprecationWarning) if pretty_print: fp.write(' {\n') fp.write(' "class": "",\n') fp.write(' "type": "path",\n') fp.write(' "color": {\n') fp.write(' "fill": {\n') fp.write(' "hue": ' + str(hue) + ',\n') fp.write(' "saturation": 0.44,\n') fp.write(' "lightness": 0.69,\n') fp.write(' "alpha": 0.5\n') fp.write(' },\n') fp.write(' "stroke": {\n') fp.write(' "hue": ' + str(hue) + ',\n') fp.write(' "saturation": 0.44,\n') fp.write(' "lightness": 0.69,\n') fp.write(' "alpha": 1.0\n') fp.write(' }\n') fp.write(' },\n') fp.write(' "segments": [\n') for i, pt in enumerate(x): fp.write(' [' + '{0:.12f}'.format(pt[0]) + ', ' + '{0:.12f}'.format(pt[1])) if i == len(x) - 1: fp.write(']\n') # last point in the contour else: fp.write('],\n') # any other point in the contour fp.write(' ],\n') fp.write(' "closed": true\n') fp.write(' }') else: fp.write('{') fp.write('"class": "",') fp.write('"type": "path",') fp.write('"color": {') fp.write('"fill": {') fp.write('"hue": ' + str(hue) + ',') fp.write('"saturation": 0.44,') fp.write('"lightness": 0.69,') fp.write('"alpha": 0.5') fp.write('},') fp.write('"stroke": {') fp.write('"hue": ' + str(hue) + ',') fp.write('"saturation": 0.44,') fp.write('"lightness": 0.69,') fp.write('"alpha": 1.0') fp.write('}') fp.write('},') fp.write('"segments": [') for i, pt in enumerate(x): fp.write('[' + '{0:.12f}'.format(pt[0]) + ',' + '{0:.12f}'.format(pt[1])) if i == len(x) - 1: fp.write(']') # last point in the contour else: fp.write('],') # any other point in the contour fp.write('],') fp.write('"closed": true') fp.write('}') return def write_paths_to_aida_json_file(fp, xs, hue=170, pretty_print=False): """ DEPRECATED: Use aida_write_new_items() instead. Write a list/tuple of contours to a JSON file in AIDA's annotation format. :param fp: file pointer to text file that is open for writing/appending. :param xs: List of contours. Each contour is a list of points given as [x,y] or (x,y). :param hue: (def 170, a greenish blue). Integer or list of integers with hue value (between 0 and 360 degrees), one per contour in xs. If hue is an integer, the same hue is applied to each contour. :param pretty_print: (def False) Boolean. Whether to save the file with '\n' and whitespaces for pretty formatting. :return: None. """ warnings.warn('Use aida_write_new_items() instead', DeprecationWarning) if np.isscalar(hue): hue = [hue] * len(xs) # write file header if pretty_print: fp.write('{\n') fp.write(' "name": "Cytometer segmentation",\n') fp.write(' "layers": [\n') fp.write(' {\n') fp.write(' "name": "Cell layer",\n') fp.write(' "opacity": 1,\n') fp.write(' "items": [\n') for i, x in enumerate(xs): write_path_to_aida_json_file(fp, x, hue=hue[i], pretty_print=pretty_print) if i == len(xs) - 1: fp.write('\n') # last path else: fp.write(',\n') # any other path fp.write(' ]\n') fp.write(' }\n') fp.write(' ]\n') fp.write('}\n') else: fp.write('{') fp.write('"name": "Cytometer segmentation",') fp.write('"layers": [') fp.write('{') fp.write('"name": "Cell layer",') fp.write('"opacity": 1,') fp.write('"items": [') for i, x in enumerate(xs): write_path_to_aida_json_file(fp, x, hue=hue[i], pretty_print=pretty_print) if i == len(xs) - 1: fp.write('') # last path else: fp.write(',') # any other path fp.write(']') fp.write('}') fp.write(']') fp.write('}') return def append_paths_to_aida_json_file(file, xs, hue=170, pretty_print=False): """ DEPRECATED: Use write_aida_annotations() instead. Add contours to AIDA's annotation file in JSON format. :param file: Path and filename of .json file with AIDA annotations. :param xs: List of contours. Each contour is a list of points given as [x,y] or (x,y). :param hue: (def 170, a greenish blue). Integer or list of integers with hue value (between 0 and 360 degrees), one per contour in xs. If hue is an integer, the same hue is applied to each contour. :param pretty_print: (def False) Boolean. Whether to save the file with '\n' and whitespaces for pretty formatting. :return: None. """ warnings.warn('Use aida_write_new_items() instead', DeprecationWarning) def seek_character(fp, target): """ Read file backwards until finding target character. :param fp: File pointer. :param target: Character that we are looking for. :return: c: Found character. """ while fp.tell() > 0: c = fp.read(1) if c == target: break else: fp.seek(fp.tell() - 2) if fp.tell() == 0: raise IOError('Beginning of file reached before finding "}"') return c if len(xs) == 0: return if np.isscalar(hue): hue = [hue] * len(xs) # truncate the tail of the annotations file: # # ' "closed": true' # ' }' ---------> end of last contour # ' ]' ---------> first line of tail (truncate this line and the rest) # ' }' # ' ]' # '}' # # so that we can append a new contour like # # ' "closed": true' # ' },' ---------> end of last contour # ' {' ---------> beginning of new contour # ' "class": "",' # ' "type": "path",' # ' ...' # ' "closed": true' # ' }' ---------> end of last contour # ' ]' ---------> first line of tail # ' }' # ' ]' # '}' if pretty_print: tail = ' ]\n' + \ ' }\n' + \ ' ]\n' + \ '}\n' else: tail = ']' + \ '}' + \ ']' + \ '}' fp = open(file, 'r') if not fp.seekable(): raise IOError('File does not support random access: ' + file) # go to end of the file pos = fp.seek(0, os.SEEK_END) # find tail characters reading backwards from the end c = seek_character(fp, '}') c = seek_character(fp, ']') c = seek_character(fp, '}') c = seek_character(fp, ']') c = seek_character(fp, '}') pos = fp.tell() # reopen file to append contours fp.close() fp = open(file, 'a') fp.seek(pos) # truncate the tail fp.truncate() # add ',' to ' }', so that we can add a new contour if pretty_print: fp.write(',\n') else: fp.write(',') # append new contours to JSON file for i, x in enumerate(xs): write_path_to_aida_json_file(fp, x, hue=hue[i], pretty_print=pretty_print) if i == len(xs) - 1: if pretty_print: fp.write('\n') # last path else: fp.write('') # last path else: if pretty_print: fp.write(',\n') # any other path else: fp.write(',') # any other path # append tail fp.write(tail) fp.close() return def zeiss_to_deepzoom(histo_list, dzi_dir=None, overwrite=False, extra_tif=False, tif_dir=None): """ Convert microscopy files from Zeiss .czi format to DeepZoom .dzi format. It can also create a TIFF version of the file that can be read by OpenSlide and probably most libraries. .dzi is a format that can be used by AIDA to display and navigate large microscopy images. :param histo_list: path and filename, or list of paths and filenames of Zeiss .czi files. :param dzi_dir: (def None) Destination path of the DeepZoom output files. If dzi_dir=None, the DeepZoom files are created in the same path as the input Zeiss image. :param overwrite: (def False) Overwrite the destination files if they already exist. :param extra_tif: (def False) Create an extra TIFF version of the file. This format can be opened by openslide. :param tif_dir: (def None) Destination path of the TIFF output files. If tif_dir=None, the TIFF files are created in the same path as the input Zeiss image. :return: None. """ if type(histo_list) is not list: histo_list = [histo_list,] for histo_file in histo_list: # basename for DeepZoom file # Note: '.dzi' will be added by pyvips to the basename we provide, and that's why the basename has no extension filename_noext = os.path.basename(histo_file) filename_noext = os.path.splitext(filename_noext)[0] if dzi_dir is None: dzi_filename_noext = os.path.join(os.path.dirname(histo_file), filename_noext) else: dzi_filename_noext = os.path.join(dzi_dir, filename_noext) if tif_dir is None: tif_filename_noext = os.path.join(os.path.dirname(histo_file), filename_noext) else: tif_filename_noext = os.path.join(tif_dir, filename_noext) dzi_filename = dzi_filename_noext + '.dzi' tif_filename = tif_filename_noext + '.tif' # files will be written if they don't exist, or if they exist but overwrite=True save_dzi = not(os.path.isfile(dzi_filename) and not overwrite) save_tif = not(os.path.isfile(tif_filename) and not overwrite) # if we are going to create either the DeepZoom or TIFF file, we need to read the Zeiss file first if save_dzi or save_tif: # open the CZI file without loading it into memory im = aicsimageio.AICSImage(histo_file, reader=CziReader) if DEBUG: # write metadata to debug file import xml.etree.ElementTree as ET tree = ET.ElementTree(im.metadata) tree.write(os.path.join('/tmp/', os.path.basename(dzi_filename_noext) + '.xml'), encoding='utf-8') if DEBUG: time0 = time.time() im_array = im.get_image_data("TCZYXS") if DEBUG: print('Time = ' + str(time.time() - time0) + ' s') # # hack to obtain the image dimensions (number of pixels) quickily, due to this problem with im.dims # # https://github.com/AllenCellModeling/aicsimageio/issues/274 # width = int(im.metadata.findall('./Metadata/Information/Image/SizeX')[0].text) # height = int(im.metadata.findall('./Metadata/Information/Image/SizeY')[0].text) width = im_array.shape[4] height = im_array.shape[3] im_vips = pyvips.Image.new_from_memory(im_array, width=width, height=height, bands=3, format='uchar') # despite the units being 'µm', the values seems to be in 'm' assert(im.metadata.findall('./Metadata/Scaling/Items/Distance[@Id="X"]/DefaultUnitFormat')[0].text == 'µm') xres = float(im.metadata.findall('./Metadata/Scaling/Items/Distance[@Id="X"]/Value')[0].text) * 1 # m, e.g. 4.4e-07 assert(im.metadata.findall('./Metadata/Scaling/Items/Distance[@Id="Y"]/DefaultUnitFormat')[0].text == 'µm') yres = float(im.metadata.findall('./Metadata/Scaling/Items/Distance[@Id="Y"]/Value')[0].text) * 1 # m, e.g. 4.4e-07 # save to DeepZoom if os.path.isfile(dzi_filename) and not overwrite: print('DeepZoom files already exists and not overwrite selected... skipping: ' + dzi_filename) elif os.path.isfile(dzi_filename) and overwrite: print('File already exists and overwrite selected: ' + dzi_filename) os.remove(dzi_filename) shutil.rmtree(filename_noext + '_files', ignore_errors=True) im_vips.dzsave(dzi_filename_noext) # note: extension will be automatically added else: print('Creating file: ' + dzi_filename) im_vips.dzsave(dzi_filename_noext) # note: extension will be automatically added # save to TIFF if extra_tif and os.path.isfile(tif_filename) and not overwrite: print('TIFF files already exists and not overwrite selected... skipping: ' + tif_filename) elif extra_tif and os.path.isfile(tif_filename) and overwrite: print('File already exists but overwrite selected: ' + tif_filename) os.remove(tif_filename) im_vips.tiffsave(tif_filename, tile=True, pyramid=True, resunit='cm', xres=float(1e-3/xres), yres=float(1e-3/yres), bigtiff=True) else: print('Creating file: ' + tif_filename) im_vips.tiffsave(tif_filename, tile=True, pyramid=True, resunit='cm', xres=float(1e-3/xres), yres=float(1e-3/yres), bigtiff=True) return
[ "matplotlib.pyplot.title", "pickle.dump", "os.remove", "numpy.random.seed", "matplotlib.pyplot.clf", "colorsys.rgb_to_hls", "random.shuffle", "numpy.empty", "pandas.read_csv", "numpy.floor", "aicsimageio.AICSImage", "ujson.dump", "os.path.isfile", "numpy.imag", "numpy.arange", "colorsy...
[((1732, 1807), 'pysto.imgproc.block_split', 'pystoim.block_split', (['x'], {'nblocks': '(1, nblocks, nblocks, 1)', 'by_reference': '(True)'}), '(x, nblocks=(1, nblocks, nblocks, 1), by_reference=True)\n', (1751, 1807), True, 'import pysto.imgproc as pystoim\n'), ((1816, 1841), 'numpy.concatenate', 'np.concatenate', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1830, 1841), True, 'import numpy as np\n'), ((4444, 4472), 'numpy.unique', 'np.unique', (['file_list_reduced'], {}), '(file_list_reduced)\n', (4453, 4472), True, 'import numpy as np\n'), ((4752, 4775), 'numpy.array', 'np.array', (['file_list_lut'], {}), '(file_list_lut)\n', (4760, 4775), True, 'import numpy as np\n'), ((5030, 5052), 'random.seed', 'random.seed', (['fold_seed'], {}), '(fold_seed)\n', (5041, 5052), False, 'import random\n'), ((5126, 5161), 'numpy.array_split', 'np.array_split', (['idx_unique', 'n_folds'], {}), '(idx_unique, n_folds)\n', (5140, 5161), True, 'import numpy as np\n'), ((7579, 7637), 're.compile', 're.compile', (["('^' + home_path_from + '[' + os.path.sep + ']')"], {}), "('^' + home_path_from + '[' + os.path.sep + ']')\n", (7589, 7637), False, 'import re\n'), ((17030, 17058), 'PIL.Image.open', 'Image.open', (['seg_file_list[0]'], {}), '(seg_file_list[0])\n', (17040, 17058), False, 'from PIL import Image\n'), ((20813, 20828), 'svgpathtools.svg2paths', 'svg2paths', (['file'], {}), '(file)\n', (20822, 20828), False, 'from svgpathtools import svg2paths\n'), ((22100, 22126), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(101)'], {}), '(0.0, 1.0, 101)\n', (22111, 22126), True, 'import numpy as np\n'), ((22759, 22812), 'scipy.stats.mstats.hdquantiles', 'scipy.stats.mstats.hdquantiles', (['areas'], {'prob': 'quantiles'}), '(areas, prob=quantiles)\n', (22789, 22812), False, 'import scipy\n'), ((22835, 22945), 'scipy.interpolate.interp1d', 'scipy.interpolate.interp1d', (['areas_by_quantiles.data', 'quantiles'], {'bounds_error': '(False)', 'fill_value': '(0.0, 1.0)'}), '(areas_by_quantiles.data, quantiles, bounds_error\n =False, fill_value=(0.0, 1.0))\n', (22861, 22945), False, 'import scipy\n'), ((24569, 24599), 'numpy.linspace', 'np.linspace', (['(0)', '(315 / 360)', '(101)'], {}), '(0, 315 / 360, 101)\n', (24580, 24599), True, 'import numpy as np\n'), ((24860, 24901), 'matplotlib.colors.ListedColormap', 'ListedColormap', (['cm'], {'name': '"""quantiles_aida"""'}), "(cm, name='quantiles_aida')\n", (24874, 24901), False, 'from matplotlib.colors import ListedColormap\n'), ((50760, 50831), 'warnings.warn', 'warnings.warn', (['"""Use aida_write_new_items() instead"""', 'DeprecationWarning'], {}), "('Use aida_write_new_items() instead', DeprecationWarning)\n", (50773, 50831), False, 'import warnings\n'), ((53869, 53940), 'warnings.warn', 'warnings.warn', (['"""Use aida_write_new_items() instead"""', 'DeprecationWarning'], {}), "('Use aida_write_new_items() instead', DeprecationWarning)\n", (53882, 53940), False, 'import warnings\n'), ((53949, 53965), 'numpy.isscalar', 'np.isscalar', (['hue'], {}), '(hue)\n', (53960, 53965), True, 'import numpy as np\n'), ((56025, 56096), 'warnings.warn', 'warnings.warn', (['"""Use aida_write_new_items() instead"""', 'DeprecationWarning'], {}), "('Use aida_write_new_items() instead', DeprecationWarning)\n", (56038, 56096), False, 'import warnings\n'), ((56681, 56697), 'numpy.isscalar', 'np.isscalar', (['hue'], {}), '(hue)\n', (56692, 56697), True, 'import numpy as np\n'), ((4297, 4322), 're.sub', 're.sub', (['ignore_str', '""""""', 'x'], {}), "(ignore_str, '', x)\n", (4303, 4322), False, 'import re\n'), ((5367, 5392), 'random.shuffle', 'random.shuffle', (['idx_train'], {}), '(idx_train)\n', (5381, 5392), False, 'import random\n'), ((5735, 5775), 'numpy.concatenate', 'np.concatenate', (['file_list_lut[idx_train]'], {}), '(file_list_lut[idx_train])\n', (5749, 5775), True, 'import numpy as np\n'), ((5912, 5951), 'numpy.concatenate', 'np.concatenate', (['file_list_lut[idx_test]'], {}), '(file_list_lut[idx_test])\n', (5926, 5951), True, 'import numpy as np\n'), ((7746, 7791), 'os.path.join', 'os.path.join', (['home_path_to', 'file_without_home'], {}), '(home_path_to, file_without_home)\n', (7758, 7791), False, 'import os\n'), ((8986, 9005), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (8999, 9005), False, 'import os\n'), ((9647, 9663), 'numpy.empty', 'np.empty', (['(1, 0)'], {}), '((1, 0))\n', (9655, 9663), True, 'import numpy as np\n'), ((9729, 9753), 'PIL.Image.open', 'Image.open', (['file_list[0]'], {}), '(file_list[0])\n', (9739, 9753), False, 'from PIL import Image\n'), ((14320, 14329), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (14327, 14329), True, 'import matplotlib.pyplot as plt\n'), ((15238, 15288), 'numpy.count_nonzero', 'np.count_nonzero', (['datasets[prefix]'], {'axis': '(1, 2, 3)'}), '(datasets[prefix], axis=(1, 2, 3))\n', (15254, 15288), True, 'import numpy as np\n'), ((17076, 17090), 'numpy.array', 'np.array', (['seg0'], {}), '(seg0)\n', (17084, 17090), True, 'import numpy as np\n'), ((17884, 17926), 'mahotas.bwperim', 'bwperim', (['im_background'], {'n': '(8)', 'mode': '"""ignore"""'}), "(im_background, n=8, mode='ignore')\n", (17891, 17926), False, 'from mahotas import bwperim\n'), ((18964, 19003), 'scipy.ndimage.distance_transform_edt', 'ndimage.distance_transform_edt', (['seg_aux'], {}), '(seg_aux)\n', (18994, 19003), False, 'from scipy import ndimage\n'), ((20944, 20966), 'os.path.basename', 'os.path.basename', (['file'], {}), '(file)\n', (20960, 20966), False, 'import os\n'), ((21023, 21054), 'os.path.splitext', 'os.path.splitext', (['file_basename'], {}), '(file_basename)\n', (21039, 21054), False, 'import os\n'), ((23011, 23020), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (23018, 23020), True, 'import matplotlib.pyplot as plt\n'), ((23035, 23090), 'matplotlib.pyplot.hist', 'plt.hist', (['areas'], {'bins': '(50)', 'density': '(True)', 'histtype': '"""step"""'}), "(areas, bins=50, density=True, histtype='step')\n", (23043, 23090), True, 'import matplotlib.pyplot as plt\n'), ((26677, 26741), 'colorsys.rgb_to_hls', 'colorsys.rgb_to_hls', (['rgb_colour[0]', 'rgb_colour[1]', 'rgb_colour[2]'], {}), '(rgb_colour[0], rgb_colour[1], rgb_colour[2])\n', (26696, 26741), False, 'import colorsys\n'), ((28974, 29002), 'colorsys.rgb_to_hls', 'colorsys.rgb_to_hls', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (28993, 29002), False, 'import colorsys\n'), ((29030, 29058), 'colorsys.rgb_to_hls', 'colorsys.rgb_to_hls', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (29049, 29058), False, 'import colorsys\n'), ((31968, 31992), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (31982, 31992), False, 'import os\n'), ((41673, 41695), 'ast.literal_eval', 'ast.literal_eval', (['line'], {}), '(line)\n', (41689, 41695), False, 'import ast\n'), ((48867, 48888), 'pandas.read_csv', 'pd.read_csv', (['metainfo'], {}), '(metainfo)\n', (48878, 48888), True, 'import pandas as pd\n'), ((49019, 49058), 'numpy.where', 'np.where', (['[(x in s) for x in mouse_ids]'], {}), '([(x in s) for x in mouse_ids])\n', (49027, 49058), True, 'import numpy as np\n'), ((60254, 60282), 'os.path.basename', 'os.path.basename', (['histo_file'], {}), '(histo_file)\n', (60270, 60282), False, 'import os\n'), ((1468, 1493), 'numpy.floor', 'np.floor', (['(nrows / nblocks)'], {}), '(nrows / nblocks)\n', (1476, 1493), True, 'import numpy as np\n'), ((1521, 1546), 'numpy.floor', 'np.floor', (['(ncols / nblocks)'], {}), '(ncols / nblocks)\n', (1529, 1546), True, 'import numpy as np\n'), ((5422, 5441), 'numpy.array', 'np.array', (['idx_train'], {}), '(idx_train)\n', (5430, 5441), True, 'import numpy as np\n'), ((6520, 6562), 'pickle.dump', 'pickle.dump', (['x', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(x, f, pickle.HIGHEST_PROTOCOL)\n', (6531, 6562), False, 'import pickle\n'), ((9206, 9244), 'os.path.join', 'os.path.join', (['file_path', 'file_basename'], {}), '(file_path, file_basename)\n', (9218, 9244), False, 'import os\n'), ((9992, 10008), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (10002, 10008), False, 'from PIL import Image\n'), ((10041, 10050), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (10048, 10050), True, 'import matplotlib.pyplot as plt\n'), ((10063, 10089), 'matplotlib.pyplot.imshow', 'plt.imshow', (['im_out[i, ...]'], {}), '(im_out[i, ...])\n', (10073, 10089), True, 'import matplotlib.pyplot as plt\n'), ((12733, 12749), 'os.path.split', 'os.path.split', (['x'], {}), '(x)\n', (12746, 12749), False, 'import os\n'), ((14069, 14081), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (14078, 14081), True, 'import numpy as np\n'), ((14094, 14122), 'numpy.random.seed', 'np.random.seed', (['shuffle_seed'], {}), '(shuffle_seed)\n', (14108, 14122), True, 'import numpy as np\n'), ((14135, 14165), 'numpy.random.shuffle', 'np.random.shuffle', (['shuffle_idx'], {}), '(shuffle_idx)\n', (14152, 14165), True, 'import numpy as np\n'), ((14604, 14636), 'matplotlib.pyplot.title', 'plt.title', (["('out[' + prefix + ']')"], {}), "('out[' + prefix + ']')\n", (14613, 14636), True, 'import matplotlib.pyplot as plt\n'), ((16885, 16901), 'numpy.empty', 'np.empty', (['(1, 0)'], {}), '((1, 0))\n', (16893, 16901), True, 'import numpy as np\n'), ((16903, 16919), 'numpy.empty', 'np.empty', (['(1, 0)'], {}), '((1, 0))\n', (16911, 16919), True, 'import numpy as np\n'), ((16921, 16937), 'numpy.empty', 'np.empty', (['(1, 0)'], {}), '((1, 0))\n', (16929, 16937), True, 'import numpy as np\n'), ((17568, 17588), 'PIL.Image.open', 'Image.open', (['seg_file'], {}), '(seg_file)\n', (17578, 17588), False, 'from PIL import Image\n'), ((18625, 18634), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (18632, 18634), True, 'import matplotlib.pyplot as plt\n'), ((18647, 18663), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (18658, 18663), True, 'import matplotlib.pyplot as plt\n'), ((18676, 18708), 'matplotlib.pyplot.imshow', 'plt.imshow', (['seg_aux'], {'cmap': '"""gray"""'}), "(seg_aux, cmap='gray')\n", (18686, 18708), True, 'import matplotlib.pyplot as plt\n'), ((18721, 18745), 'matplotlib.pyplot.title', 'plt.title', (['"""Cell labels"""'], {}), "('Cell labels')\n", (18730, 18745), True, 'import matplotlib.pyplot as plt\n'), ((18758, 18774), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (18769, 18774), True, 'import matplotlib.pyplot as plt\n'), ((18787, 18825), 'matplotlib.pyplot.imshow', 'plt.imshow', (['mask[i, :, :]'], {'cmap': '"""gray"""'}), "(mask[i, :, :], cmap='gray')\n", (18797, 18825), True, 'import matplotlib.pyplot as plt\n'), ((18838, 18866), 'matplotlib.pyplot.title', 'plt.title', (['"""Training weight"""'], {}), "('Training weight')\n", (18847, 18866), True, 'import matplotlib.pyplot as plt\n'), ((19063, 19079), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (19074, 19079), True, 'import matplotlib.pyplot as plt\n'), ((19092, 19117), 'matplotlib.pyplot.imshow', 'plt.imshow', (['dmap[i, :, :]'], {}), '(dmap[i, :, :])\n', (19102, 19117), True, 'import matplotlib.pyplot as plt\n'), ((19130, 19155), 'matplotlib.pyplot.title', 'plt.title', (['"""Distance map"""'], {}), "('Distance map')\n", (19139, 19155), True, 'import matplotlib.pyplot as plt\n'), ((24771, 24822), 'colorsys.hls_to_rgb', 'colorsys.hls_to_rgb', ([], {'h': 'h', 'l': 'lightness', 's': 'saturation'}), '(h=h, l=lightness, s=saturation)\n', (24790, 24822), False, 'import colorsys\n'), ((32085, 32099), 'ujson.load', 'ujson.load', (['fp'], {}), '(fp)\n', (32095, 32099), False, 'import ujson\n'), ((36353, 36367), 'ujson.load', 'ujson.load', (['fp'], {}), '(fp)\n', (36363, 36367), False, 'import ujson\n'), ((36650, 36704), 're.match', 're.match', (['layer_name', "annotations['layers'][l]['name']"], {}), "(layer_name, annotations['layers'][l]['name'])\n", (36658, 36704), False, 'import re\n'), ((49345, 49439), 'warnings.warn', 'warnings.warn', (["('Either s has no valid ID, or metainfo is missing a row for that ID: ' + s)"], {}), "(\n 'Either s has no valid ID, or metainfo is missing a row for that ID: ' + s)\n", (49358, 49439), False, 'import warnings\n'), ((49458, 49496), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'metainfo.columns'}), '(columns=metainfo.columns)\n', (49470, 49496), True, 'import pandas as pd\n'), ((60308, 60340), 'os.path.splitext', 'os.path.splitext', (['filename_noext'], {}), '(filename_noext)\n', (60324, 60340), False, 'import os\n'), ((60510, 60547), 'os.path.join', 'os.path.join', (['dzi_dir', 'filename_noext'], {}), '(dzi_dir, filename_noext)\n', (60522, 60547), False, 'import os\n'), ((60714, 60751), 'os.path.join', 'os.path.join', (['tif_dir', 'filename_noext'], {}), '(tif_dir, filename_noext)\n', (60726, 60751), False, 'import os\n'), ((61309, 61360), 'aicsimageio.AICSImage', 'aicsimageio.AICSImage', (['histo_file'], {'reader': 'CziReader'}), '(histo_file, reader=CziReader)\n', (61330, 61360), False, 'import aicsimageio\n'), ((62325, 62420), 'pyvips.Image.new_from_memory', 'pyvips.Image.new_from_memory', (['im_array'], {'width': 'width', 'height': 'height', 'bands': '(3)', 'format': '"""uchar"""'}), "(im_array, width=width, height=height, bands=3,\n format='uchar')\n", (62353, 62420), False, 'import pyvips\n'), ((63029, 63057), 'os.path.isfile', 'os.path.isfile', (['dzi_filename'], {}), '(dzi_filename)\n', (63043, 63057), False, 'import os\n'), ((63734, 63762), 'os.path.isfile', 'os.path.isfile', (['tif_filename'], {}), '(tif_filename)\n', (63748, 63762), False, 'import os\n'), ((2273, 2284), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2281, 2284), True, 'import numpy as np\n'), ((2297, 2308), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2305, 2308), True, 'import numpy as np\n'), ((6244, 6288), 'numpy.concatenate', 'np.concatenate', (['(idx_test_all[i], idx_train)'], {}), '((idx_test_all[i], idx_train))\n', (6258, 6288), True, 'import numpy as np\n'), ((7824, 7852), 'os.path.isfile', 'os.path.isfile', (['file_list[i]'], {}), '(file_list[i])\n', (7838, 7852), False, 'import os\n'), ((12765, 12804), 're.match', 're.match', (["('^' + prefix_from)", 'x_basename'], {}), "('^' + prefix_from, x_basename)\n", (12773, 12804), False, 'import re\n'), ((12971, 13025), 're.sub', 're.sub', (["('^' + prefix_from)", 'prefix', 'x_basename'], {'count': '(1)'}), "('^' + prefix_from, prefix, x_basename, count=1)\n", (12977, 13025), False, 'import re\n'), ((13046, 13073), 'os.path.isfile', 'os.path.isfile', (['prefix_file'], {}), '(prefix_file)\n', (13060, 13073), False, 'import os\n'), ((14486, 14521), 'matplotlib.pyplot.imshow', 'plt.imshow', (['out[prefix][i, :, :, 0]'], {}), '(out[prefix][i, :, :, 0])\n', (14496, 14521), True, 'import matplotlib.pyplot as plt\n'), ((14556, 14591), 'matplotlib.pyplot.imshow', 'plt.imshow', (['out[prefix][i, :, :, :]'], {}), '(out[prefix][i, :, :, :])\n', (14566, 14591), True, 'import matplotlib.pyplot as plt\n'), ((34735, 34804), 'ujson.dump', 'ujson.dump', (['annotations', 'fp'], {'indent': 'indent', 'ensure_ascii': 'ensure_ascii'}), '(annotations, fp, indent=indent, ensure_ascii=ensure_ascii)\n', (34745, 34804), False, 'import ujson\n'), ((34990, 35003), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (35000, 35003), False, 'import time\n'), ((35169, 35182), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (35179, 35182), False, 'import time\n'), ((60418, 60445), 'os.path.dirname', 'os.path.dirname', (['histo_file'], {}), '(histo_file)\n', (60433, 60445), False, 'import os\n'), ((60622, 60649), 'os.path.dirname', 'os.path.dirname', (['histo_file'], {}), '(histo_file)\n', (60637, 60649), False, 'import os\n'), ((60968, 60996), 'os.path.isfile', 'os.path.isfile', (['dzi_filename'], {}), '(dzi_filename)\n', (60982, 60996), False, 'import os\n'), ((61039, 61067), 'os.path.isfile', 'os.path.isfile', (['tif_filename'], {}), '(tif_filename)\n', (61053, 61067), False, 'import os\n'), ((61505, 61532), 'xml.etree.ElementTree.ElementTree', 'ET.ElementTree', (['im.metadata'], {}), '(im.metadata)\n', (61519, 61532), True, 'import xml.etree.ElementTree as ET\n'), ((61695, 61706), 'time.time', 'time.time', ([], {}), '()\n', (61704, 61706), False, 'import time\n'), ((63197, 63225), 'os.path.isfile', 'os.path.isfile', (['dzi_filename'], {}), '(dzi_filename)\n', (63211, 63225), False, 'import os\n'), ((63334, 63357), 'os.remove', 'os.remove', (['dzi_filename'], {}), '(dzi_filename)\n', (63343, 63357), False, 'import os\n'), ((63370, 63430), 'shutil.rmtree', 'shutil.rmtree', (["(filename_noext + '_files')"], {'ignore_errors': '(True)'}), "(filename_noext + '_files', ignore_errors=True)\n", (63383, 63430), False, 'import shutil\n'), ((63912, 63940), 'os.path.isfile', 'os.path.isfile', (['tif_filename'], {}), '(tif_filename)\n', (63926, 63940), False, 'import os\n'), ((64049, 64072), 'os.remove', 'os.remove', (['tif_filename'], {}), '(tif_filename)\n', (64058, 64072), False, 'import os\n'), ((27755, 27765), 'shapely.geometry.Polygon', 'Polygon', (['c'], {}), '(c)\n', (27762, 27765), False, 'from shapely.geometry import Polygon\n'), ((43163, 43181), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (43175, 43181), True, 'import pandas as pd\n'), ((44552, 44570), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (44564, 44570), True, 'import pandas as pd\n'), ((20597, 20614), 'numpy.real', 'np.real', (['pt.start'], {}), '(pt.start)\n', (20604, 20614), True, 'import numpy as np\n'), ((20627, 20644), 'numpy.imag', 'np.imag', (['pt.start'], {}), '(pt.start)\n', (20634, 20644), True, 'import numpy as np\n'), ((46040, 46061), 're.compile', 're.compile', (['"""loss:.*"""'], {}), "('loss:.*')\n", (46050, 46061), False, 'import re\n'), ((61582, 61618), 'os.path.basename', 'os.path.basename', (['dzi_filename_noext'], {}), '(dzi_filename_noext)\n', (61598, 61618), False, 'import os\n'), ((61818, 61829), 'time.time', 'time.time', ([], {}), '()\n', (61827, 61829), False, 'import time\n')]
# -*- coding:utf-8 -*- import argparse from collections import OrderedDict from pathlib import Path import os import numpy as np import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter from citylearn import CityLearn from agent import RL_Agents from utils.io import get_output_folder from utils.standardization import normalize_state from reward_function import reward_function parser = argparse.ArgumentParser() # RL Hyper-parameters parser.add_argument('--lr', type=float, default=1e-4) parser.add_argument('--MAX_BUFFER', type=int, default=10000) parser.add_argument('--seed', '-s', type=int, default=0) parser.add_argument('--BATCH_SIZE', type=int, default=32) parser.add_argument('--climate_zone', type=int, default=1) parser.add_argument('--act_limit', type=float, default=0.5) parser.add_argument('--decay', type=float, default=1) # TCN Hyper-parameters parser.add_argument('--encode_dim', type=int, default=64) parser.add_argument('--num_layers', type=int, default=1) parser.add_argument('--alpha', type=float, default=0.2) parser.add_argument('--kernel_size', type=int, default=3) parser.add_argument('--kernel_size_forecast', type=int, default=3) parser.add_argument('--levels', type=int, default=5) parser.add_argument('--levels_forecast', type=int, default=3) parser.add_argument('--seq_len', type=int, default=24) parser.add_argument('--seq_len_forecast', type=int, default=6) parser.add_argument('--episode_len', type=int, default=168) # reward Hyper-parameters parser.add_argument('--A_r', type=float, default=0) parser.add_argument('--B_r', type=float, default=1) parser.add_argument('--window_len_A', type=int, default=6) parser.add_argument('--window_len_B', type=int, default=12) parser.add_argument('--price_factor', type=float, default=0.01) # logger parser.add_argument('--print_per_step', type=int, default=250) parser.add_argument('--start_k', type=int, default=0) parser.add_argument('--start_c', type=int, default=0) # load model parser.add_argument('--continue_flag', type=int, default=0) parser.add_argument('--load_episode', type=int, default=295) # training length parser.add_argument('--MaxEpisode', type=int, default=100000) parser.add_argument('--save_per_episode', type=int, default=500) parser.add_argument('--train', dest='train', default=True, action='store_true') parser.add_argument('--eval', dest='train', action='store_false') parser.add_argument('--suffix', type=str, default="") args = parser.parse_args() reward_kwargs = OrderedDict( alpha=args.A_r, beta=args.B_r, total_energy_window=args.window_len_A, heat_energy_window=args.window_len_B, price_factor=args.price_factor, ramping_window=6 ) full_dim = 33 src_dim = 21 pred_dim = 4 latent_dim = 3 act_dim = 2 # Load Model using args dict def get_agent_kwargs(args, log_path, train=None): # Lazy Import from model.BaseModules import ActionClipping from model.Encoder import ROMAEncoder, ROMALSTMEncoder from model.RLModules import DualHyperQNet, SGHNActor, MLP encode_dim = args.encode_dim encoder_kwargs = (ROMAEncoder, OrderedDict( # for ROMAEncoder input_size=33, output_size=encode_dim, role_size=latent_dim, rnn_kwarg=OrderedDict(num_layers=args.num_layers)) ) model_kwargs = OrderedDict( Encoder=encoder_kwargs, DualCritic=(DualHyperQNet, OrderedDict(input_size=encode_dim, latent_size=latent_dim, action_size=act_dim)), Actor=(SGHNActor, OrderedDict(input_size=encode_dim, output_size=act_dim, latent_size=latent_dim)), DisparityNet=(MLP, OrderedDict(input_size=latent_dim * 2, output_size=1, layer_sizes=[encode_dim], norm_layer=nn.BatchNorm1d, activation=nn.LeakyReLU())), ) default_lr = args.lr action_clip_kwargs = OrderedDict( start_bound=args.act_limit, stop_bound=.1, decay=args.decay, step_size=20000, warm_up=0, verbose=True ) # print("act limit:", action_clip_kwargs['start_bound) if train is None: train = args.train if not train: algo_kwargs = None print("eval mode, use deterministic policy") else: unique_optim_kwargs = OrderedDict( Encoder=OrderedDict(), DualCritic=OrderedDict(), Actor=OrderedDict() ) algo_kwargs = OrderedDict( batch_size=args.BATCH_SIZE, alpha=args.alpha, buffer_capacity=args.MAX_BUFFER, optim_cls=torch.optim.Adam, optim_kwargs=OrderedDict(lr=default_lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0), unique_optim_kwargs=unique_optim_kwargs, verbose=True, log_interval=args.print_per_step, log_path=log_path ) ac_kwargs = dict( model_kwargs=model_kwargs, algo_kwargs=algo_kwargs, # state_fn=lambda s: normalize_seq2seq_state_forRL(s, future_len=args.seq_len_forecast), state_fn=normalize_state, # No reward_fn for Hierarchical Agents # TODO Compatibility with original agent reward_fn=None, action_clipping=lambda model: ActionClipping(model, **action_clip_kwargs), memory_size=args.seq_len ) return ac_kwargs filename = "zone_" + str(args.climate_zone) + \ "_lr" + str(args.lr) + \ "_predLen_" + str(args.seq_len_forecast) + \ "_actlimit" + str(args.act_limit) + \ "_num_layers_" + str(args.num_layers) + \ "_encode_" + str(args.encode_dim) + \ "_episodeLen_" + str(args.episode_len) + \ "_seqLen_" + str(args.seq_len) + \ "_decay_" + str(args.decay) + \ "_" + str(args.suffix) # Instantiating the Tensorboard writers PATH_base = 'datas/new/' PATH_base = get_output_folder(PATH_base, 'scalar_' + filename) # for eval stage reward_writer = SummaryWriter(PATH_base + '/reward') cost_writer = SummaryWriter(PATH_base + '/cost') loss_writer = SummaryWriter(PATH_base + '/loss') # load data data_path = Path("../data/Climate_Zone_" + str(args.climate_zone)) building_attributes = data_path / 'building_attributes.json' weather_file = data_path / 'weather_data.csv' solar_profile = data_path / 'solar_generation_1kW.csv' building_state_actions = 'buildings_state_action_space.json' building_ids = ["Building_1", "Building_2", "Building_3", "Building_4", "Building_5", "Building_6", "Building_7", "Building_8", "Building_9"] objective_function = ['ramping', '1-load_factor', 'average_daily_peak', 'peak_demand', 'net_electricity_consumption', 'total'] # Alias Env = CityLearn # Instantiating the env env = Env(data_path, building_attributes, weather_file, solar_profile, building_ids, buildings_states_actions=building_state_actions, cost_function=objective_function) observations_spaces, actions_spaces = env.get_state_action_spaces() # Provides information on Building type, Climate Zone, Annual DHW demand, Annual Cooling Demand, # Annual Electricity Demand, Solar Capacity, and correllations among buildings building_info = env.get_building_information() # Select many episodes for training. In the final run we will set this value to 1 (the buildings run for one year) start_episode = 0 ac_kwargs = get_agent_kwargs(args, PATH_base) rl_agents = RL_Agents(building_info, observations_spaces, actions_spaces, ac_kwargs) # initialize the model best_model_path = "./Models_best_zone" + str(args.climate_zone) model_path = './Models_' + filename if not os.path.isdir(model_path): os.mkdir(model_path) env_kwargs = dict( data_path=data_path, building_attributes=building_attributes, weather_file=weather_file, solar_profile=solar_profile, building_ids=building_ids, buildings_states_actions=building_state_actions, cost_function=objective_function ) reward_fn = reward_function MaxEpisode = args.MaxEpisode def run(time_dim, time_length, episode_maxstep): # 若time_length = 1,无需预热也可计算reward warmup_step = time_length - 1 total_step = warmup_step + episode_maxstep if args.continue_flag: print("training: Load model from episode {}.".format(args.load_episode)) rl_agents.agent.load_models(model_path, args.load_episode) log_iter = 0 # for test reward logging for e in range(MaxEpisode): if e>0 and e % args.save_per_episode == 0: rl_agents.agent.save_models(model_path, e) test(model_path, e, log_iter=log_iter) log_iter += 1 # 随机初始化开始日期,8760是一年的总小时,实际下标范围是(0, 8759) # 注意无法取到最大值,所以若total_step=1,实际最大只到8758 start_idx = np.random.randint(0, 8760 - total_step) env = Env(simulation_period=(start_idx, start_idx + total_step), **env_kwargs) # 注意要重置agent,要清空GRU记忆的状态 rl_agents.agent.reset() # 跑一个Episode,拿warmup + 正常跑的轨迹 traj, final_state, _ = run_one(env, rl_agents.agent, total_step, state=None, reset=True) # 在时间维度上拼接经验(注意state缺少final_state,后面拼) state, action, raw_reward, done = generate_experience(traj, time_dim) state_chunks, raw_reward_chunks = magic_manipulation(state, raw_reward, time_dim=time_dim, time_length=time_length) # 获取真正的奖励 # state_chunks: (Chunks, *, Time_Length, S) # raw_reward_chunks: (Chunks, *, Time_Length,) # -> rewards:(Chunks, *, 1) rewards, reward_logger = reward_fn(raw_reward_chunks, state_chunks, **reward_kwargs) rewards = rewards.swapaxes(0, -1) # -> (*, Chunks) = (*, EpisodeStep) # 切割warmup的状态,如果没有warmup,则states长度应该没变化 warmup_states, states = np.split(state, (warmup_step, ), axis=time_dim) if warmup_states.shape[time_dim] <= 0: # 如果没有warmup,放None warmup_states = None _, actions = np.split(action, (warmup_step,), axis=time_dim) _, dones = np.split(done, (warmup_step,), axis=time_dim) # 现在追加终局状态 states = np.append(states, np.expand_dims(final_state, time_dim), axis=time_dim) # 其他需要的参数都堆在这里 other = dict( init_states=warmup_states, ) # Update rl_agents.agent.add_to_buffer(states, actions, rewards, done=dones, **other) rl_agents.agent.update_agent() def print_grad(model): for name, param in model.named_parameters(): if param.requires_grad: print(name, param) def print_weight(model): print(list(model.parameters())) def test(model_path, e, log_iter): print("===============test stage start================") test_ac_kwargs = get_agent_kwargs(args, PATH_base, train=False) test_agents = RL_Agents(building_info, observations_spaces, actions_spaces, test_ac_kwargs) print("testing: Load model from episode {}.".format(e)) test_agents.agent.load_models(model_path, e) # print_grad(test_agents.agent.actor) # return env = CityLearn(**env_kwargs) state = env.reset() test_agents.agent.reset() done = False k = 0 cum_reward = {} for id in range(test_agents.n_buildings): cum_reward[id] = 0 cost = {} while not done: with torch.no_grad(): action = test_agents.select_action(state) next_state, raw_reward, done, _ = env.step(action) state = next_state if k % 1000 == 0: print("testing time step:{}, write rewards".format(k)) for id in range(test_agents.n_buildings): cum_reward[id] += raw_reward[id] reward_writer.add_scalar('building_reward_' + str(id), raw_reward[id], log_iter * 8760 + k) k += 1 # write episode-accumulated reward for r in range(test_agents.n_buildings): reward_writer.add_scalar('building_cum_reward_' + str(r), cum_reward[r], e) # write cost cost[e] = env.cost() print("cost_writer adding scalar") for i in range(len(objective_function)): cost_writer.add_scalar(str("cost_") + objective_function[i], cost[e][objective_function[i]], e) cost_writer.flush() def magic_manipulation(*arrs, time_dim=-2, time_length=24): # 其实就是对输入的多个arr进行统一分割 return [split_chunks(arr, time_dim, time_length) for arr in arrs] def split_chunks(arr, time_dim, time_length): """ :param arr: state: (9, t_len, state) reward: (9, t_len) :param time_dim: :param time_length: real_t_len = t_len - (time_length - 1) :return: (real_t_len, *, time_length, S) """ t_len = arr.shape[time_dim] # 看看总共有多少个时间步 # 生成(总时间步 * 时间片长度)的下标, real_t_len = t_len - (time_length - 1) idx = np.arange(0, real_t_len)[:, None] + np.arange(0, time_length)[None] # 这里做了三件事,首先拍扁idx # 然后在time_dim维度上按照下标,选取(总时间步 * 时间片长度)个数据 # 再分成t_len个片段,得到(t_len, *, time_length, S) arr = arr[:, idx].swapaxes(time_dim, 0) # arr = torch.FloatTensor(arr) # arr = arr.index_select(idx.flatten(), time_dim).numpy() return arr def generate_experience(traj, time_dim): # 在time_dim的位置增添1个维度,然后在这个维度上串联数据 # traj: list of tuple(state, action, reward, done), list len: total length # list(zip(*traj)): list len=3, tuple(state, action, reward, done) """ :param traj: :param time_dim: :return: for case when time_dim=1: out = [state_arr, action_arr, reward_arr, done_arr] shape: state_arr (9, tot_len, state) action_arr (9, tot_len, 2) reward_arr (9, tot_len) done_arr (9, tot_len) """ out = [] for arr in list(zip(*traj)): if np.array(arr[0]).ndim == 0: # deal with done arr = ([[x] * 9 for x in arr]) tmp = np.stack(arr, axis=time_dim) out.append(tmp) # return [np.stack(arr, axis=time_dim) for arr in list(zip(*traj))] return out def run_one(env, rl_agents, step, state=None, reset=False): Traj = [] if state is None: assert reset if reset: state = env.reset() rl_agents.reset() for _ in range(step): action = rl_agents.select_action(state) next_state, raw_reward, done, _ = env.step(action) Traj.append((state, action, raw_reward, done)) state = next_state return Traj, next_state, done run(time_dim=1, time_length=args.seq_len, episode_maxstep=args.episode_len)
[ "numpy.stack", "os.mkdir", "citylearn.CityLearn", "argparse.ArgumentParser", "os.path.isdir", "numpy.expand_dims", "agent.RL_Agents", "numpy.split", "numpy.random.randint", "numpy.arange", "numpy.array", "torch.utils.tensorboard.SummaryWriter", "model.BaseModules.ActionClipping", "collecti...
[((419, 444), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (442, 444), False, 'import argparse\n'), ((2509, 2688), 'collections.OrderedDict', 'OrderedDict', ([], {'alpha': 'args.A_r', 'beta': 'args.B_r', 'total_energy_window': 'args.window_len_A', 'heat_energy_window': 'args.window_len_B', 'price_factor': 'args.price_factor', 'ramping_window': '(6)'}), '(alpha=args.A_r, beta=args.B_r, total_energy_window=args.\n window_len_A, heat_energy_window=args.window_len_B, price_factor=args.\n price_factor, ramping_window=6)\n', (2520, 2688), False, 'from collections import OrderedDict\n'), ((6063, 6113), 'utils.io.get_output_folder', 'get_output_folder', (['PATH_base', "('scalar_' + filename)"], {}), "(PATH_base, 'scalar_' + filename)\n", (6080, 6113), False, 'from utils.io import get_output_folder\n'), ((6148, 6184), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (["(PATH_base + '/reward')"], {}), "(PATH_base + '/reward')\n", (6161, 6184), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6199, 6233), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (["(PATH_base + '/cost')"], {}), "(PATH_base + '/cost')\n", (6212, 6233), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6248, 6282), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (["(PATH_base + '/loss')"], {}), "(PATH_base + '/loss')\n", (6261, 6282), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((7606, 7678), 'agent.RL_Agents', 'RL_Agents', (['building_info', 'observations_spaces', 'actions_spaces', 'ac_kwargs'], {}), '(building_info, observations_spaces, actions_spaces, ac_kwargs)\n', (7615, 7678), False, 'from agent import RL_Agents\n'), ((4038, 4157), 'collections.OrderedDict', 'OrderedDict', ([], {'start_bound': 'args.act_limit', 'stop_bound': '(0.1)', 'decay': 'args.decay', 'step_size': '(20000)', 'warm_up': '(0)', 'verbose': '(True)'}), '(start_bound=args.act_limit, stop_bound=0.1, decay=args.decay,\n step_size=20000, warm_up=0, verbose=True)\n', (4049, 4157), False, 'from collections import OrderedDict\n'), ((7811, 7836), 'os.path.isdir', 'os.path.isdir', (['model_path'], {}), '(model_path)\n', (7824, 7836), False, 'import os\n'), ((7842, 7862), 'os.mkdir', 'os.mkdir', (['model_path'], {}), '(model_path)\n', (7850, 7862), False, 'import os\n'), ((11093, 11170), 'agent.RL_Agents', 'RL_Agents', (['building_info', 'observations_spaces', 'actions_spaces', 'test_ac_kwargs'], {}), '(building_info, observations_spaces, actions_spaces, test_ac_kwargs)\n', (11102, 11170), False, 'from agent import RL_Agents\n'), ((11346, 11369), 'citylearn.CityLearn', 'CityLearn', ([], {}), '(**env_kwargs)\n', (11355, 11369), False, 'from citylearn import CityLearn\n'), ((8920, 8959), 'numpy.random.randint', 'np.random.randint', (['(0)', '(8760 - total_step)'], {}), '(0, 8760 - total_step)\n', (8937, 8959), True, 'import numpy as np\n'), ((10073, 10119), 'numpy.split', 'np.split', (['state', '(warmup_step,)'], {'axis': 'time_dim'}), '(state, (warmup_step,), axis=time_dim)\n', (10081, 10119), True, 'import numpy as np\n'), ((10253, 10300), 'numpy.split', 'np.split', (['action', '(warmup_step,)'], {'axis': 'time_dim'}), '(action, (warmup_step,), axis=time_dim)\n', (10261, 10300), True, 'import numpy as np\n'), ((10320, 10365), 'numpy.split', 'np.split', (['done', '(warmup_step,)'], {'axis': 'time_dim'}), '(done, (warmup_step,), axis=time_dim)\n', (10328, 10365), True, 'import numpy as np\n'), ((14200, 14228), 'numpy.stack', 'np.stack', (['arr'], {'axis': 'time_dim'}), '(arr, axis=time_dim)\n', (14208, 14228), True, 'import numpy as np\n'), ((10420, 10457), 'numpy.expand_dims', 'np.expand_dims', (['final_state', 'time_dim'], {}), '(final_state, time_dim)\n', (10434, 10457), True, 'import numpy as np\n'), ((11593, 11608), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11606, 11608), False, 'import torch\n'), ((13103, 13127), 'numpy.arange', 'np.arange', (['(0)', 'real_t_len'], {}), '(0, real_t_len)\n', (13112, 13127), True, 'import numpy as np\n'), ((13139, 13164), 'numpy.arange', 'np.arange', (['(0)', 'time_length'], {}), '(0, time_length)\n', (13148, 13164), True, 'import numpy as np\n'), ((3340, 3379), 'collections.OrderedDict', 'OrderedDict', ([], {'num_layers': 'args.num_layers'}), '(num_layers=args.num_layers)\n', (3351, 3379), False, 'from collections import OrderedDict\n'), ((3525, 3604), 'collections.OrderedDict', 'OrderedDict', ([], {'input_size': 'encode_dim', 'latent_size': 'latent_dim', 'action_size': 'act_dim'}), '(input_size=encode_dim, latent_size=latent_dim, action_size=act_dim)\n', (3536, 3604), False, 'from collections import OrderedDict\n'), ((3680, 3759), 'collections.OrderedDict', 'OrderedDict', ([], {'input_size': 'encode_dim', 'output_size': 'act_dim', 'latent_size': 'latent_dim'}), '(input_size=encode_dim, output_size=act_dim, latent_size=latent_dim)\n', (3691, 3759), False, 'from collections import OrderedDict\n'), ((4488, 4501), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4499, 4501), False, 'from collections import OrderedDict\n'), ((4526, 4539), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4537, 4539), False, 'from collections import OrderedDict\n'), ((4559, 4572), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (4570, 4572), False, 'from collections import OrderedDict\n'), ((4798, 4871), 'collections.OrderedDict', 'OrderedDict', ([], {'lr': 'default_lr', 'betas': '(0.9, 0.999)', 'eps': '(1e-08)', 'weight_decay': '(0)'}), '(lr=default_lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)\n', (4809, 4871), False, 'from collections import OrderedDict\n'), ((5409, 5452), 'model.BaseModules.ActionClipping', 'ActionClipping', (['model'], {}), '(model, **action_clip_kwargs)\n', (5423, 5452), False, 'from model.BaseModules import ActionClipping\n'), ((14097, 14113), 'numpy.array', 'np.array', (['arr[0]'], {}), '(arr[0])\n', (14105, 14113), True, 'import numpy as np\n'), ((3963, 3977), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (3975, 3977), True, 'import torch.nn as nn\n')]
from __future__ import division import scipy.signal as sig import numpy as np from .utility import disambiguate_params, As_from_beta try: from math import gcd except: from fractions import gcd # global cache of resamplers _precomputed_filters = {} def compute_filt(up, down, fc='nn', beta=5.0, N=32001, return_fc=False): r""" Computes a filter to resample a signal from rate "down" to rate "up" Parameters ---------- up : int The upsampling factor. down : int The downsampling factor. fc : float or string (optional) cutoff frequency (normalized to Nyquist, f_s/2) or type of method to determine fc. Options are "nn" (null-on-Nyquist), 'kaiser' (edge of transition band as given by formula by Kaiser), or 'standard' (middle of transition band). beta : float (optional) Beta factor for Kaiser window. Determines tradeoff between stopband attenuation and transition band width N : int (optional) FIR filter order. Determines stopband attenuation. The higher the better, ath the cost of complexity. return_fc : bool If true, fc (the numerical value) is returned as well. Default false. Returns ------- filt : array The FIR filter coefficients Notes ----- This function is to be used if you want to manage your own filters to be used with scipy.signal.resample_poly (use the `window=...` parameter). WARNING: Some versions (at least 0.19.1) of scipy modify the passed filter, so make sure to make a copy beforehand: out = scipy.signal.resample_poly(in up, down, window=numpy.array(filt)) """ # see explanation in resample below if up==down: raise ValueError('upsampling and downsampling rate cannot be the same.') # Determine our up and down factors g = gcd(up, down) up = up//g down = down//g max_rate = max(up, down) sfact = np.sqrt(1+(beta/np.pi)**2) if isinstance(fc, float): pass # the "standard" way to generate the filter is to just place fc on the # Nyquist frequency, which results in considerable aliasing but is # neccesary for perfect reconstruction multirate filterbanks but not # for audio resampling! Included here mostly for completeness and # comparison purposes. elif fc == 'standard': fc = 1/max_rate # The paper by Kaiser gives a formula for the neccesary length of the # filter given a desired stopband attenuation and transition band width; # conversly, we can determine the transition band width from the stop # band attenuation and filter length. This allows us to shift fc. elif fc == 'kaiser' or fc == 'Kaiser': As = As_from_beta(beta) offset = (As-7.95)/(14.36*N) fc = (1/max_rate)-offset # The null-on-Nyquist method: the reason I wrote this package in the first # place. My argument is that the cutoff frequency should be on the border # between the main lobe of the filter and the first sidelobe; this should # give the best tradeoff between retaining the desired signal and # suppressing aliasing. elif fc == 'nn': # This is a two-step procedure. First we generate a filter in the # 'normal' way: with 6dB attenuation at Falsef_c. init_filt = sig.fir_filter_design.firwin(N, 1/max_rate, window=('kaiser', beta)) # Next, find the first null. Convert the filter into frequency domain. N_FFT = 2**19 NBINS = N_FFT/2+1 paddedfilt = np.zeros(N_FFT) paddedfilt[:N] = init_filt ffilt = np.fft.rfft(paddedfilt) # Now find the minimum between f_c and f_c+sqrt(1+(beta/pi)^2)/L bot = int(np.floor(NBINS/max_rate)) top = int(np.ceil(NBINS*(1/max_rate + 2*sfact/N))) firstnull = (np.argmin(np.abs(ffilt[bot:top])) + bot)/NBINS # get the new fc fc = -firstnull+2/max_rate else: raise ValueError('Unknown option for fc in compute_filt') # Now we can generate the desired filter f = sig.fir_filter_design.firwin(N, fc, window=('kaiser', beta)) if return_fc: return f, fc else: return f def resample(s, up, down, axis=0, fc='nn', **kwargs): r""" Resample a signal from rate "down" to rate "up" Parameters ---------- s : array_like The data to be resampled. up : int The upsampling factor. down : int The downsampling factor. axis : int, optional The axis of `x` that is resampled. Default is 0. As : float (optional) Stopband attenuation in dB N : float (optional) Filter order (length of impulse response in samples) df : float (optional) Transition band width, normalized to Nyquist (fs/2) beta : float (optional) The beta parameter of the Kaiser window Returns ------- resampled_x : array The resampled array. Notes ----- The function keeps a global cache of filters, since they are determined entirely by up, down, fc, beta, and L. If a filter has previously been used it is looked up instead of being recomputed. """ # BUG FIX: if up==down, sig.fir_filter_design.firwin will throw # an exception. In compute_filt that is OK (the user is assumed # to know what they are doing if they use that function), but in # the "user-friendly" resample function, we should just silently # return a copy of the input. (Principle of least surprise) # Thanks to johndoe46 on github for pointing this out. if up==down: return np.array(s) # from design parameters, find the generative parameters N, beta, As = disambiguate_params(**kwargs) # check if a resampling filter with the chosen parameters already exists params = (up, down, fc, beta, N) if params in _precomputed_filters.keys(): # if so, use it. filt = _precomputed_filters[params] else: # if not, generate filter, store it, use it filt = compute_filt(up, down, fc, beta=beta, N=N) _precomputed_filters[params] = filt return sig.resample_poly(s, up, down, window=np.array(filt), axis=axis)
[ "fractions.gcd", "numpy.fft.rfft", "numpy.abs", "numpy.ceil", "numpy.floor", "numpy.zeros", "numpy.array", "scipy.signal.fir_filter_design.firwin", "numpy.sqrt" ]
[((1876, 1889), 'fractions.gcd', 'gcd', (['up', 'down'], {}), '(up, down)\n', (1879, 1889), False, 'from fractions import gcd\n'), ((1966, 1998), 'numpy.sqrt', 'np.sqrt', (['(1 + (beta / np.pi) ** 2)'], {}), '(1 + (beta / np.pi) ** 2)\n', (1973, 1998), True, 'import numpy as np\n'), ((4152, 4212), 'scipy.signal.fir_filter_design.firwin', 'sig.fir_filter_design.firwin', (['N', 'fc'], {'window': "('kaiser', beta)"}), "(N, fc, window=('kaiser', beta))\n", (4180, 4212), True, 'import scipy.signal as sig\n'), ((5710, 5721), 'numpy.array', 'np.array', (['s'], {}), '(s)\n', (5718, 5721), True, 'import numpy as np\n'), ((6276, 6290), 'numpy.array', 'np.array', (['filt'], {}), '(filt)\n', (6284, 6290), True, 'import numpy as np\n'), ((3357, 3427), 'scipy.signal.fir_filter_design.firwin', 'sig.fir_filter_design.firwin', (['N', '(1 / max_rate)'], {'window': "('kaiser', beta)"}), "(N, 1 / max_rate, window=('kaiser', beta))\n", (3385, 3427), True, 'import scipy.signal as sig\n'), ((3624, 3639), 'numpy.zeros', 'np.zeros', (['N_FFT'], {}), '(N_FFT)\n', (3632, 3639), True, 'import numpy as np\n'), ((3691, 3714), 'numpy.fft.rfft', 'np.fft.rfft', (['paddedfilt'], {}), '(paddedfilt)\n', (3702, 3714), True, 'import numpy as np\n'), ((3807, 3833), 'numpy.floor', 'np.floor', (['(NBINS / max_rate)'], {}), '(NBINS / max_rate)\n', (3815, 3833), True, 'import numpy as np\n'), ((3851, 3898), 'numpy.ceil', 'np.ceil', (['(NBINS * (1 / max_rate + 2 * sfact / N))'], {}), '(NBINS * (1 / max_rate + 2 * sfact / N))\n', (3858, 3898), True, 'import numpy as np\n'), ((3923, 3945), 'numpy.abs', 'np.abs', (['ffilt[bot:top]'], {}), '(ffilt[bot:top])\n', (3929, 3945), True, 'import numpy as np\n')]
import torch import torch.nn as nn import random import math import datetime #import adabound import os import numpy as np import cv2 from torch.utils.data import Dataset, DataLoader from torchvision import utils from torch.nn import functional as F from torch.autograd import Variable from torch.nn import Parameter from sklearn.svm import LinearSVC from sklearn.svm import SVC def dt(): return datetime.datetime.now().strftime('%H:%M:%S') def l2_norm(input,axis=1): norm = torch.norm(input,2,axis,True)+(1e-12) #print(norm) output = torch.div(input, norm) return output def train_softmax(model, criterion, optimizer, trainloader, use_gpu, epoch, num_classes): model.train() model.feature = False trainloss = 0 for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() _, outputs = model(data) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() trainloss += loss.item() if batch_idx % 10 == 0: print(dt(), 'epoch=%d batch#%d batchloss=%.4f averLoss=%.4f' % (epoch, batch_idx, loss.item(), trainloss / (batch_idx + 1))) def train_centerloss(model, criterion_xent, criterion_cent, optimizer_model, optimizer_centloss, trainloader, use_gpu, epoch, coeff=0.005): model.train() model.feature = False trainloss = 0 for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features, outputs = model(data) loss_xent = criterion_xent(outputs, labels) loss_cent = criterion_cent(features, labels) loss = loss_xent + coeff*loss_cent optimizer_model.zero_grad() optimizer_centloss.zero_grad() loss.backward() optimizer_model.step() optimizer_centloss.step() trainloss += loss.item() if batch_idx % 10 == 0: print(dt(), 'epoch=%d batch#%d batchloss=%.4f averLoss=%.4f, loss_xent=%.4f, loss_centws=%.4f' % (epoch, batch_idx, loss.item(), trainloss / (batch_idx + 1), loss_xent.item(), loss_cent.item())) def train_centerloss(model, criterion_xent, criterion_cent, optimizer_model, optimizer_centloss, trainloader, use_gpu, epoch, coeff=0.005): model.train() model.feature = False trainloss = 0 l2loss = 0 for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features, outputs = model(data) loss_xent = criterion_xent(outputs, labels) loss_cent = criterion_cent(features, labels) loss = loss_xent + coeff*loss_cent optimizer_model.zero_grad() optimizer_centloss.zero_grad() loss.backward() optimizer_model.step() optimizer_centloss.step() trainloss += loss.item() if batch_idx % 10 == 0: print(dt(), 'epoch=%d batch#%d batchloss=%.4f averLoss=%.4f, loss_xent=%.4f, loss_centws=%.4f' % (epoch, batch_idx, loss.item(), trainloss / (batch_idx + 1), loss_xent.item(), loss_cent.item())) def train_arc(model, criterion, criterion_arc, optimizer, trainloader, use_gpu, epoch, num_classes): model.train() model.feature = False trainloss = 0 for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features, outputs = model(data) loss = criterion(criterion_arc(features, labels), labels) optimizer.zero_grad() loss.backward() optimizer.step() trainloss += loss.item() if batch_idx % 10 == 0: print(dt(), 'epoch=%d batch#%d batchloss=%.4f averLoss=%.4f' % (epoch, batch_idx, loss.item(), trainloss / (batch_idx + 1))) def train_sphere(model, criterion_sphere, optimizer_model, trainloader, use_gpu, epoch): model.train() model.feature = False trainloss = 0 for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features, outputs = model(data) loss = criterion_sphere(outputs, labels) optimizer_model.zero_grad() loss.backward() optimizer_model.step() trainloss += loss.item() if batch_idx % 10 == 0: print(dt(), 'epoch=%d batch#%d batchloss=%.4f averLoss=%.4f' % (epoch, batch_idx, loss.item(), trainloss / (batch_idx + 1))) """ center loss, ECCV 2016, the full loss should be centerloss + softmaxloss """ class CenterLoss(nn.Module): def __init__(self, num_classes=10574, feat_dim=64, use_gpu=True): super(CenterLoss, self).__init__() self.num_classes = num_classes self.feat_dim = feat_dim self.use_gpu = use_gpu if self.use_gpu: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim).cuda()) else: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim)) def forward(self, x, labels): batch_centers = self.centers[labels, :] diff = (batch_centers - x) loss = diff.pow(2).sum(1).clamp(min=1e-12, max=1e+12).mean() return loss class SlimLoss(nn.Module): def __init__(self, num_classes=10574, feat_dim=64, use_gpu=True): super(SlimLoss, self).__init__() self.num_classes = num_classes self.feat_dim = feat_dim self.use_gpu = use_gpu self.cossim = nn.CosineSimilarity if self.use_gpu: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim).cuda()) else: self.centers = nn.Parameter(torch.randn(self.num_classes, self.feat_dim)) def forward(self, x, labels): batch_centers = self.centers[labels, :] diff = 1-self.cossim(x, batch_centers) loss = diff.pow(2).sum(1).clamp(min=1e-12, max=1e+12).mean() """ Arcface ArcFace: Additive Angular Margin Loss for Deep Face Recognition """ class Arcface(nn.Module): # implementation of additive margin softmax loss in https://arxiv.org/abs/1801.05599 def __init__(self, embedding_size=512, classnum=28, s=64., m=0.5): super(Arcface, self).__init__() self.classnum = classnum self.kernel = nn.Parameter(torch.Tensor(embedding_size,classnum)) # initial kernel self.kernel.data.uniform_(-1, 1).renorm_(2,1,1e-5).mul_(1e5) self.m = m # the margin value, default is 0.5 self.s = s # scalar value default is 64, see normface https://arxiv.org/abs/1704.06369 self.cos_m = math.cos(m) self.sin_m = math.sin(m) self.mm = self.sin_m * m # issue 1 self.threshold = math.cos(math.pi - m) def forward(self, embbedings, label): # weights norm nB = len(embbedings) kernel_norm = l2_norm(self.kernel,axis=0) # cos(theta+m) cos_theta = torch.mm(embbedings,kernel_norm) # output = torch.mm(embbedings,kernel_norm) cos_theta = cos_theta.clamp(-1,1) # for numerical stability cos_theta_2 = torch.pow(cos_theta, 2) sin_theta_2 = 1 - cos_theta_2 sin_theta = torch.sqrt(sin_theta_2) cos_theta_m = (cos_theta * self.cos_m - sin_theta * self.sin_m) # this condition controls the theta+m should in range [0, pi] # 0<=theta+m<=pi # -m<=theta<=pi-m cond_v = cos_theta - self.threshold cond_mask = cond_v <= 0 keep_val = (cos_theta - self.mm) # when theta not in [0,pi], use cosface instead cos_theta_m[cond_mask] = keep_val[cond_mask] output = cos_theta * 1.0 # a little bit hacky way to prevent in_place operation on cos_theta idx_ = torch.arange(0, nB, dtype=torch.long) output[idx_, label] = cos_theta_m[idx_, label] output *= self.s # scale up in order to make softmax work, first introduced in normface return output """ Angle Loss """ def myphi(x,m): x = x * m return 1-x**2/math.factorial(2)+x**4/math.factorial(4)-x**6/math.factorial(6) + \ x**8/math.factorial(8) - x**9/math.factorial(9) class AngleLinear(nn.Module): def __init__(self, in_features, num_classes, m = 4, phiflag=True): super(AngleLinear, self).__init__() self.in_features = in_features self.out_features = num_classes self.weight = Parameter(torch.Tensor(in_features,num_classes)) self.weight.data.uniform_(-1, 1).renorm_(2,1,1e-5).mul_(1e5) self.phiflag = phiflag self.m = m self.mlambda = [ lambda x: x**0, lambda x: x**1, lambda x: 2*x**2-1, lambda x: 4*x**3-3*x, lambda x: 8*x**4-8*x**2+1, lambda x: 16*x**5-20*x**3+5*x ] def forward(self, input): x = input # size=(B,F) F is feature len w = self.weight # size=(F,Classnum) F=in_features Classnum=out_features ww = w.renorm(2,1,1e-5).mul(1e5) xlen = x.pow(2).sum(1).pow(0.5) # size=B wlen = ww.pow(2).sum(0).pow(0.5) # size=Classnum cos_theta = x.mm(ww) # size=(B,Classnum) cos_theta = cos_theta / xlen.view(-1,1) / wlen.view(1,-1) cos_theta = cos_theta.clamp(-1,1) if self.phiflag: cos_m_theta = self.mlambda[self.m](cos_theta) theta = Variable(cos_theta.data.acos()) k = (self.m*theta/3.14159265).floor() n_one = k*0.0 - 1 phi_theta = (n_one**k) * cos_m_theta - 2*k else: theta = cos_theta.acos() phi_theta = myphi(theta,self.m) phi_theta = phi_theta.clamp(-1*self.m,1) cos_theta = cos_theta * xlen.view(-1,1) phi_theta = phi_theta * xlen.view(-1,1) output = (cos_theta,phi_theta) return output # size=(B,Classnum,2) class AngleLoss(nn.Module): def __init__(self, gamma=0): super(AngleLoss, self).__init__() self.gamma = gamma self.it = 0 self.LambdaMin = 5.0 self.LambdaMax = 1500.0 self.lamb = 1500.0 def forward(self, input, target): self.it += 1 cos_theta,phi_theta = input target = target.view(-1,1) #size=(B,1) index = cos_theta.data * 0.0 #size=(B,Classnum) index.scatter_(1,target.data.view(-1,1),1) index = index.byte() index = Variable(index) self.lamb = max(self.LambdaMin,self.LambdaMax/(1+0.1*self.it )) output = cos_theta * 1.0 #size=(B,Classnum) output[index] -= cos_theta[index]*(1.0+0)/(1+self.lamb) output[index] += phi_theta[index]*(1.0+0)/(1+self.lamb) logpt = F.log_softmax(output) logpt = logpt.gather(1,target) logpt = logpt.view(-1) pt = Variable(logpt.data.exp()) loss = -1 * (1-pt)**self.gamma * logpt loss = loss.mean() return loss """ this kernel does not work """ def cosine_kernel(X,Y): return np.dot(X, Y.T)/(np.linalg.norm(X)*np.linalg.norm(Y)) def save_model(model, filename): state = model.state_dict() for key in state: state[key] = state[key].clone().cpu() torch.save(state, filename) def KFold(n=1200, n_folds=5, shuffle=False): folds = [] base = list(range(n)) for i in range(n_folds): test = base[i*n//n_folds:(i+1)*n//n_folds] train = list(set(base)-set(test)) folds.append([train,test]) return folds def eval_acc(threshold, diff): y_true = [] y_predict = [] for d in diff: same = 1 if float(d[0]) > threshold else 0 y_predict.append(same) y_true.append(int(d[1])) y_true = np.array(y_true) y_predict = np.array(y_predict) accuracy = 1.0*np.count_nonzero(y_true==y_predict)/len(y_true) return accuracy """ not recommend, only used for NN classification """ def evaluate_pure_pytorch(model, testloader, use_gpu, epoch): model.eval() model.feature = False train_features, train_labels = [], [] test_features, test_labels = [], [] correct = 0 total = 0 with torch.no_grad(): for batch_idx, (data, labels) in enumerate(testloader): if use_gpu: data, labels = data.cuda(), labels _, output = model(data) _, predicted = torch.max(output.data.cpu(), 1) total += labels.size(0) correct += (predicted == labels).sum().item() acc = float(correct)/total print('epoch= %d, svm classification accuracy: %.4f' % (epoch, acc)) return acc """ cosine distance verification test """ def find_best_threshold(thresholds, predicts): best_threshold = best_acc = 0 for threshold in thresholds: accuracy = eval_acc(threshold, predicts) if accuracy >= best_acc: best_acc = accuracy best_threshold = threshold return best_threshold def evaluate(model, testloader, use_gpu, epoch): model.eval() #ignore the classifier model.feature = True predicts = [] with torch.no_grad(): for batch_idx, (img1, img2, sameflag) in enumerate(testloader): if use_gpu: img1 = img1.float().cuda() img2 = img2.float().cuda() else: img1 = img1.float() img2 = img2.float() f1 = model(img1) f2 = model(img2) for i in range(len(f1)): cosdistance = f1[i].view(1, -1).mm(f2[i].view(-1, 1)) / (f1[i].norm() * f2[i].norm() + 1e-5) # predicts.append('{}\t{}\n'.format(cosdistance, sameflag[i])) if use_gpu: predicts.append((cosdistance.cpu().item(), sameflag[i].item())) else: predicts.append((cosdistance.item(), sameflag[i].item())) accuracy = [] thd = [] folds = KFold(n=4272, n_folds=4, shuffle=False) thresholds = np.arange(-1.0, 1.0, 0.005) # cosine distance for idx, (train, test) in enumerate(folds): best_thresh = find_best_threshold(thresholds, [predicts[i] for i in train]) accuracy.append(eval_acc(best_thresh, [predicts[i] for i in test])) thd.append(best_thresh) print('Epoch={} acc={:.4f} std={:.4f} thd={:.4f}'.format(epoch, np.mean(accuracy), np.std(accuracy), np.mean(thd))) return np.mean(accuracy), np.std(accuracy), np.mean(thd) def evaluate_identification(model, trainloader, testloader, use_gpu, epoch): model.eval() model.feature = True train_features, train_labels = [], [] test_features, test_labels = [], [] with torch.no_grad(): for batch_idx, (data, labels) in enumerate(trainloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features = model(data) if use_gpu: train_features.append(features.data.cpu().numpy()) train_labels.append(labels.data.cpu().numpy()) else: train_features.append(features.data.numpy()) train_labels.append(labels.data.numpy()) train_features = np.concatenate(train_features, 0) train_labels = np.concatenate(train_labels, 0) with torch.no_grad(): for batch_idx, (data, labels) in enumerate(testloader): if use_gpu: data, labels = data.cuda(), labels.cuda() features = model(data) if use_gpu: test_features.append(features.data.cpu().numpy()) test_labels.append(labels.data.cpu().numpy()) else: test_features.append(features.data.numpy()) test_labels.append(labels.data.numpy()) test_features = np.concatenate(test_features, 0) test_labels = np.concatenate(test_labels, 0) #svm_model = XGBClassifier() #svm_model = LinearSVC(C=100, random_state=42, max_iter=5000) svm_model = LinearSVC(C=1, random_state=42) svm_model.fit(train_features, train_labels) labels_pred = svm_model.predict(test_features) #scores = svm_model.predict_proba(test_features) #scores_max = scores[range(len(scores)), scores.argmax(axis=1)] acc_test = np.sum(np.array(labels_pred) == np.array(test_labels)) / len(test_labels) print('epoch= %d, svm classification accuracy: %.4f' % (epoch, acc_test)) return acc_test
[ "torch.sqrt", "torch.mm", "torch.randn", "numpy.mean", "numpy.arange", "torch.arange", "numpy.linalg.norm", "torch.no_grad", "numpy.std", "torch.Tensor", "math.cos", "torch.nn.functional.log_softmax", "sklearn.svm.LinearSVC", "datetime.datetime.now", "torch.norm", "torch.autograd.Varia...
[((553, 575), 'torch.div', 'torch.div', (['input', 'norm'], {}), '(input, norm)\n', (562, 575), False, 'import torch\n'), ((11453, 11480), 'torch.save', 'torch.save', (['state', 'filename'], {}), '(state, filename)\n', (11463, 11480), False, 'import torch\n'), ((11961, 11977), 'numpy.array', 'np.array', (['y_true'], {}), '(y_true)\n', (11969, 11977), True, 'import numpy as np\n'), ((11994, 12013), 'numpy.array', 'np.array', (['y_predict'], {}), '(y_predict)\n', (12002, 12013), True, 'import numpy as np\n'), ((14232, 14259), 'numpy.arange', 'np.arange', (['(-1.0)', '(1.0)', '(0.005)'], {}), '(-1.0, 1.0, 0.005)\n', (14241, 14259), True, 'import numpy as np\n'), ((16242, 16273), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {'C': '(1)', 'random_state': '(42)'}), '(C=1, random_state=42)\n', (16251, 16273), False, 'from sklearn.svm import LinearSVC\n'), ((485, 517), 'torch.norm', 'torch.norm', (['input', '(2)', 'axis', '(True)'], {}), '(input, 2, axis, True)\n', (495, 517), False, 'import torch\n'), ((6875, 6886), 'math.cos', 'math.cos', (['m'], {}), '(m)\n', (6883, 6886), False, 'import math\n'), ((6908, 6919), 'math.sin', 'math.sin', (['m'], {}), '(m)\n', (6916, 6919), False, 'import math\n'), ((6989, 7010), 'math.cos', 'math.cos', (['(math.pi - m)'], {}), '(math.pi - m)\n', (6997, 7010), False, 'import math\n'), ((7198, 7231), 'torch.mm', 'torch.mm', (['embbedings', 'kernel_norm'], {}), '(embbedings, kernel_norm)\n', (7206, 7231), False, 'import torch\n'), ((7373, 7396), 'torch.pow', 'torch.pow', (['cos_theta', '(2)'], {}), '(cos_theta, 2)\n', (7382, 7396), False, 'import torch\n'), ((7455, 7478), 'torch.sqrt', 'torch.sqrt', (['sin_theta_2'], {}), '(sin_theta_2)\n', (7465, 7478), False, 'import torch\n'), ((8015, 8052), 'torch.arange', 'torch.arange', (['(0)', 'nB'], {'dtype': 'torch.long'}), '(0, nB, dtype=torch.long)\n', (8027, 8052), False, 'import torch\n'), ((10681, 10696), 'torch.autograd.Variable', 'Variable', (['index'], {}), '(index)\n', (10689, 10696), False, 'from torch.autograd import Variable\n'), ((10967, 10988), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['output'], {}), '(output)\n', (10980, 10988), True, 'from torch.nn import functional as F\n'), ((11263, 11277), 'numpy.dot', 'np.dot', (['X', 'Y.T'], {}), '(X, Y.T)\n', (11269, 11277), True, 'import numpy as np\n'), ((12384, 12399), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (12397, 12399), False, 'import torch\n'), ((13346, 13361), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (13359, 13361), False, 'import torch\n'), ((14650, 14667), 'numpy.mean', 'np.mean', (['accuracy'], {}), '(accuracy)\n', (14657, 14667), True, 'import numpy as np\n'), ((14669, 14685), 'numpy.std', 'np.std', (['accuracy'], {}), '(accuracy)\n', (14675, 14685), True, 'import numpy as np\n'), ((14687, 14699), 'numpy.mean', 'np.mean', (['thd'], {}), '(thd)\n', (14694, 14699), True, 'import numpy as np\n'), ((14914, 14929), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14927, 14929), False, 'import torch\n'), ((15431, 15464), 'numpy.concatenate', 'np.concatenate', (['train_features', '(0)'], {}), '(train_features, 0)\n', (15445, 15464), True, 'import numpy as np\n'), ((15488, 15519), 'numpy.concatenate', 'np.concatenate', (['train_labels', '(0)'], {}), '(train_labels, 0)\n', (15502, 15519), True, 'import numpy as np\n'), ((15530, 15545), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15543, 15545), False, 'import torch\n'), ((16041, 16073), 'numpy.concatenate', 'np.concatenate', (['test_features', '(0)'], {}), '(test_features, 0)\n', (16055, 16073), True, 'import numpy as np\n'), ((16096, 16126), 'numpy.concatenate', 'np.concatenate', (['test_labels', '(0)'], {}), '(test_labels, 0)\n', (16110, 16126), True, 'import numpy as np\n'), ((401, 424), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (422, 424), False, 'import datetime\n'), ((6572, 6610), 'torch.Tensor', 'torch.Tensor', (['embedding_size', 'classnum'], {}), '(embedding_size, classnum)\n', (6584, 6610), False, 'import torch\n'), ((8404, 8421), 'math.factorial', 'math.factorial', (['(9)'], {}), '(9)\n', (8418, 8421), False, 'import math\n'), ((8679, 8717), 'torch.Tensor', 'torch.Tensor', (['in_features', 'num_classes'], {}), '(in_features, num_classes)\n', (8691, 8717), False, 'import torch\n'), ((11279, 11296), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {}), '(X)\n', (11293, 11296), True, 'import numpy as np\n'), ((11297, 11314), 'numpy.linalg.norm', 'np.linalg.norm', (['Y'], {}), '(Y)\n', (11311, 11314), True, 'import numpy as np\n'), ((12033, 12070), 'numpy.count_nonzero', 'np.count_nonzero', (['(y_true == y_predict)'], {}), '(y_true == y_predict)\n', (12049, 12070), True, 'import numpy as np\n'), ((14587, 14604), 'numpy.mean', 'np.mean', (['accuracy'], {}), '(accuracy)\n', (14594, 14604), True, 'import numpy as np\n'), ((14606, 14622), 'numpy.std', 'np.std', (['accuracy'], {}), '(accuracy)\n', (14612, 14622), True, 'import numpy as np\n'), ((14624, 14636), 'numpy.mean', 'np.mean', (['thd'], {}), '(thd)\n', (14631, 14636), True, 'import numpy as np\n'), ((5182, 5226), 'torch.randn', 'torch.randn', (['self.num_classes', 'self.feat_dim'], {}), '(self.num_classes, self.feat_dim)\n', (5193, 5226), False, 'import torch\n'), ((5932, 5976), 'torch.randn', 'torch.randn', (['self.num_classes', 'self.feat_dim'], {}), '(self.num_classes, self.feat_dim)\n', (5943, 5976), False, 'import torch\n'), ((8379, 8396), 'math.factorial', 'math.factorial', (['(8)'], {}), '(8)\n', (8393, 8396), False, 'import math\n'), ((16516, 16537), 'numpy.array', 'np.array', (['labels_pred'], {}), '(labels_pred)\n', (16524, 16537), True, 'import numpy as np\n'), ((16541, 16562), 'numpy.array', 'np.array', (['test_labels'], {}), '(test_labels)\n', (16549, 16562), True, 'import numpy as np\n'), ((8340, 8357), 'math.factorial', 'math.factorial', (['(6)'], {}), '(6)\n', (8354, 8357), False, 'import math\n'), ((5075, 5119), 'torch.randn', 'torch.randn', (['self.num_classes', 'self.feat_dim'], {}), '(self.num_classes, self.feat_dim)\n', (5086, 5119), False, 'import torch\n'), ((5817, 5861), 'torch.randn', 'torch.randn', (['self.num_classes', 'self.feat_dim'], {}), '(self.num_classes, self.feat_dim)\n', (5828, 5861), False, 'import torch\n'), ((8317, 8334), 'math.factorial', 'math.factorial', (['(4)'], {}), '(4)\n', (8331, 8334), False, 'import math\n'), ((8294, 8311), 'math.factorial', 'math.factorial', (['(2)'], {}), '(2)\n', (8308, 8311), False, 'import math\n')]
""" @author: <NAME> <<EMAIL>> """ import tensorflow as tf from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession import numpy as np import cv2 import argparse from collections import deque from src.model import CLASS_IDS from src.utils import get_overlay, get_images HAND_GESTURES = ["Open", "Closed"] WHITE_RGB = (255, 255, 255) GREEN_RGB = (0, 255, 0) PURPLE_RGB = (255, 0, 127) def get_args(): parser = argparse.ArgumentParser( """Implementation of Google's Quick Draw Project (https://quickdraw.withgoogle.com/#)""") parser.add_argument("-a", "--area", type=int, default=3000, help="Minimum area of captured object") parser.add_argument("-l", "--load_path", type=str, default="data/trained_models") parser.add_argument("-s", "--save_video", type=str, default="data/output.mp4") args = parser.parse_args() return args def load_graph(path): config = ConfigProto() config.gpu_options.allow_growth = True InteractiveSession(config=config) detection_graph = tf.Graph() with detection_graph.as_default(): graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile(path, 'rb') as fid: graph_def.ParseFromString(fid.read()) tf.import_graph_def(graph_def, name='') sess = tf.compat.v1.Session(graph=detection_graph) return detection_graph, sess def detect_hands(image, graph, sess): input_image = graph.get_tensor_by_name('image_tensor:0') detection_boxes = graph.get_tensor_by_name('detection_boxes:0') detection_scores = graph.get_tensor_by_name('detection_scores:0') detection_classes = graph.get_tensor_by_name('detection_classes:0') image = image[None, :, :, :] boxes, scores, classes = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict={input_image: image}) return np.squeeze(boxes), np.squeeze(scores), np.squeeze(classes) def predict(boxes, scores, classes, threshold, width, height, num_hands=2): count = 0 results = {} for box, score, class_ in zip(boxes[:num_hands], scores[:num_hands], classes[:num_hands]): if score > threshold: y_min = int(box[0] * height) x_min = int(box[1] * width) y_max = int(box[2] * height) x_max = int(box[3] * width) category = HAND_GESTURES[int(class_) - 1] results[count] = [x_min, x_max, y_min, y_max, category] count += 1 return results def main(opt): graph, sess = load_graph("data/pretrained_model.pb") model = tf.keras.models.load_model(opt.load_path) cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) out = cv2.VideoWriter(opt.save_video, cv2.VideoWriter_fourcc(*"MJPG"), int(cap.get(cv2.CAP_PROP_FPS)), (640, 480)) points = deque(maxlen=1024) canvas = np.zeros((480, 640, 3), dtype=np.uint8) is_drawing = False is_shown = False predicted_class = None class_images = get_images("images", CLASS_IDS.values()) while True: key = cv2.waitKey(10) if key == ord("q"): break elif key == ord(" "): is_drawing = not is_drawing if is_drawing: if is_shown: points = deque(maxlen=1024) canvas = np.zeros((480, 640, 3), dtype=np.uint8) is_shown = False if not is_drawing and not is_shown: if len(points): canvas_gs = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY) # Blur image median = cv2.medianBlur(canvas_gs, 9) gaussian = cv2.GaussianBlur(median, (5, 5), 0) # Otsu's thresholding _, thresh = cv2.threshold(gaussian, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) contour_gs, _ = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) if len(contour_gs): contour = sorted(contour_gs, key=cv2.contourArea, reverse=True)[0] # Check if the largest contour satisfy the condition of minimum area if cv2.contourArea(contour) > opt.area: x, y, w, h = cv2.boundingRect(contour) image = canvas_gs[y:y + h, x:x + w] image = cv2.resize(image, (28, 28)) image = np.array(image, dtype=np.float32)[None, :, :, None] / 255 image = tf.convert_to_tensor(image) predictions = model.predict(image) score = tf.nn.softmax(predictions[0]) predicted_class = np.argmax(score) is_shown = True else: print("The object drawn is too small. Please draw a bigger one!") points = deque(maxlen=1024) canvas = np.zeros((480, 640, 3), dtype=np.uint8) # Read frame from camera ret, frame = cap.read() if frame is None: continue frame = cv2.flip(frame, 1) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) boxes, scores, classes = detect_hands(frame, graph, sess) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) results = predict(boxes, scores, classes, 0.6, 640, 480) # Check to see if any contours are found if len(results) == 1: x_min, x_max, y_min, y_max, category = results[0] x = int((x_min + x_max) / 2) y = int((y_min + y_max) / 2) cv2.circle(frame, (x, y), 5, (0, 0, 255), -1) if is_drawing: if category == "Closed": points.appendleft((x, y, 1)) else: points.appendleft((x, y, 0)) for i in range(1, len(points)): if points[i - 1] is None or points[i - 1][2] == 0 or points[i] is None: continue cv2.line(canvas, points[i - 1][:2], points[i][:2], WHITE_RGB, 5) cv2.line(frame, points[i - 1][:2], points[i][:2], GREEN_RGB, 2) if is_shown: cv2.putText(frame, 'You are drawing', (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, PURPLE_RGB, 5, cv2.LINE_AA) frame[5:65, 490:550] = get_overlay(frame[5:65, 490:550], class_images[predicted_class], (60, 60)) cv2.imshow("Camera", frame) out.write(frame) cap.release() out.release() cv2.destroyAllWindows() if __name__ == '__main__': opt = get_args() main(opt)
[ "cv2.GaussianBlur", "tensorflow.compat.v1.InteractiveSession", "argparse.ArgumentParser", "cv2.VideoWriter_fourcc", "cv2.medianBlur", "numpy.argmax", "cv2.imshow", "collections.deque", "cv2.line", "tensorflow.nn.softmax", "cv2.contourArea", "cv2.cvtColor", "tensorflow.compat.v1.Session", "...
[((455, 574), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Implementation of Google\'s Quick Draw Project (https://quickdraw.withgoogle.com/#)"""'], {}), '(\n "Implementation of Google\'s Quick Draw Project (https://quickdraw.withgoogle.com/#)"\n )\n', (478, 574), False, 'import argparse\n'), ((935, 948), 'tensorflow.compat.v1.ConfigProto', 'ConfigProto', ([], {}), '()\n', (946, 948), False, 'from tensorflow.compat.v1 import ConfigProto\n'), ((996, 1029), 'tensorflow.compat.v1.InteractiveSession', 'InteractiveSession', ([], {'config': 'config'}), '(config=config)\n', (1014, 1029), False, 'from tensorflow.compat.v1 import InteractiveSession\n'), ((1052, 1062), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1060, 1062), True, 'import tensorflow as tf\n'), ((2615, 2656), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['opt.load_path'], {}), '(opt.load_path)\n', (2641, 2656), True, 'import tensorflow as tf\n'), ((2667, 2686), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2683, 2686), False, 'import cv2\n'), ((2932, 2950), 'collections.deque', 'deque', ([], {'maxlen': '(1024)'}), '(maxlen=1024)\n', (2937, 2950), False, 'from collections import deque\n'), ((2964, 3003), 'numpy.zeros', 'np.zeros', (['(480, 640, 3)'], {'dtype': 'np.uint8'}), '((480, 640, 3), dtype=np.uint8)\n', (2972, 3003), True, 'import numpy as np\n'), ((6674, 6697), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6695, 6697), False, 'import cv2\n'), ((1122, 1145), 'tensorflow.compat.v1.GraphDef', 'tf.compat.v1.GraphDef', ([], {}), '()\n', (1143, 1145), True, 'import tensorflow as tf\n'), ((1314, 1357), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'graph': 'detection_graph'}), '(graph=detection_graph)\n', (1334, 1357), True, 'import tensorflow as tf\n'), ((1910, 1927), 'numpy.squeeze', 'np.squeeze', (['boxes'], {}), '(boxes)\n', (1920, 1927), True, 'import numpy as np\n'), ((1929, 1947), 'numpy.squeeze', 'np.squeeze', (['scores'], {}), '(scores)\n', (1939, 1947), True, 'import numpy as np\n'), ((1949, 1968), 'numpy.squeeze', 'np.squeeze', (['classes'], {}), '(classes)\n', (1959, 1968), True, 'import numpy as np\n'), ((2816, 2847), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (2838, 2847), False, 'import cv2\n'), ((3115, 3133), 'src.model.CLASS_IDS.values', 'CLASS_IDS.values', ([], {}), '()\n', (3131, 3133), False, 'from src.model import CLASS_IDS\n'), ((3166, 3181), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (3177, 3181), False, 'import cv2\n'), ((5223, 5241), 'cv2.flip', 'cv2.flip', (['frame', '(1)'], {}), '(frame, 1)\n', (5231, 5241), False, 'import cv2\n'), ((5258, 5296), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (5270, 5296), False, 'import cv2\n'), ((5379, 5417), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_RGB2BGR'], {}), '(frame, cv2.COLOR_RGB2BGR)\n', (5391, 5417), False, 'import cv2\n'), ((6580, 6607), 'cv2.imshow', 'cv2.imshow', (['"""Camera"""', 'frame'], {}), "('Camera', frame)\n", (6590, 6607), False, 'import cv2\n'), ((1159, 1188), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['path', '"""rb"""'], {}), "(path, 'rb')\n", (1176, 1188), True, 'import tensorflow as tf\n'), ((1259, 1298), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '""""""'}), "(graph_def, name='')\n", (1278, 1298), True, 'import tensorflow as tf\n'), ((5719, 5764), 'cv2.circle', 'cv2.circle', (['frame', '(x, y)', '(5)', '(0, 0, 255)', '(-1)'], {}), '(frame, (x, y), 5, (0, 0, 255), -1)\n', (5729, 5764), False, 'import cv2\n'), ((6329, 6441), 'cv2.putText', 'cv2.putText', (['frame', '"""You are drawing"""', '(100, 50)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1.5)', 'PURPLE_RGB', '(5)', 'cv2.LINE_AA'], {}), "(frame, 'You are drawing', (100, 50), cv2.FONT_HERSHEY_SIMPLEX, \n 1.5, PURPLE_RGB, 5, cv2.LINE_AA)\n", (6340, 6441), False, 'import cv2\n'), ((6496, 6570), 'src.utils.get_overlay', 'get_overlay', (['frame[5:65, 490:550]', 'class_images[predicted_class]', '(60, 60)'], {}), '(frame[5:65, 490:550], class_images[predicted_class], (60, 60))\n', (6507, 6570), False, 'from src.utils import get_overlay, get_images\n'), ((3604, 3644), 'cv2.cvtColor', 'cv2.cvtColor', (['canvas', 'cv2.COLOR_BGR2GRAY'], {}), '(canvas, cv2.COLOR_BGR2GRAY)\n', (3616, 3644), False, 'import cv2\n'), ((3699, 3727), 'cv2.medianBlur', 'cv2.medianBlur', (['canvas_gs', '(9)'], {}), '(canvas_gs, 9)\n', (3713, 3727), False, 'import cv2\n'), ((3755, 3790), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['median', '(5, 5)', '(0)'], {}), '(median, (5, 5), 0)\n', (3771, 3790), False, 'import cv2\n'), ((3857, 3925), 'cv2.threshold', 'cv2.threshold', (['gaussian', '(0)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(gaussian, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (3870, 3925), False, 'import cv2\n'), ((6146, 6210), 'cv2.line', 'cv2.line', (['canvas', 'points[i - 1][:2]', 'points[i][:2]', 'WHITE_RGB', '(5)'], {}), '(canvas, points[i - 1][:2], points[i][:2], WHITE_RGB, 5)\n', (6154, 6210), False, 'import cv2\n'), ((6231, 6294), 'cv2.line', 'cv2.line', (['frame', 'points[i - 1][:2]', 'points[i][:2]', 'GREEN_RGB', '(2)'], {}), '(frame, points[i - 1][:2], points[i][:2], GREEN_RGB, 2)\n', (6239, 6294), False, 'import cv2\n'), ((3383, 3401), 'collections.deque', 'deque', ([], {'maxlen': '(1024)'}), '(maxlen=1024)\n', (3388, 3401), False, 'from collections import deque\n'), ((3431, 3470), 'numpy.zeros', 'np.zeros', (['(480, 640, 3)'], {'dtype': 'np.uint8'}), '((480, 640, 3), dtype=np.uint8)\n', (3439, 3470), True, 'import numpy as np\n'), ((4263, 4287), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (4278, 4287), False, 'import cv2\n'), ((4337, 4362), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (4353, 4362), False, 'import cv2\n'), ((4455, 4482), 'cv2.resize', 'cv2.resize', (['image', '(28, 28)'], {}), '(image, (28, 28))\n', (4465, 4482), False, 'import cv2\n'), ((4605, 4632), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['image'], {}), '(image)\n', (4625, 4632), True, 'import tensorflow as tf\n'), ((4724, 4753), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['predictions[0]'], {}), '(predictions[0])\n', (4737, 4753), True, 'import tensorflow as tf\n'), ((4796, 4812), 'numpy.argmax', 'np.argmax', (['score'], {}), '(score)\n', (4805, 4812), True, 'import numpy as np\n'), ((5002, 5020), 'collections.deque', 'deque', ([], {'maxlen': '(1024)'}), '(maxlen=1024)\n', (5007, 5020), False, 'from collections import deque\n'), ((5054, 5093), 'numpy.zeros', 'np.zeros', (['(480, 640, 3)'], {'dtype': 'np.uint8'}), '((480, 640, 3), dtype=np.uint8)\n', (5062, 5093), True, 'import numpy as np\n'), ((4515, 4548), 'numpy.array', 'np.array', (['image'], {'dtype': 'np.float32'}), '(image, dtype=np.float32)\n', (4523, 4548), True, 'import numpy as np\n')]
from ifm import Enum class DfePd: """ Functions regarding Discrete Feature Elements using Pandas. """ def __init__(self, doc): self.doc = doc def dfe(self): import pandas as pd import numpy as np df_nodes = self.doc.c.mesh.df.nodes() df_dfe = pd.DataFrame( [self.doc.getNodalArrayOfFractureElement(f) for f in range(self.doc.getNumberOfTotalFractureElements())], columns=["node_1", "node_2"]) df_dfe.index.name = "dfe" df_dfe["Law"] = [self.doc.getFracLaw(f, Enum.FRAC_1D, Enum.ALL_FRAC_MODES) for f in range(self.doc.getNumberOfTotalFractureElements())] # df_dfe["Area"] = [doc.getFracArea(f, Enum.FRAC_1D, Enum.ALL_FRAC_MODES) for f in range(doc.getNumberOfTotalFractureElements())] df_dfe["x1"] = np.array(df_nodes.loc[df_dfe.node_1].X) df_dfe["x2"] = np.array(df_nodes.loc[df_dfe.node_2].X) df_dfe["y1"] = np.array(df_nodes.loc[df_dfe.node_1].Y) df_dfe["y2"] = np.array(df_nodes.loc[df_dfe.node_2].Y) df_dfe["length"] = ((df_dfe.x1 - df_dfe.x2) ** 2 + (df_dfe.y1 - df_dfe.y2) ** 2) ** 0.5 return df_dfe
[ "numpy.array" ]
[((849, 888), 'numpy.array', 'np.array', (['df_nodes.loc[df_dfe.node_1].X'], {}), '(df_nodes.loc[df_dfe.node_1].X)\n', (857, 888), True, 'import numpy as np\n'), ((912, 951), 'numpy.array', 'np.array', (['df_nodes.loc[df_dfe.node_2].X'], {}), '(df_nodes.loc[df_dfe.node_2].X)\n', (920, 951), True, 'import numpy as np\n'), ((975, 1014), 'numpy.array', 'np.array', (['df_nodes.loc[df_dfe.node_1].Y'], {}), '(df_nodes.loc[df_dfe.node_1].Y)\n', (983, 1014), True, 'import numpy as np\n'), ((1038, 1077), 'numpy.array', 'np.array', (['df_nodes.loc[df_dfe.node_2].Y'], {}), '(df_nodes.loc[df_dfe.node_2].Y)\n', (1046, 1077), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt # Prepare data_set data_a = np.random.randn(100, 2) data_a[(data_a[:, 0] >= -0.1) & (data_a[:, 1] >= -0.1)] = - \ 0.5 * abs(np.random.rand(1, 2)) data_b = np.random.randn(100, 2) data_b[(data_b[:, 0] <= 0.1) | (data_b[:, 1] <= 0.1) ] = 0.5 * abs(np.random.rand(1, 2)) label_a = np.ones((100, 1)) label_b = np.zeros((100, 1)) group_a = np.concatenate((data_a, label_a), axis=1) group_b = np.concatenate((data_b, label_b), axis=1) data_set = np.concatenate((group_a, group_b), axis=0) features = data_set[:, 0:2] labels = data_set[:, 2] # Initialization Parameter n_feature = 2 n_output = 1 iteration = 1000 learn_rate = 0.01 W = np.random.randn(n_feature, 1) b = np.zeros(n_output) # Activate function def activate_step(t): if t >= 0: y = 1 else: y = 0 return y def activate_sigmoid(t): y = 1 / (1 + np.exp(-t)) return y def activate_relu(t): if t >= 0: y = t else: y = 0 return y # ForwardPropagation def forward_prop(X, W, b, opt='sigmoid'): net_out = np.zeros(len(X[:, 0])) activate_out = np.zeros(len(X[:, 0])) for i in range(len(X[:, 0])): net_out[i] = (np.matmul(X[i, :], W) + b) if (opt == 'sigmoid'): activate_out[i] = activate_sigmoid(net_out[i]) elif (opt == 'relu'): activate_out[i] = activate_relu(net_out[i]) return activate_out # BackwardPropagation def backward_prop(X, Y, W, b, learn_rate=0.01): net_out = np.zeros(len(Y)) activate_out = np.zeros(len(Y)) for i in range(len(Y)): net_out[i] = (np.matmul(X[i, :], W) + b) activate_out[i] = activate_sigmoid(net_out[i]) W[0] = W[0] + learn_rate*(Y[i]-activate_out[i]) * \ (1-activate_out[i])*activate_out[i]*X[i, 0] W[1] = W[1] + learn_rate*(Y[i]-activate_out[i]) * \ (1-activate_out[i])*activate_out[i]*X[i, 1] b = b + learn_rate * (Y[i] - activate_out[i]) * \ (1 - activate_out[i]) * activate_out[i] * 1 return W, b line_x = np.linspace(-3, 3, 100) line_y = -W[0] / W[1] * line_x - b / W[1] plt.plot(line_x, line_y, '--k', label='initial line') # Run the whole batch (one shot) for i in range(iteration): activate_out = forward_prop(features, W, b, opt='sigmoid') W, b = backward_prop(features, labels, W, b, 0.01) # Visualization line_x = np.linspace(-3, 3, 100) line_y = -W[0] / W[1] * line_x - b / W[1] accuracy = 0 for i in range(len(labels)): if i < 100: if activate_out[i] > 0.7: plt.plot(features[i, 0], features[i, 1], '.r') accuracy += 1 else: if activate_out[i] < 0.3: plt.plot(features[i, 0], features[i, 1], '.b') accuracy += 1 plt.scatter(group_a[:, 0], group_a[:, 1], color='red', facecolors='none', label='group_a') plt.scatter(group_b[:, 0], group_b[:, 1], color='blue', facecolors='none', label='group_b') plt.plot(line_x, line_y, 'b', label='final line') plt.tight_layout() plt.xlim((-3, 3)) plt.ylim((-3, 3)) plt.legend() plt.title('1 layer: sigmoid') plt.text(-2, -2, 'accuracy:' + str(accuracy/200*100) + ' %') print('Accuracy: ', accuracy/200 * 100, '%') plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "numpy.random.randn", "matplotlib.pyplot.ylim", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "numpy.zeros", "numpy.ones", "numpy.exp", "numpy.linspace", "numpy.matmul", "num...
[((80, 103), 'numpy.random.randn', 'np.random.randn', (['(100)', '(2)'], {}), '(100, 2)\n', (95, 103), True, 'import numpy as np\n'), ((212, 235), 'numpy.random.randn', 'np.random.randn', (['(100)', '(2)'], {}), '(100, 2)\n', (227, 235), True, 'import numpy as np\n'), ((343, 360), 'numpy.ones', 'np.ones', (['(100, 1)'], {}), '((100, 1))\n', (350, 360), True, 'import numpy as np\n'), ((371, 389), 'numpy.zeros', 'np.zeros', (['(100, 1)'], {}), '((100, 1))\n', (379, 389), True, 'import numpy as np\n'), ((401, 442), 'numpy.concatenate', 'np.concatenate', (['(data_a, label_a)'], {'axis': '(1)'}), '((data_a, label_a), axis=1)\n', (415, 442), True, 'import numpy as np\n'), ((453, 494), 'numpy.concatenate', 'np.concatenate', (['(data_b, label_b)'], {'axis': '(1)'}), '((data_b, label_b), axis=1)\n', (467, 494), True, 'import numpy as np\n'), ((507, 549), 'numpy.concatenate', 'np.concatenate', (['(group_a, group_b)'], {'axis': '(0)'}), '((group_a, group_b), axis=0)\n', (521, 549), True, 'import numpy as np\n'), ((696, 725), 'numpy.random.randn', 'np.random.randn', (['n_feature', '(1)'], {}), '(n_feature, 1)\n', (711, 725), True, 'import numpy as np\n'), ((730, 748), 'numpy.zeros', 'np.zeros', (['n_output'], {}), '(n_output)\n', (738, 748), True, 'import numpy as np\n'), ((2100, 2123), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (2111, 2123), True, 'import numpy as np\n'), ((2166, 2219), 'matplotlib.pyplot.plot', 'plt.plot', (['line_x', 'line_y', '"""--k"""'], {'label': '"""initial line"""'}), "(line_x, line_y, '--k', label='initial line')\n", (2174, 2219), True, 'import matplotlib.pyplot as plt\n'), ((2426, 2449), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (2437, 2449), True, 'import numpy as np\n'), ((2799, 2893), 'matplotlib.pyplot.scatter', 'plt.scatter', (['group_a[:, 0]', 'group_a[:, 1]'], {'color': '"""red"""', 'facecolors': '"""none"""', 'label': '"""group_a"""'}), "(group_a[:, 0], group_a[:, 1], color='red', facecolors='none',\n label='group_a')\n", (2810, 2893), True, 'import matplotlib.pyplot as plt\n'), ((2902, 2997), 'matplotlib.pyplot.scatter', 'plt.scatter', (['group_b[:, 0]', 'group_b[:, 1]'], {'color': '"""blue"""', 'facecolors': '"""none"""', 'label': '"""group_b"""'}), "(group_b[:, 0], group_b[:, 1], color='blue', facecolors='none',\n label='group_b')\n", (2913, 2997), True, 'import matplotlib.pyplot as plt\n'), ((3007, 3056), 'matplotlib.pyplot.plot', 'plt.plot', (['line_x', 'line_y', '"""b"""'], {'label': '"""final line"""'}), "(line_x, line_y, 'b', label='final line')\n", (3015, 3056), True, 'import matplotlib.pyplot as plt\n'), ((3057, 3075), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3073, 3075), True, 'import matplotlib.pyplot as plt\n'), ((3076, 3093), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-3, 3)'], {}), '((-3, 3))\n', (3084, 3093), True, 'import matplotlib.pyplot as plt\n'), ((3094, 3111), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-3, 3)'], {}), '((-3, 3))\n', (3102, 3111), True, 'import matplotlib.pyplot as plt\n'), ((3112, 3124), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3122, 3124), True, 'import matplotlib.pyplot as plt\n'), ((3125, 3154), 'matplotlib.pyplot.title', 'plt.title', (['"""1 layer: sigmoid"""'], {}), "('1 layer: sigmoid')\n", (3134, 3154), True, 'import matplotlib.pyplot as plt\n'), ((3262, 3272), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3270, 3272), True, 'import matplotlib.pyplot as plt\n'), ((180, 200), 'numpy.random.rand', 'np.random.rand', (['(1)', '(2)'], {}), '(1, 2)\n', (194, 200), True, 'import numpy as np\n'), ((310, 330), 'numpy.random.rand', 'np.random.rand', (['(1)', '(2)'], {}), '(1, 2)\n', (324, 330), True, 'import numpy as np\n'), ((905, 915), 'numpy.exp', 'np.exp', (['(-t)'], {}), '(-t)\n', (911, 915), True, 'import numpy as np\n'), ((1223, 1244), 'numpy.matmul', 'np.matmul', (['X[i, :]', 'W'], {}), '(X[i, :], W)\n', (1232, 1244), True, 'import numpy as np\n'), ((1643, 1664), 'numpy.matmul', 'np.matmul', (['X[i, :]', 'W'], {}), '(X[i, :], W)\n', (1652, 1664), True, 'import numpy as np\n'), ((2596, 2642), 'matplotlib.pyplot.plot', 'plt.plot', (['features[i, 0]', 'features[i, 1]', '""".r"""'], {}), "(features[i, 0], features[i, 1], '.r')\n", (2604, 2642), True, 'import matplotlib.pyplot as plt\n'), ((2725, 2771), 'matplotlib.pyplot.plot', 'plt.plot', (['features[i, 0]', 'features[i, 1]', '""".b"""'], {}), "(features[i, 0], features[i, 1], '.b')\n", (2733, 2771), True, 'import matplotlib.pyplot as plt\n')]
import sys from time import time from datetime import datetime import argparse import numpy as np from helicalc import helicalc_dir, helicalc_data from helicalc.solcalc import * from helicalc.geometry import read_solenoid_geom_combined from helicalc.tools import generate_cartesian_grid_df from helicalc.constants import ( PS_grid, TSu_grid, TSd_grid, DS_grid, PStoDumpArea_grid, ProtonDumpArea_grid, DS_cyl2d_grid_5mm ) # paramdir = '/home/ckampa/coding/helicalc/dev/params/' paramdir = helicalc_dir + 'dev/params/' paramname = 'Mu2e_V13' datadir = helicalc_data+'Bmaps/SolCalc_partial/' regions = {'PS': PS_grid, 'TSu': TSu_grid, 'TSd': TSd_grid, 'DS': DS_grid, 'PStoDumpArea': PStoDumpArea_grid, 'ProtonDumpArea': ProtonDumpArea_grid, 'DSCyl2D': DS_cyl2d_grid_5mm} if __name__=='__main__': # parse command line arguments parser = argparse.ArgumentParser() parser.add_argument('-r', '--Region', help='Which region of Mu2e to calculate? '+ '["PS"(default), "TSu", "TSd", "DS", "PStoDumpArea"'+ ', "ProtonDumpArea", "DSCyl2D"]') parser.add_argument('-t', '--Testing', help='Calculate using small subset of coils?'+ '"y"(default)/"n"') parser.add_argument('-u', '--Unused', help='Unused argument.') args = parser.parse_args() # fill defaults where needed if args.Region is None: args.Region = 'PS' else: args.Region = args.Region.strip() if args.Testing is None: args.Testing = 'n' else: args.Testing = args.Testing.strip() reg = args.Region # print configs print(f'Region: {reg}') print(f'Testing on subset of coils? {args.Testing}\n') # redirect stdout to log file dt = datetime.strftime(datetime.now(), '%Y-%m-%d_%H%M%S') log_file = open(datadir+f"logs/{dt}_calculate_{reg}_region.log", "w") old_stdout = sys.stdout sys.stdout = log_file # print configs in file print(f'Region: {reg}') print(f'Testing on subset of coils? {args.Testing}\n') # step size for integrator drz = np.array([5e-3, 1e-2]) # create grid df = generate_cartesian_grid_df(regions[reg]) # define base save name base_name = f'Mau13.SolCalc.{reg}_region.standard' # load geometry geom_df_mu2e = read_solenoid_geom_combined(paramdir,paramname) # TESTING (only a few coils) if args.Testing == 'y': geom_df_mu2e = geom_df_mu2e.iloc[5:8] # loop through all coils N_coils = len(geom_df_mu2e) for i in range(N_coils): # for geom in geom_df_mu2e.itertuples(): j = int(round(geom_df_mu2e.iloc[i].Coil_Num)) # print coil number to screen for reference print(f'Calculating coil {i+1}/'+f'{N_coils}', file=old_stdout) # instantiate integrator mySolCalc = SolCalcIntegrator(geom_df_mu2e.iloc[i], drz=drz) # integrate on grid (and update the grid df) df = mySolCalc.integrate_grid(df) # save single coil results mySolCalc.save_grid_calc(savetype='pkl', savename=datadir+base_name+f'.coil_{j}', all_solcalc_cols=False) # save df with all coils i0 = int(round(geom_df_mu2e.iloc[0].Coil_Num)) i1 = int(round(geom_df_mu2e.iloc[-1].Coil_Num)) mySolCalc.save_grid_calc(savetype='pkl', savename=datadir+base_name+f'.coils_{i0}-{i1}', all_solcalc_cols=True) # close log file log_file.close()
[ "helicalc.geometry.read_solenoid_geom_combined", "argparse.ArgumentParser", "helicalc.tools.generate_cartesian_grid_df", "numpy.array", "datetime.datetime.now" ]
[((905, 930), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (928, 930), False, 'import argparse\n'), ((2216, 2239), 'numpy.array', 'np.array', (['[0.005, 0.01]'], {}), '([0.005, 0.01])\n', (2224, 2239), True, 'import numpy as np\n'), ((2266, 2306), 'helicalc.tools.generate_cartesian_grid_df', 'generate_cartesian_grid_df', (['regions[reg]'], {}), '(regions[reg])\n', (2292, 2306), False, 'from helicalc.tools import generate_cartesian_grid_df\n'), ((2429, 2477), 'helicalc.geometry.read_solenoid_geom_combined', 'read_solenoid_geom_combined', (['paramdir', 'paramname'], {}), '(paramdir, paramname)\n', (2456, 2477), False, 'from helicalc.geometry import read_solenoid_geom_combined\n'), ((1897, 1911), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1909, 1911), False, 'from datetime import datetime\n')]
''' Набор общих юнитов @author: Kosh ''' import numpy as np from streampy.units.base.pooled import Pool, Worker as Base class Worker(Base): ''' Преобразуем ббоксы в заполненные ячейки для yolo-подобного детектирования пока в примитивном варианте с одним классом todo: добить до множества анкоров, возможно в нескольких разрешениях ''' def process(self, inData, inMeta): config = self.config cellsConfig = config.get('cells', [7, 7]) cellsSizeConfig = config.get('cellsSize', [32, 32]) cells = np.zeros((cellsConfig[0], cellsConfig[1], 5)) # print(cellsConfig) for bbox in inData['bboxes']: cx = bbox[2]/2 + bbox[0] cy = bbox[3]/2 + bbox[1] xCell = int(cx // cellsSizeConfig[0]) yCell = int(cy // cellsSizeConfig[1]) dx = (cx % cellsSizeConfig[0]) / cellsSizeConfig[0] dy = (cy % cellsSizeConfig[1]) / cellsSizeConfig[1] dw = bbox[2] / cellsSizeConfig[0] dh = bbox[3] / cellsSizeConfig[1] cells[yCell][xCell] = [1, dx, dy, dw, dh] # print(bbox) # print(xCell, yCell) # print(cells[yCell][xCell]) # print(cells) return [{'cells':cells}]
[ "numpy.zeros" ]
[((581, 626), 'numpy.zeros', 'np.zeros', (['(cellsConfig[0], cellsConfig[1], 5)'], {}), '((cellsConfig[0], cellsConfig[1], 5))\n', (589, 626), True, 'import numpy as np\n')]
# import sys # from scipy.signal import spectrogram, detrend # from scipy.linalg import norm # import matplotlib.pyplot as plt import numpy as np import pickle from obspy.core import Trace # , Stream, read from obstools.atacr import utils # , plotting from pkg_resources import resource_filename from pathlib import Path np.seterr(all='ignore') # np.set_printoptions(threshold=sys.maxsize) class EventStream(object): """ An EventStream object contains attributes that store station-event metadata and methods for applying the transfer functions to the various components and produce corrected/cleaned vertical components. Note ---- An ``EventStream`` object is defined as the data (:class:`~obspy.core.Stream` object) are read from file or downloaded from an ``obspy`` Client. Based on the available components, a list of possible corrections is determined automatically. Attributes ---------- sta : :class:`~stdb.StdbElement` An instance of an stdb object key : str Station key for current object sth : :class:`~obspy.core.Stream` Stream containing three-component seismic data (traces are empty if data are not available) stp : :class:`~obspy.core.Stream` Stream containing pressure data (trace is empty if data are not available) tstamp : str Time stamp for event evlat : float Latitude of seismic event evlon : float Longitude of seismic event evtime : :class:`~obspy.core.UTCDateTime` Origin time of seismic event window : float Length of time window in seconds fs : float Sampling frequency (in Hz) dt : float Sampling distance in seconds npts : int Number of points in time series ncomp : int Number of available components (either 2, 3 or 4) ev_list : Dict Dictionary of possible transfer functions given the available components. This is determined during initialization. correct : :class:`~obstools.atacr.classes.EventStream.CorrectDict` Container Dictionary for all possible corrections from the transfer functions. This is calculated from the method :func:`~obstools.atacr.classes.EventStream.correct_data` Examples -------- Get demo earthquake data as EventStream object >>> from obstools.atacr import EventStream >>> evstream = EventStream('demo') Uploading demo earthquake data - March 09, 2012, station 7D.M08A >>> evstream.__dict__.keys() dict_keys(['sta', 'key', 'sth', 'stp', 'tstamp', 'evlat', 'evlon', 'evtime', 'window', 'fs', 'dt', 'ncomp', 'ev_list']) Plot the raw traces >>> import obstools.atacr.plot as plot >>> plot.fig_event_raw(evstream, fmin=1./150., fmax=2.) .. figure:: ../obstools/examples/figures/Figure_11.png :align: center """ def __init__(self, sta=None, sth=None, stp=None, tstamp=None, lat=None, lon=None, time=None, window=None, sampling_rate=None, ncomp=None, correct=False): if sta == 'demo' or sta == 'Demo': print("Uploading demo earthquake data - March 09, 2012, " + "station 7D.M08A") exmpl_path = Path(resource_filename('obstools', 'examples')) fn = '2012.069.07.09.event.pkl' fn = exmpl_path / 'event' / fn evstream = pickle.load(open(fn, 'rb')) sta = evstream.sta key = evstream.key sth = evstream.sth stp = evstream.stp tstamp = evstream.tstamp lat = evstream.evlat lon = evstream.evlon time = evstream.evtime window = evstream.window sampling_rate = evstream.fs ncomp = evstream.ncomp correct = evstream.correct if any(value == None for value in [sta, sth, stp, tstamp, lat, lon, time, window, sampling_rate, ncomp]): raise(Exception( "Error: Initializing EventStream object with None values - " + "aborting")) self.sta = sta self.key = sta.network+'.'+sta.station self.sth = sth self.stp = stp self.tstamp = tstamp self.evlat = lat self.evlon = lon self.evtime = time self.window = window self.fs = sampling_rate self.dt = 1./sampling_rate self.ncomp = ncomp self.correct = False # Build list of available transfer functions for future use if self.ncomp == 2: self.ev_list = {'ZP': True, 'Z1': False, 'Z2-1': False, 'ZP-21': False, 'ZH': False, 'ZP-H': False, 'ZH-P': False} elif self.ncomp == 3: self.ev_list = {'ZP': False, 'Z1': True, 'Z2-1': True, 'ZP-21': False, 'ZH': True, 'ZP-H': False, 'ZH-P': False} else: self.ev_list = {'ZP': True, 'Z1': True, 'Z2-1': True, 'ZP-21': True, 'ZH': True, 'ZP-H': True, 'ZH-P': True} class CorrectDict(dict): def __init__(self): self = dict() def add(self, key, value): self[key] = value def correct_data(self, tfnoise, n_signif=0): """ Method to apply transfer functions between multiple components (and component combinations) to produce corrected/cleaned vertical components. Parameters ---------- tfnoise : :class:`~obstools.atacr.classes.TFNoise` Object that contains the noise transfer functions used in the correction n_signif (int): only apply transfer function correction if this number of neighboring coherencies are above the 95% significance level Attributes ---------- correct : :class:`~obstools.atacr.classes.EventStream.CorrectDict` Container Dictionary for all possible corrections from the transfer functions Examples -------- Let's carry through the correction of the vertical component for a single day of noise, say corresponding to the noise recorded on March 04, 2012. In practice, the DayNoise object should correspond to the same day at that of the recorded earthquake to avoid bias in the correction. >>> from obstools.atacr import DayNoise, TFNoise, EventStream >>> daynoise = DayNoise('demo') Uploading demo data - March 04, 2012, station 7D.M08A >>> daynoise.QC_daily_spectra() >>> daynoise.average_daily_spectra() >>> tfnoise_day = TFNoise(daynoise) >>> tfnoise_day.transfer_func() >>> evstream = EventStream('demo') Uploading demo earthquake data - March 09, 2012, station 7D.M08A >>> evstream.correct_data(tfnoise_day) Plot the corrected traces >>> import obstools.atacr.plot as plot >>> plot.fig_event_corrected(evstream, tfnoise_day.tf_list) .. figure:: ../obstools/examples/figures/Figure_corrected_march04.png :align: center Carry out the same exercise but this time using a StaNoise object >>> from obstools.atacr import StaNoise, TFNoise, EventStream >>> stanoise = StaNoise('demo') Uploading demo data - March 01 to 04, 2012, station 7D.M08A >>> stanoise.QC_sta_spectra() >>> stanoise.average_sta_spectra() >>> tfnoise_sta = TFNoise(stanoise) >>> tfnoise_sta.transfer_func() >>> evstream = EventStream('demo') Uploading demo earthquake data - March 09, 2012, station 7D.M08A >>> evstream.correct_data(tfnoise_sta) Plot the corrected traces >>> import obstools.atacr.plot as plot >>> plot.fig_event_corrected(evstream, tfnoise_sta.tf_list) .. figure:: ../obstools/examples/figures/Figure_corrected_sta.png :align: center """ if not tfnoise.transfunc: raise( Exception("Error: Object TFNoise has no transfunc " + "attribute - aborting")) if n_signif: if not tfnoise.coher: raise( Exception("Error: Object TFNoise has no coher " + "attribute - aborting")) coher = tfnoise.coher n_wins = tfnoise.n_wins correct = self.CorrectDict() # Extract list and transfer functions available tf_list = tfnoise.tf_list transfunc = tfnoise.transfunc # Points in window ws = int(self.window/self.dt) # Extract traces trZ, tr1, tr2, trP = Trace(), Trace(), Trace(), Trace() trZ = self.sth.select(component='Z')[0] if self.ncomp == 2 or self.ncomp == 4: trP = self.stp[0] if self.ncomp == 3 or self.ncomp == 4: tr1 = self.sth.select(component='1')[0] tr2 = self.sth.select(component='2')[0] # Get Fourier spectra ft1, ft2, ftZ, ftP = None, None, None, None ftZ, f = utils.calculate_windowed_fft(trZ, ws, hann=False) if self.ncomp == 2 or self.ncomp == 4: ftP, f = utils.calculate_windowed_fft(trP, ws, hann=False) if self.ncomp == 3 or self.ncomp == 4: ft1, f = utils.calculate_windowed_fft(tr1, ws, hann=False) ft2, f = utils.calculate_windowed_fft(tr2, ws, hann=False) if not np.allclose(f, tfnoise.f): raise(Exception('Frequency axes are different: ', f, tfnoise.f)) # set up self._fTF() calls self._tfnoise = tfnoise self._nF = len(f) self._n_signif = n_signif for key, value in tf_list.items(): if not value: continue if key == 'ZP' and self.ev_list[key] and tf_list[key]: fTF_ZP = self._fTF(key, 'TF_ZP') corrspec = ftZ - fTF_ZP*ftP elif key == 'Z1' and self.ev_list[key] and tf_list[key]: fTF_Z1 = self._fTF(key, 'TF_Z1') corrspec = ftZ - fTF_Z1*ft1 elif key == 'Z2-1' and self.ev_list[key] and tf_list[key]: fTF_Z1 = self._fTF('Z1', 'TF_Z1') fTF_21 = self._fTF(key, 'TF_21') fTF_Z2_1 = self._fTF(key, 'TF_Z2-1') corrspec = ftZ - fTF_Z1*ft1 - (ft2 - ft1*fTF_21)*fTF_Z2_1 elif key == 'ZP-21' and self.ev_list[key] and tf_list[key]: fTF_Z1 = self._fTF(key, 'TF_Z1') fTF_21 = self._fTF(key, 'TF_21') fTF_Z2_1 = self._fTF(key, 'TF_Z2-1') fTF_P1 = self._fTF(key, 'TF_P1') fTF_P2_1 = self._fTF(key, 'TF_P2-1') fTF_ZP_21 = self._fTF(key, 'TF_ZP-21') corrspec = (ftZ - fTF_Z1*ft1 - (ft2 - ft1*fTF_21)*fTF_Z2_1 - (ftP - ft1*fTF_P1 - (ft2 - ft1*fTF_21)*fTF_P2_1)*fTF_ZP_21) elif key == 'ZH' and self.ev_list[key] and tf_list[key]: ftH = utils.rotate_dir(ft1, ft2, tfnoise.tilt) fTF_ZH = self._fTF(key, 'TF_ZH') corrspec = ftZ - fTF_ZH*ftH elif key == 'ZP-H' and self.ev_list[key] and tf_list[key]: ftH = utils.rotate_dir(ft1, ft2, tfnoise.tilt) fTF_ZH = self._fTF('ZH', 'TF_ZH') fTF_PH = self._fTF('ZP-H', 'TF_PH') fTF_ZP_H = self._fTF('ZP-H', 'TF_ZP-H') corrspec = ftZ - fTF_ZH*ftH - (ftP - ftH*fTF_PH)*fTF_ZP_H elif key == 'ZH-P' and self.ev_list[key] and tf_list[key]: ftH = utils.rotate_dir(ft1, ft2, tfnoise.tilt) fTF_ZP = self._fTF('ZP', 'TF_ZP') fTF_HP = self._fTF('ZH-P', 'TF_HP') fTF_ZH_P = self._fTF('ZH-P', 'TF_ZH-P') corrspec = ftZ - ftP*fTF_ZP - (ftH - ftP*fTF_HP)*fTF_ZH_P else: continue corrtime = np.real(np.fft.ifft(corrspec))[0:ws] correct.add(key, corrtime) # correct.add(key+'_spec', corrspec) # WCC added to get spectra as well self.correct = correct def _fTF(self, key1, key2): """ Calculate Fourier Transfer Function (WCC) Args: key1 (str): first key of transfer function / coherency key2 (str): second key of transfer function / coherency """ TF = self._tfnoise.transfunc[key1][key2] if self._n_signif: coh = self._tfnoise.coher[key1][key2] TF[~self._good_cohers(coh, self._tfnoise.n_wins, self._n_signif)] = 0 return np.hstack((TF, np.conj(TF[::-1][1:self._nF-1]))) def _good_cohers(self, coher, n_wins, n_signif=3): """ Return boolean array indicating where coherency is significant (WCC) Args: coher (:class:`~numpy.ndarray`): coherency n_signif: number of neighboring coherencies that need to be above the 95% significance level n_wins (int): number of windows used to calcualate tf and coher Returns: (:class:`~numpy.ndarray`): boolean array of significant coherences >>> from obstools.atacr import EventStream >>> from numpy import arange >>> cohers = arange(0, 1, 0.05) >>> cohers[13] = 0 >>> EventStream._good_cohers(cohers, 40, 1) array([False, False, False, False, False, True, True, True, True, True, True, True, True, False, True, True, True, True, True, True], dtype=bool) >>> EventStream._good_cohers(cohers, 40, 3) array([False, False, False, False, False, False, False, True, True, True, True, True, True, False, False, False, True, True, True, True], dtype=bool) >>> EventStream._good_cohers(cohers, 40, 5) array([False, False, False, False, False, False, False, True, True, True, True, False, False, False, False, False, True, True, True, True], dtype=bool) >>> cohers[~EventStream._good_cohers(cohers, 40, 5)] = 0 >>> cohers array([ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0.35, 0.4 , 0.45, 0.5 , 0. , 0. , 0. , 0. , 0. , 0.8 , 0.85, 0.9 , 0.95]) """ if n_signif == 0: return np.ones(size(coher)) signif_level = np.sqrt(2/n_wins) # 95% significancy level good_coher = np.abs(coher) > signif_level if n_signif > 1: # Propagate bad coherences n_signif-1 to the right good_coher_orig = good_coher.copy() for i in np.arange(1, n_signif): good_coher &= np.concatenate((good_coher_orig[:i], np.roll(good_coher_orig, i)[i:])) # Shift good_coher back to the original indices if n_signif >= 3: left_shift = int(n_signif/2) good_coher = np.concatenate((np.roll(good_coher, -left_shift)[:-left_shift], good_coher[-left_shift:])) return good_coher def save(self, filename): """ Method to save the object to file using `~Pickle`. Parameters ---------- filename : str File name Examples -------- Following from the example outlined in method :func:`~obstools.atacr.classes.EventStream.correct_data`, we simply save the final object >>> evstream.save('evstream_demo.pkl') Check that object has been saved >>> import glob >>> glob.glob("./evstream_demo.pkl") ['./evstream_demo.pkl'] """ if not self.correct: print("Warning: saving EventStream object before having done " + "the corrections") file = open(filename, 'wb') pickle.dump(self, file) file.close()
[ "obstools.atacr.utils.rotate_dir", "numpy.conj", "pickle.dump", "obspy.core.Trace", "numpy.abs", "numpy.fft.ifft", "numpy.roll", "numpy.seterr", "numpy.allclose", "obstools.atacr.utils.calculate_windowed_fft", "pkg_resources.resource_filename", "numpy.arange", "numpy.sqrt" ]
[((323, 346), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (332, 346), True, 'import numpy as np\n'), ((9271, 9320), 'obstools.atacr.utils.calculate_windowed_fft', 'utils.calculate_windowed_fft', (['trZ', 'ws'], {'hann': '(False)'}), '(trZ, ws, hann=False)\n', (9299, 9320), False, 'from obstools.atacr import utils\n'), ((14678, 14697), 'numpy.sqrt', 'np.sqrt', (['(2 / n_wins)'], {}), '(2 / n_wins)\n', (14685, 14697), True, 'import numpy as np\n'), ((16202, 16225), 'pickle.dump', 'pickle.dump', (['self', 'file'], {}), '(self, file)\n', (16213, 16225), False, 'import pickle\n'), ((8860, 8867), 'obspy.core.Trace', 'Trace', ([], {}), '()\n', (8865, 8867), False, 'from obspy.core import Trace\n'), ((8869, 8876), 'obspy.core.Trace', 'Trace', ([], {}), '()\n', (8874, 8876), False, 'from obspy.core import Trace\n'), ((8878, 8885), 'obspy.core.Trace', 'Trace', ([], {}), '()\n', (8883, 8885), False, 'from obspy.core import Trace\n'), ((8887, 8894), 'obspy.core.Trace', 'Trace', ([], {}), '()\n', (8892, 8894), False, 'from obspy.core import Trace\n'), ((9389, 9438), 'obstools.atacr.utils.calculate_windowed_fft', 'utils.calculate_windowed_fft', (['trP', 'ws'], {'hann': '(False)'}), '(trP, ws, hann=False)\n', (9417, 9438), False, 'from obstools.atacr import utils\n'), ((9507, 9556), 'obstools.atacr.utils.calculate_windowed_fft', 'utils.calculate_windowed_fft', (['tr1', 'ws'], {'hann': '(False)'}), '(tr1, ws, hann=False)\n', (9535, 9556), False, 'from obstools.atacr import utils\n'), ((9578, 9627), 'obstools.atacr.utils.calculate_windowed_fft', 'utils.calculate_windowed_fft', (['tr2', 'ws'], {'hann': '(False)'}), '(tr2, ws, hann=False)\n', (9606, 9627), False, 'from obstools.atacr import utils\n'), ((9644, 9669), 'numpy.allclose', 'np.allclose', (['f', 'tfnoise.f'], {}), '(f, tfnoise.f)\n', (9655, 9669), True, 'import numpy as np\n'), ((14743, 14756), 'numpy.abs', 'np.abs', (['coher'], {}), '(coher)\n', (14749, 14756), True, 'import numpy as np\n'), ((14929, 14951), 'numpy.arange', 'np.arange', (['(1)', 'n_signif'], {}), '(1, n_signif)\n', (14938, 14951), True, 'import numpy as np\n'), ((3285, 3326), 'pkg_resources.resource_filename', 'resource_filename', (['"""obstools"""', '"""examples"""'], {}), "('obstools', 'examples')\n", (3302, 3326), False, 'from pkg_resources import resource_filename\n'), ((12910, 12943), 'numpy.conj', 'np.conj', (['TF[::-1][1:self._nF - 1]'], {}), '(TF[::-1][1:self._nF - 1])\n', (12917, 12943), True, 'import numpy as np\n'), ((12223, 12244), 'numpy.fft.ifft', 'np.fft.ifft', (['corrspec'], {}), '(corrspec)\n', (12234, 12244), True, 'import numpy as np\n'), ((15066, 15093), 'numpy.roll', 'np.roll', (['good_coher_orig', 'i'], {}), '(good_coher_orig, i)\n', (15073, 15093), True, 'import numpy as np\n'), ((15280, 15312), 'numpy.roll', 'np.roll', (['good_coher', '(-left_shift)'], {}), '(good_coher, -left_shift)\n', (15287, 15312), True, 'import numpy as np\n'), ((11282, 11322), 'obstools.atacr.utils.rotate_dir', 'utils.rotate_dir', (['ft1', 'ft2', 'tfnoise.tilt'], {}), '(ft1, ft2, tfnoise.tilt)\n', (11298, 11322), False, 'from obstools.atacr import utils\n'), ((11509, 11549), 'obstools.atacr.utils.rotate_dir', 'utils.rotate_dir', (['ft1', 'ft2', 'tfnoise.tilt'], {}), '(ft1, ft2, tfnoise.tilt)\n', (11525, 11549), False, 'from obstools.atacr import utils\n'), ((11875, 11915), 'obstools.atacr.utils.rotate_dir', 'utils.rotate_dir', (['ft1', 'ft2', 'tfnoise.tilt'], {}), '(ft1, ft2, tfnoise.tilt)\n', (11891, 11915), False, 'from obstools.atacr import utils\n')]
import numpy as np from scipy import ndimage from scipy import special import lmfit from .. import geometry def get_thick_line(point1, point2, length_spacing=1, line_thickness=0, width_spacing=1): """Construct a list of points representing a discrete line. If `line_thickness` > 0 then the line is composed of multiple parallel line to each other with a width equal to `line_thickness`. Args: point1: 1D array or float. point2: 1D array or float. length_spacing: float, when computing the points inside a line what distance should separate the points (pixel). line_thickness: float, the thickness of the line used centered on the input line (pixel). width_spacing: float, same as `length_spacing` but in the perpendicular direction when `line_thickness` is not 0. Returns: points: 3D array of shape [2xWxL] where W are points along the thickness of the line and L along its length. """ line_tips = np.array([point1, point2]) # Get points along the initial line. points = geometry.discretize_line(line_tips, length_spacing) if line_thickness > 0: # Get the two lines parallel to the initial line # at the distance defined by `line_thickness`. normal_distance = line_thickness / 2 vec = points[-1] - points[0] normal_points = geometry.get_normal_points(vec, points, normal_distance) lines = [] # Iterate over the length of the initial line. for p1, p2 in np.rollaxis(normal_points, -1): line = np.array([p1, p2]) thickness_points = geometry.discretize_line(line, width_spacing) lines.append(thickness_points) lines = np.array(lines).T else: lines = np.array([points]).T.swapaxes(1, 2) return lines def line_profile( image, point1, point2, length_spacing=0.1, line_thickness=0, width_spacing=0.1, normalized_intensities=True, threshold=None, ): """Get a line profile defined by an image and two points. Args: image: 2D array. point1: 1D array or float. point2: 1D array or float. length_spacing: float, when computing the points inside a line what distance should separate the points (pixel). line_thickness: float, the thickness of the line used centered on the input line (pixel). width_spacing: float, same as `length_spacing` but in the perpendicular direction when `line_thickness` is not 0. normalized_intensities: bool, normalize from 0 to 1 if True. Returns: x_profile: array, the x coordinates of the profile where unit is pixel. y_profile: array, the intensities values of the profile. """ lines = get_thick_line( point1, point2, length_spacing=length_spacing, line_thickness=line_thickness, width_spacing=width_spacing, ) # Get the intensity profile of the lines. y_profiles = ndimage.map_coordinates(image, lines.reshape(2, -1), order=1, mode="constant") y_profiles = y_profiles.reshape(lines.shape[1:]) # Get the mean profile y_profile = y_profiles.mean(axis=0) if normalized_intensities: # Normalize the profile between 0 and 1. # FUTURE: could be modified. y_profile = y_profile / y_profile.max() # Define the x values of the profile so the unit is a pixel. x_profile = np.arange(0, y_profile.shape[0]) * length_spacing if threshold: to_keep = y_profile > threshold y_profile = y_profile[to_keep] x_profile = x_profile[to_keep] return x_profile, y_profile # pylint: disable=too-many-locals def perpendicular_line_fit(lines, image, length_spacing, fit_threshold, continuous_discard=False): """From a list of lines, fit each line to a Gaussian and record the `mu` value for each fit and compute the position in the image of this value. Args: lines: see what returns `get_thick_line()`. image: 2D array. length_spacing: float, `get_thick_line()`. fit_threshold: float, fit with a `mu` stderr above this value will be discarded. continuous_discard: bool, Discard all fit after the first one above `fit_threshold`. """ def gaussian_wall(x, mu, sigma, mt, bg): return mt * np.exp(-0.5 * ((x - mu) / sigma) ** 2) + bg model = lmfit.Model(gaussian_wall) # This threshold is sensitive to `length_spacing` # TODO: I am not sure this is the best condition # to filter out bad fits. mu_stderr_threshold = fit_threshold args = {} args["length_spacing"] = length_spacing # pixel args["line_thickness"] = 0 args["normalized_intensities"] = True fitted_line = [] errors = [] for line in np.rollaxis(lines, -1): point1, point2 = line[:, 0], line[:, -1] x_profile, y_profile = line_profile(image, point1, point2, **args) fit_params = {} fit_params["mu"] = lmfit.Parameter("mu", value=x_profile[-1] / 2, min=0, max=x_profile[-1]) fit_params["sigma"] = lmfit.Parameter( "sigma", value=100, vary=True, min=0, max=x_profile[-1] ) fit_params["mt"] = lmfit.Parameter("mt", value=50, vary=True, min=0) fit_params["bg"] = lmfit.Parameter("bg", value=50, vary=True, min=0) fit_result = model.fit(y_profile, x=x_profile, **fit_params) # Distance between point 1 and the fitted center d = fit_result.best_values["mu"] vec = point2 - point1 # Get the point at a certain distance d from point1 line_center = geometry.get_point_from_vector(vec, point1, d) fitted_line.append(line_center) # When error is None then we set its value to infinity. if not fit_result.params["mu"].stderr: errors.append(np.inf) else: errors.append(fit_result.params["mu"].stderr) fitted_line = np.array(fitted_line) errors = np.array(errors) if continuous_discard: # Discard fitted lines after a fit above `mu_stderr_threshold` discard_index = np.where(errors > mu_stderr_threshold)[0][0] fitted_line = fitted_line[:discard_index] else: fitted_line = fitted_line[errors < mu_stderr_threshold] return fitted_line def tip_line_fit(point1, point2, image, length_spacing, line_thickness, width_spacing): """Fit the tip of a line to a complementary error function, 1 - erf(x). Args: point1: 1D array or float. point2: 1D array or float. image: 2D array. length_spacing: float, `get_thick_line()`. line_thickness: float, `get_thick_line()`. width_spacing: float, `get_thick_line()`. """ profile_parameters = {} profile_parameters["length_spacing"] = length_spacing # pixel profile_parameters["line_thickness"] = line_thickness # pixel profile_parameters["width_spacing"] = width_spacing # pixel profile_parameters["normalized_intensities"] = True x_profile, y_profile = line_profile(image, point1, point2, **profile_parameters) def errorfunction(x, mu, sigma, mt, bg): # pylint: disable=no-member return bg + (0.5 * mt * special.erfc((x - mu) / (np.sqrt(2) * sigma))) model = lmfit.Model(errorfunction) fit_params = {} fit_params["mu"] = lmfit.Parameter("mu", value=x_profile[-1] / 2, min=0, max=x_profile[-1]) fit_params["sigma"] = lmfit.Parameter("sigma", value=1, vary=True, min=0, max=x_profile[-1]) fit_params["mt"] = lmfit.Parameter("mt", value=1, vary=True, min=0) fit_params["bg"] = lmfit.Parameter("bg", value=1, vary=True, min=0) fit_result = model.fit(y_profile.copy(), x=x_profile.copy(), **fit_params) return x_profile, y_profile, fit_result, errorfunction def microtubule_tip_fitter( tip_start, tip_end, image, get_thick_line_args, perpendicular_line_fit_args, offset_start, offset_end, tip_fit_args, ): """ Args: tip_start: tip_end: image: get_thick_line_args: perpendicular_line_fit_args: offset_start: offset_end: tip_fit_args: """ lines = get_thick_line(tip_start, tip_end, **get_thick_line_args) fitted_line = perpendicular_line_fit(lines, image, **perpendicular_line_fit_args) # Now we fit the best line from those points a, b = np.polyfit(fitted_line[:, 1], fitted_line[:, 0], deg=1) new_point1 = np.array([a * fitted_line[0, 1] + b, fitted_line[0, 1]]) new_point2 = np.array([a * fitted_line[-1, 1] + b, fitted_line[-1, 1]]) # Now we fit the microtubule using a line profile with a defined thickness. # Calculate the vector of the line and its norm vec = new_point2 - new_point1 # Get the coordinates of the points we'll use # to for line fitting. start_point = geometry.get_point_from_vector(-vec, new_point2, offset_start) end_point = geometry.get_point_from_vector(vec, new_point2, offset_end) line_fit_tips = np.array([start_point, end_point]) # Fit the tip tip_line_fit_results = tip_line_fit(line_fit_tips[0], line_fit_tips[1], image, **tip_fit_args) return [line_fit_tips] + list(tip_line_fit_results)
[ "numpy.polyfit", "lmfit.Parameter", "numpy.where", "numpy.array", "numpy.arange", "numpy.exp", "numpy.rollaxis", "numpy.sqrt", "lmfit.Model" ]
[((999, 1025), 'numpy.array', 'np.array', (['[point1, point2]'], {}), '([point1, point2])\n', (1007, 1025), True, 'import numpy as np\n'), ((4420, 4446), 'lmfit.Model', 'lmfit.Model', (['gaussian_wall'], {}), '(gaussian_wall)\n', (4431, 4446), False, 'import lmfit\n'), ((4820, 4842), 'numpy.rollaxis', 'np.rollaxis', (['lines', '(-1)'], {}), '(lines, -1)\n', (4831, 4842), True, 'import numpy as np\n'), ((5978, 5999), 'numpy.array', 'np.array', (['fitted_line'], {}), '(fitted_line)\n', (5986, 5999), True, 'import numpy as np\n'), ((6013, 6029), 'numpy.array', 'np.array', (['errors'], {}), '(errors)\n', (6021, 6029), True, 'import numpy as np\n'), ((7310, 7336), 'lmfit.Model', 'lmfit.Model', (['errorfunction'], {}), '(errorfunction)\n', (7321, 7336), False, 'import lmfit\n'), ((7381, 7453), 'lmfit.Parameter', 'lmfit.Parameter', (['"""mu"""'], {'value': '(x_profile[-1] / 2)', 'min': '(0)', 'max': 'x_profile[-1]'}), "('mu', value=x_profile[-1] / 2, min=0, max=x_profile[-1])\n", (7396, 7453), False, 'import lmfit\n'), ((7480, 7550), 'lmfit.Parameter', 'lmfit.Parameter', (['"""sigma"""'], {'value': '(1)', 'vary': '(True)', 'min': '(0)', 'max': 'x_profile[-1]'}), "('sigma', value=1, vary=True, min=0, max=x_profile[-1])\n", (7495, 7550), False, 'import lmfit\n'), ((7574, 7622), 'lmfit.Parameter', 'lmfit.Parameter', (['"""mt"""'], {'value': '(1)', 'vary': '(True)', 'min': '(0)'}), "('mt', value=1, vary=True, min=0)\n", (7589, 7622), False, 'import lmfit\n'), ((7646, 7694), 'lmfit.Parameter', 'lmfit.Parameter', (['"""bg"""'], {'value': '(1)', 'vary': '(True)', 'min': '(0)'}), "('bg', value=1, vary=True, min=0)\n", (7661, 7694), False, 'import lmfit\n'), ((8425, 8480), 'numpy.polyfit', 'np.polyfit', (['fitted_line[:, 1]', 'fitted_line[:, 0]'], {'deg': '(1)'}), '(fitted_line[:, 1], fitted_line[:, 0], deg=1)\n', (8435, 8480), True, 'import numpy as np\n'), ((8498, 8554), 'numpy.array', 'np.array', (['[a * fitted_line[0, 1] + b, fitted_line[0, 1]]'], {}), '([a * fitted_line[0, 1] + b, fitted_line[0, 1]])\n', (8506, 8554), True, 'import numpy as np\n'), ((8572, 8630), 'numpy.array', 'np.array', (['[a * fitted_line[-1, 1] + b, fitted_line[-1, 1]]'], {}), '([a * fitted_line[-1, 1] + b, fitted_line[-1, 1]])\n', (8580, 8630), True, 'import numpy as np\n'), ((9054, 9088), 'numpy.array', 'np.array', (['[start_point, end_point]'], {}), '([start_point, end_point])\n', (9062, 9088), True, 'import numpy as np\n'), ((1534, 1564), 'numpy.rollaxis', 'np.rollaxis', (['normal_points', '(-1)'], {}), '(normal_points, -1)\n', (1545, 1564), True, 'import numpy as np\n'), ((3470, 3502), 'numpy.arange', 'np.arange', (['(0)', 'y_profile.shape[0]'], {}), '(0, y_profile.shape[0])\n', (3479, 3502), True, 'import numpy as np\n'), ((5021, 5093), 'lmfit.Parameter', 'lmfit.Parameter', (['"""mu"""'], {'value': '(x_profile[-1] / 2)', 'min': '(0)', 'max': 'x_profile[-1]'}), "('mu', value=x_profile[-1] / 2, min=0, max=x_profile[-1])\n", (5036, 5093), False, 'import lmfit\n'), ((5124, 5196), 'lmfit.Parameter', 'lmfit.Parameter', (['"""sigma"""'], {'value': '(100)', 'vary': '(True)', 'min': '(0)', 'max': 'x_profile[-1]'}), "('sigma', value=100, vary=True, min=0, max=x_profile[-1])\n", (5139, 5196), False, 'import lmfit\n'), ((5246, 5295), 'lmfit.Parameter', 'lmfit.Parameter', (['"""mt"""'], {'value': '(50)', 'vary': '(True)', 'min': '(0)'}), "('mt', value=50, vary=True, min=0)\n", (5261, 5295), False, 'import lmfit\n'), ((5323, 5372), 'lmfit.Parameter', 'lmfit.Parameter', (['"""bg"""'], {'value': '(50)', 'vary': '(True)', 'min': '(0)'}), "('bg', value=50, vary=True, min=0)\n", (5338, 5372), False, 'import lmfit\n'), ((1585, 1603), 'numpy.array', 'np.array', (['[p1, p2]'], {}), '([p1, p2])\n', (1593, 1603), True, 'import numpy as np\n'), ((1740, 1755), 'numpy.array', 'np.array', (['lines'], {}), '(lines)\n', (1748, 1755), True, 'import numpy as np\n'), ((4363, 4401), 'numpy.exp', 'np.exp', (['(-0.5 * ((x - mu) / sigma) ** 2)'], {}), '(-0.5 * ((x - mu) / sigma) ** 2)\n', (4369, 4401), True, 'import numpy as np\n'), ((6153, 6191), 'numpy.where', 'np.where', (['(errors > mu_stderr_threshold)'], {}), '(errors > mu_stderr_threshold)\n', (6161, 6191), True, 'import numpy as np\n'), ((1784, 1802), 'numpy.array', 'np.array', (['[points]'], {}), '([points])\n', (1792, 1802), True, 'import numpy as np\n'), ((7275, 7285), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (7282, 7285), True, 'import numpy as np\n')]
"""Functions to plot M/EEG data e.g. topographies """ from __future__ import print_function # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: Simplified BSD import math import copy import numpy as np from scipy import linalg from ..baseline import rescale from ..io.constants import FIFF from ..io.pick import pick_types from ..utils import _clean_names, deprecated from .utils import tight_layout, _setup_vmin_vmax, DEFAULTS from .utils import _prepare_trellis, _check_delayed_ssp from .utils import _draw_proj_checkbox def _prepare_topo_plot(obj, ch_type, layout): """"Aux Function""" info = copy.deepcopy(obj.info) if layout is None and ch_type is not 'eeg': from ..layouts.layout import find_layout layout = find_layout(info) elif layout == 'auto': layout = None info['ch_names'] = _clean_names(info['ch_names']) for ii, this_ch in enumerate(info['chs']): this_ch['ch_name'] = info['ch_names'][ii] # special case for merging grad channels if (ch_type == 'grad' and FIFF.FIFFV_COIL_VV_PLANAR_T1 in np.unique([ch['coil_type'] for ch in info['chs']])): from ..layouts.layout import _pair_grad_sensors picks, pos = _pair_grad_sensors(info, layout) merge_grads = True else: merge_grads = False if ch_type == 'eeg': picks = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude='bads') else: picks = pick_types(info, meg=ch_type, ref_meg=False, exclude='bads') if len(picks) == 0: raise ValueError("No channels of type %r" % ch_type) if layout is None: chs = [info['chs'][i] for i in picks] from ..layouts.layout import _find_topomap_coords pos = _find_topomap_coords(chs, layout) else: names = [n.upper() for n in layout.names] pos = [layout.pos[names.index(info['ch_names'][k].upper())] for k in picks] return picks, pos, merge_grads, info['ch_names'] def _plot_update_evoked_topomap(params, bools): """ Helper to update topomaps """ projs = [proj for ii, proj in enumerate(params['projs']) if ii in np.where(bools)[0]] params['proj_bools'] = bools new_evoked = params['evoked'].copy() new_evoked.info['projs'] = [] new_evoked.add_proj(projs) new_evoked.apply_proj() data = new_evoked.data[np.ix_(params['picks'], params['time_idx'])] * params['scale'] if params['merge_grads']: from ..layouts.layout import _merge_grad_data data = _merge_grad_data(data) image_mask = params['image_mask'] pos_x, pos_y = np.asarray(params['pos'])[:, :2].T xi = np.linspace(pos_x.min(), pos_x.max(), params['res']) yi = np.linspace(pos_y.min(), pos_y.max(), params['res']) Xi, Yi = np.meshgrid(xi, yi) for ii, im in enumerate(params['images']): Zi = _griddata(pos_x, pos_y, data[:, ii], Xi, Yi) Zi[~image_mask] = np.nan im.set_data(Zi) for cont in params['contours']: cont.set_array(np.c_[Xi, Yi, Zi]) params['fig'].canvas.draw() def plot_projs_topomap(projs, layout=None, cmap='RdBu_r', sensors='k,', colorbar=False, res=64, size=1, show=True, outlines='head', contours=6, image_interp='bilinear'): """Plot topographic maps of SSP projections Parameters ---------- projs : list of Projection The projections layout : None | Layout | list of Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). Or a list of Layout if projections are from different sensor types. cmap : matplotlib colormap Colormap. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). colorbar : bool Plot a colorbar. res : int The resolution of the topomap image (n pixels along each side). size : scalar Side length of the topomaps in inches (only applies when plotting multiple topomaps at a time). show : bool Show figures if True outlines : 'head' | dict | None The outlines to be drawn. If 'head', a head scheme will be drawn. If dict, each key refers to a tuple of x and y positions. The values in 'mask_pos' will serve as image mask. If None, nothing will be drawn. Defaults to 'head'. contours : int | False | None The number of contour lines to draw. If 0, no contours will be drawn. image_interp : str The image interpolation to be used. All matplotlib options are accepted. Returns ------- fig : instance of matplotlib figure Figure distributing one image per channel across sensor topography. """ import matplotlib.pyplot as plt if layout is None: from ..layouts import read_layout layout = read_layout('Vectorview-all') if not isinstance(layout, list): layout = [layout] n_projs = len(projs) nrows = math.floor(math.sqrt(n_projs)) ncols = math.ceil(n_projs / nrows) fig = plt.gcf() fig.clear() for k, proj in enumerate(projs): ch_names = _clean_names(proj['data']['col_names']) data = proj['data']['data'].ravel() idx = [] for l in layout: is_vv = l.kind.startswith('Vectorview') if is_vv: from ..layouts.layout import _pair_grad_sensors_from_ch_names grad_pairs = _pair_grad_sensors_from_ch_names(ch_names) if grad_pairs: ch_names = [ch_names[i] for i in grad_pairs] idx = [l.names.index(c) for c in ch_names if c in l.names] if len(idx) == 0: continue pos = l.pos[idx] if is_vv and grad_pairs: from ..layouts.layout import _merge_grad_data shape = (len(idx) / 2, 2, -1) pos = pos.reshape(shape).mean(axis=1) data = _merge_grad_data(data[grad_pairs]).ravel() break ax = plt.subplot(nrows, ncols, k + 1) ax.set_title(proj['desc'][:10] + '...') if len(idx): plot_topomap(data, pos, vmax=None, cmap=cmap, sensors=sensors, res=res, outlines=outlines, contours=contours, image_interp=image_interp) if colorbar: plt.colorbar() else: raise RuntimeError('Cannot find a proper layout for projection %s' % proj['desc']) fig = ax.get_figure() if show and plt.get_backend() != 'agg': fig.show() tight_layout(fig=fig) return fig def _check_outlines(pos, outlines, head_scale=0.85): """Check or create outlines for topoplot """ pos = np.asarray(pos) if outlines in ('head', None): radius = 0.5 step = 2 * np.pi / 101 l = np.arange(0, 2 * np.pi + step, step) head_x = np.cos(l) * radius head_y = np.sin(l) * radius nose_x = np.array([0.18, 0, -0.18]) * radius nose_y = np.array([radius - .004, radius * 1.15, radius - .004]) ear_x = np.array([.497, .510, .518, .5299, .5419, .54, .547, .532, .510, .489]) ear_y = np.array([.0555, .0775, .0783, .0746, .0555, -.0055, -.0932, -.1313, -.1384, -.1199]) x, y = pos[:, :2].T x_range = np.abs(x.max() - x.min()) y_range = np.abs(y.max() - y.min()) # shift and scale the electrode positions pos[:, 0] = head_scale * ((pos[:, 0] - x.min()) / x_range - 0.5) pos[:, 1] = head_scale * ((pos[:, 1] - y.min()) / y_range - 0.5) # Define the outline of the head, ears and nose if outlines is not None: outlines = dict(head=(head_x, head_y), nose=(nose_x, nose_y), ear_left=(ear_x, ear_y), ear_right=(-ear_x, ear_y)) else: outlines = dict() outlines['mask_pos'] = head_x, head_y elif isinstance(outlines, dict): if 'mask_pos' not in outlines: raise ValueError('You must specify the coordinates of the image' 'mask') else: raise ValueError('Invalid value for `outlines') return pos, outlines def _inside_contour(pos, contour): """Aux function""" npos, ncnt = len(pos), len(contour) x, y = pos[:, :2].T check_mask = np.ones((npos), dtype=bool) check_mask[((x < np.min(x)) | (y < np.min(y)) | (x > np.max(x)) | (y > np.max(y)))] = False critval = 0.1 sel = np.where(check_mask)[0] for this_sel in sel: contourx = contour[:, 0] - pos[this_sel, 0] contoury = contour[:, 1] - pos[this_sel, 1] angle = np.arctan2(contoury, contourx) angle = np.unwrap(angle) total = np.sum(np.diff(angle)) check_mask[this_sel] = np.abs(total) > critval return check_mask def _griddata(x, y, v, xi, yi): """Aux function""" xy = x.ravel() + y.ravel() * -1j d = xy[None, :] * np.ones((len(xy), 1)) d = np.abs(d - d.T) n = d.shape[0] d.flat[::n + 1] = 1. g = (d * d) * (np.log(d) - 1.) g.flat[::n + 1] = 0. weights = linalg.solve(g, v.ravel()) m, n = xi.shape zi = np.zeros_like(xi) xy = xy.T g = np.empty(xy.shape) for i in range(m): for j in range(n): d = np.abs(xi[i, j] + -1j * yi[i, j] - xy) mask = np.where(d == 0)[0] if len(mask): d[mask] = 1. np.log(d, out=g) g -= 1. g *= d * d if len(mask): g[mask] = 0. zi[i, j] = g.dot(weights) return zi def plot_topomap(data, pos, vmax=None, vmin=None, cmap='RdBu_r', sensors='k,', res=64, axis=None, names=None, show_names=False, mask=None, mask_params=None, outlines='head', image_mask=None, contours=6, image_interp='bilinear'): """Plot a topographic map as image Parameters ---------- data : array, length = n_points The data values to plot. pos : array, shape = (n_points, 2) For each data point, the x and y coordinates. vmin : float | callable The value specfying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). vmax : float | callable The value specfying the upper bound of the color range. If None, the maximum absolute value is used. If vmin is None, but vmax is not, defaults to np.min(data). If callable, the output equals vmax(data). cmap : matplotlib colormap Colormap. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). res : int The resolution of the topomap image (n pixels along each side). axis : instance of Axis | None The axis to plot to. If None, the current axis will be used. names : list | None List of channel names. If None, channel names are not plotted. show_names : bool | callable If True, show channel names on top of the map. If a callable is passed, channel names will be formatted using the callable; e.g., to delete the prefix 'MEG ' from all channel names, pass the function lambda x: x.replace('MEG ', ''). If `mask` is not None, only significant sensors will be shown. mask : ndarray of bool, shape (n_channels, n_times) | None The channels to be marked as significant at a given time point. Indices set to `True` will be considered. Defaults to None. mask_params : dict | None Additional plotting parameters for plotting significant sensors. Default (None) equals: dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4) outlines : 'head' | dict | None The outlines to be drawn. If 'head', a head scheme will be drawn. If dict, each key refers to a tuple of x and y positions. The values in 'mask_pos' will serve as image mask. If None, nothing will be drawn. Defaults to 'head'. image_mask : ndarray of bool, shape (res, res) | None The image mask to cover the interpolated surface. If None, it will be computed from the outline. contour : int | False | None The number of contour lines to draw. If 0, no contours will be drawn. image_interp : str The image interpolation to be used. All matplotlib options are accepted. Returns ------- im : matplotlib.image.AxesImage The interpolated data. cn : matplotlib.contour.ContourSet The fieldlines. """ import matplotlib.pyplot as plt data = np.asarray(data) if data.ndim > 1: err = ("Data needs to be array of shape (n_sensors,); got shape " "%s." % str(data.shape)) raise ValueError(err) elif len(data) != len(pos): err = ("Data and pos need to be of same length. Got data of shape %s, " "pos of shape %s." % (str(), str())) axes = plt.gca() axes.set_frame_on(False) vmin, vmax = _setup_vmin_vmax(data, vmin, vmax) plt.xticks(()) plt.yticks(()) pos, outlines = _check_outlines(pos, outlines) pos_x = pos[:, 0] pos_y = pos[:, 1] ax = axis if axis else plt.gca() if any([not pos_y.any(), not pos_x.any()]): raise RuntimeError('No position information found, cannot compute ' 'geometries for topomap.') if outlines is None: xmin, xmax = pos_x.min(), pos_x.max() ymin, ymax = pos_y.min(), pos_y.max() else: xlim = np.inf, -np.inf, ylim = np.inf, -np.inf, mask_ = np.c_[outlines['mask_pos']] xmin, xmax = (np.min(np.r_[xlim[0], mask_[:, 0] * 1.01]), np.max(np.r_[xlim[1], mask_[:, 0] * 1.01])) ymin, ymax = (np.min(np.r_[ylim[0], mask_[:, 1] * 1.01]), np.max(np.r_[ylim[1], mask_[:, 1] * 1.01])) # interpolate data xi = np.linspace(xmin, xmax, res) yi = np.linspace(ymin, ymax, res) Xi, Yi = np.meshgrid(xi, yi) Zi = _griddata(pos_x, pos_y, data, Xi, Yi) if outlines is None: _is_default_outlines = False elif isinstance(outlines, dict): _is_default_outlines = any([k.startswith('head') for k in outlines]) if _is_default_outlines and image_mask is None: # prepare masking image_mask, pos = _make_image_mask(outlines, pos, res) if image_mask is not None and not _is_default_outlines: Zi[~image_mask] = np.nan if mask_params is None: mask_params = DEFAULTS['mask_params'].copy() elif isinstance(mask_params, dict): params = dict((k, v) for k, v in DEFAULTS['mask_params'].items() if k not in mask_params) mask_params.update(params) else: raise ValueError('`mask_params` must be of dict-type ' 'or None') # plot map and countour im = ax.imshow(Zi, cmap=cmap, vmin=vmin, vmax=vmax, origin='lower', aspect='equal', extent=(xmin, xmax, ymin, ymax), interpolation=image_interp) # plot outline linewidth = mask_params['markeredgewidth'] if isinstance(outlines, dict): for k, (x, y) in outlines.items(): if 'mask' in k: continue ax.plot(x, y, color='k', linewidth=linewidth) # This tackles an incomprehensible matplotlib bug if no contours are # drawn. To avoid rescalings, we will always draw contours. # But if no contours are desired we only draw one and make it invisible . no_contours = False if contours in (False, None): contours, no_contours = 1, True cont = ax.contour(Xi, Yi, Zi, contours, colors='k', linewidths=linewidth) if no_contours is True: for col in cont.collections: col.set_visible(False) if _is_default_outlines: from matplotlib import patches # remove nose offset and tweak patch = patches.Circle((0.5, 0.4687), radius=.46, clip_on=True, transform=ax.transAxes) im.set_clip_path(patch) ax.set_clip_path(patch) if cont is not None: for col in cont.collections: col.set_clip_path(patch) if sensors is True: sensors = 'k,' if sensors and mask is None: ax.plot(pos_x, pos_y, sensors) elif sensors and mask is not None: idx = np.where(mask)[0] ax.plot(pos_x[idx], pos_y[idx], **mask_params) idx = np.where(~mask)[0] ax.plot(pos_x[idx], pos_y[idx], sensors) if show_names: if show_names is True: show_names = lambda x: x show_idx = np.arange(len(names)) if mask is None else np.where(mask)[0] for ii, (p, ch_id) in enumerate(zip(pos, names)): if ii not in show_idx: continue ch_id = show_names(ch_id) ax.text(p[0], p[1], ch_id, horizontalalignment='center', verticalalignment='center', size='x-small') plt.subplots_adjust(top=.95) return im, cont def _make_image_mask(outlines, pos, res): """Aux function """ mask_ = np.c_[outlines['mask_pos']] xmin, xmax = (np.min(np.r_[np.inf, mask_[:, 0]]), np.max(np.r_[-np.inf, mask_[:, 0]])) ymin, ymax = (np.min(np.r_[np.inf, mask_[:, 1]]), np.max(np.r_[-np.inf, mask_[:, 1]])) inside = _inside_contour(pos, mask_) outside = np.invert(inside) outlier_points = pos[outside] while np.any(outlier_points): # auto shrink pos *= 0.99 inside = _inside_contour(pos, mask_) outside = np.invert(inside) outlier_points = pos[outside] image_mask = np.zeros((res, res), dtype=bool) xi_mask = np.linspace(xmin, xmax, res) yi_mask = np.linspace(ymin, ymax, res) Xi_mask, Yi_mask = np.meshgrid(xi_mask, yi_mask) pos_ = np.c_[Xi_mask.flatten(), Yi_mask.flatten()] inds = _inside_contour(pos_, mask_) image_mask[inds.reshape(image_mask.shape)] = True return image_mask, pos @deprecated('`plot_ica_topomap` is deprecated and will be removed in ' 'MNE 1.0. Use `plot_ica_components` instead') def plot_ica_topomap(ica, source_idx, ch_type='mag', res=64, layout=None, vmax=None, cmap='RdBu_r', sensors='k,', colorbar=True, show=True): """This functoin is deprecated See ``plot_ica_components``. """ return plot_ica_components(ica, source_idx, ch_type, res, layout, vmax, cmap, sensors, colorbar) def plot_ica_components(ica, picks=None, ch_type='mag', res=64, layout=None, vmin=None, vmax=None, cmap='RdBu_r', sensors='k,', colorbar=False, title=None, show=True, outlines='head', contours=6, image_interp='bilinear'): """Project unmixing matrix on interpolated sensor topogrpahy. Parameters ---------- ica : instance of mne.preprocessing.ICA The ICA solution. picks : int | array-like | None The indices of the sources to be plotted. If None all are plotted in batches of 20. ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. layout : None | Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout is inferred from the data. vmin : float | callable The value specfying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). vmax : float | callable The value specfying the upper bound of the color range. If None, the maximum absolute value is used. If vmin is None, but vmax is not, defaults to np.min(data). If callable, the output equals vmax(data). cmap : matplotlib colormap Colormap. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). colorbar : bool Plot a colorbar. res : int The resolution of the topomap image (n pixels along each side). show : bool Call pyplot.show() at the end. outlines : 'head' | dict | None The outlines to be drawn. If 'head', a head scheme will be drawn. If dict, each key refers to a tuple of x and y positions. The values in 'mask_pos' will serve as image mask. If None, nothing will be drawn. defaults to 'head'. contours : int | False | None The number of contour lines to draw. If 0, no contours will be drawn. image_interp : str The image interpolation to be used. All matplotlib options are accepted. Returns ------- fig : instance of matplotlib.pyplot.Figure or list The figure object(s). """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid import make_axes_locatable if picks is None: # plot components by sets of 20 n_components = ica.mixing_matrix_.shape[1] p = 20 figs = [] for k in range(0, n_components, p): picks = range(k, min(k + p, n_components)) fig = plot_ica_components(ica, picks=picks, ch_type=ch_type, res=res, layout=layout, vmax=vmax, cmap=cmap, sensors=sensors, colorbar=colorbar, title=title, show=show, outlines=outlines, contours=contours, image_interp=image_interp) figs.append(fig) return figs elif np.isscalar(picks): picks = [picks] data = np.dot(ica.mixing_matrix_[:, picks].T, ica.pca_components_[:ica.n_components_]) if ica.info is None: raise RuntimeError('The ICA\'s measurement info is missing. Please ' 'fit the ICA or add the corresponding info object.') data_picks, pos, merge_grads, names = _prepare_topo_plot(ica, ch_type, layout) pos, outlines = _check_outlines(pos, outlines) if outlines not in (None, 'head'): image_mask, pos = _make_image_mask(outlines, pos, res) else: image_mask = None data = np.atleast_2d(data) data = data[:, data_picks] # prepare data for iteration fig, axes = _prepare_trellis(len(data), max_col=5) if title is None: title = 'ICA components' fig.suptitle(title) if merge_grads: from ..layouts.layout import _merge_grad_data for ii, data_, ax in zip(picks, data, axes): ax.set_title('IC #%03d' % ii, fontsize=12) data_ = _merge_grad_data(data_) if merge_grads else data_ vmin_, vmax_ = _setup_vmin_vmax(data_, vmin, vmax) im = plot_topomap(data_.flatten(), pos, vmin=vmin_, vmax=vmax_, res=res, axis=ax, cmap=cmap, outlines=outlines, image_mask=image_mask, contours=contours, image_interp=image_interp)[0] if colorbar: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap) cbar.ax.tick_params(labelsize=12) cbar.set_ticks((vmin_, vmax_)) cbar.ax.set_title('AU', fontsize=10) ax.set_yticks([]) ax.set_xticks([]) ax.set_frame_on(False) tight_layout(fig=fig) fig.subplots_adjust(top=0.95) fig.canvas.draw() if show is True: plt.show() return fig def plot_tfr_topomap(tfr, tmin=None, tmax=None, fmin=None, fmax=None, ch_type='mag', baseline=None, mode='mean', layout=None, vmax=None, vmin=None, cmap='RdBu_r', sensors='k,', colorbar=True, unit=None, res=64, size=2, format='%1.1e', show_names=False, title=None, axes=None, show=True): """Plot topographic maps of specific time-frequency intervals of TFR data Parameters ---------- tfr : AvereageTFR The AvereageTFR object. tmin : None | float The first time instant to display. If None the first time point available is used. tmax : None | float The last time instant to display. If None the last time point available is used. fmin : None | float The first frequency to display. If None the first frequency available is used. fmax : None | float The last frequency to display. If None the last frequency available is used. ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. baseline : tuple or list of length 2 The time interval to apply rescaling / baseline correction. If None do not apply it. If baseline is (a, b) the interval is between "a (s)" and "b (s)". If a is None the beginning of the data is used and if b is None then b is set to the end of the interval. If baseline is equal to (None, None) all the time interval is used. mode : 'logratio' | 'ratio' | 'zscore' | 'mean' | 'percent' Do baseline correction with ratio (power is divided by mean power during baseline) or z-score (power is divided by standard deviation of power during baseline after subtracting the mean, power = [power - mean(power_baseline)] / std(power_baseline)) If None, baseline no correction will be performed. layout : None | Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. vmin : float | callable The value specfying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). vmax : float | callable The value specfying the upper bound of the color range. If None, the maximum absolute value is used. If vmin is None, but vmax is not, defaults to np.min(data). If callable, the output equals vmax(data). cmap : matplotlib colormap Colormap. For magnetometers and eeg defaults to 'RdBu_r', else 'Reds'. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). colorbar : bool Plot a colorbar. unit : str | None The unit of the channel type used for colorbar labels. res : int The resolution of the topomap image (n pixels along each side). size : float Side length per topomap in inches. format : str String format for colorbar values. show_names : bool | callable If True, show channel names on top of the map. If a callable is passed, channel names will be formatted using the callable; e.g., to delete the prefix 'MEG ' from all channel names, pass the function lambda x: x.replace('MEG ', ''). If `mask` is not None, only significant sensors will be shown. title : str | None Title. If None (default), no title is displayed. axes : instance of Axis | None The axes to plot to. If None the axes is defined automatically. show : bool Call pyplot.show() at the end. Returns ------- fig : matplotlib.figure.Figure The figure containing the topography. """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable picks, pos, merge_grads, names = _prepare_topo_plot(tfr, ch_type, layout) if not show_names: names = None data = tfr.data if mode is not None and baseline is not None: data = rescale(data, tfr.times, baseline, mode, copy=True) # crop time itmin, itmax = None, None if tmin is not None: itmin = np.where(tfr.times >= tmin)[0][0] if tmax is not None: itmax = np.where(tfr.times <= tmax)[0][-1] # crop freqs ifmin, ifmax = None, None if fmin is not None: ifmin = np.where(tfr.freqs >= fmin)[0][0] if fmax is not None: ifmax = np.where(tfr.freqs <= fmax)[0][-1] data = data[picks, ifmin:ifmax, itmin:itmax] data = np.mean(np.mean(data, axis=2), axis=1)[:, np.newaxis] if merge_grads: from ..layouts.layout import _merge_grad_data data = _merge_grad_data(data) vmin, vmax = _setup_vmin_vmax(data, vmin, vmax) if axes is None: fig = plt.figure() ax = fig.gca() else: fig = axes.figure ax = axes ax.set_yticks([]) ax.set_xticks([]) ax.set_frame_on(False) if title is not None: ax.set_title(title) im, _ = plot_topomap(data[:, 0], pos, vmin=vmin, vmax=vmax, axis=ax, cmap=cmap, image_interp='bilinear', contours=False, names=names) if colorbar: divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap) cbar.set_ticks((vmin, vmax)) cbar.ax.tick_params(labelsize=12) cbar.ax.set_title('AU') if show: plt.show() return fig def plot_evoked_topomap(evoked, times=None, ch_type='mag', layout=None, vmax=None, vmin=None, cmap='RdBu_r', sensors='k,', colorbar=True, scale=None, scale_time=1e3, unit=None, res=64, size=1, format='%3.1f', time_format='%01d ms', proj=False, show=True, show_names=False, title=None, mask=None, mask_params=None, outlines='head', contours=6, image_interp='bilinear'): """Plot topographic maps of specific time points of evoked data Parameters ---------- evoked : Evoked The Evoked object. times : float | array of floats | None. The time point(s) to plot. If None, 10 topographies will be shown will a regular time spacing between the first and last time instant. ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' The channel type to plot. For 'grad', the gradiometers are collected in pairs and the RMS for each pair is plotted. layout : None | Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. vmin : float | callable The value specfying the lower bound of the color range. If None, and vmax is None, -vmax is used. Else np.min(data). If callable, the output equals vmin(data). vmax : float | callable The value specfying the upper bound of the color range. If None, the maximum absolute value is used. If vmin is None, but vmax is not, defaults to np.min(data). If callable, the output equals vmax(data). cmap : matplotlib colormap Colormap. For magnetometers and eeg defaults to 'RdBu_r', else 'Reds'. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). colorbar : bool Plot a colorbar. scale : float | None Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13 for grad and 1e15 for mag. scale_time : float | None Scale the time labels. Defaults to 1e3 (ms). unit : str | None The unit of the channel type used for colorbar label. If scale is None the unit is automatically determined. res : int The resolution of the topomap image (n pixels along each side). size : float Side length per topomap in inches. format : str String format for colorbar values. time_format : str String format for topomap values. Defaults to "%01d ms" proj : bool | 'interactive' If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be show. show : bool Call pyplot.show() at the end. show_names : bool | callable If True, show channel names on top of the map. If a callable is passed, channel names will be formatted using the callable; e.g., to delete the prefix 'MEG ' from all channel names, pass the function lambda x: x.replace('MEG ', ''). If `mask` is not None, only significant sensors will be shown. title : str | None Title. If None (default), no title is displayed. mask : ndarray of bool, shape (n_channels, n_times) | None The channels to be marked as significant at a given time point. Indicies set to `True` will be considered. Defaults to None. mask_params : dict | None Additional plotting parameters for plotting significant sensors. Default (None) equals: dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markersize=4) outlines : 'head' | dict | None The outlines to be drawn. If 'head', a head scheme will be drawn. If dict, each key refers to a tuple of x and y positions. The values in 'mask_pos' will serve as image mask. If None, nothing will be drawn. Defaults to 'head'. contours : int | False | None The number of contour lines to draw. If 0, no contours will be drawn. image_interp : str The image interpolation to be used. All matplotlib options are accepted. """ import matplotlib.pyplot as plt if ch_type.startswith('planar'): key = 'grad' else: key = ch_type if scale is None: scale = DEFAULTS['scalings'][key] unit = DEFAULTS['units'][key] if mask_params is None: mask_params = DEFAULTS['mask_params'].copy() mask_params['markersize'] *= size / 2. mask_params['markeredgewidth'] *= size / 2. if times is None: times = np.linspace(evoked.times[0], evoked.times[-1], 10) elif np.isscalar(times): times = [times] if len(times) > 20: raise RuntimeError('Too many plots requested. Please pass fewer ' 'than 20 time instants.') tmin, tmax = evoked.times[[0, -1]] for t in times: if not tmin <= t <= tmax: raise ValueError('Times should be between %0.3f and %0.3f. (Got ' '%0.3f).' % (tmin, tmax, t)) picks, pos, merge_grads, names = _prepare_topo_plot(evoked, ch_type, layout) if not show_names: names = None n = len(times) nax = n + bool(colorbar) width = size * nax height = size * 1. + max(0, 0.1 * (4 - size)) fig = plt.figure(figsize=(width, height)) w_frame = plt.rcParams['figure.subplot.wspace'] / (2 * nax) top_frame = max((0.05 if title is None else 0.15), .2 / size) fig.subplots_adjust(left=w_frame, right=1 - w_frame, bottom=0, top=1 - top_frame) time_idx = [np.where(evoked.times >= t)[0][0] for t in times] if proj is True and evoked.proj is not True: data = evoked.copy().apply_proj().data else: data = evoked.data data = data[np.ix_(picks, time_idx)] * scale if merge_grads: from ..layouts.layout import _merge_grad_data data = _merge_grad_data(data) vmin, vmax = _setup_vmin_vmax(data, vmin, vmax) images, contours_ = [], [] if mask is not None: _picks = picks[::2 if ch_type not in ['mag', 'eeg'] else 1] mask_ = mask[np.ix_(_picks, time_idx)] pos, outlines = _check_outlines(pos, outlines) if outlines is not None: image_mask, pos = _make_image_mask(outlines, pos, res) else: image_mask = None for i, t in enumerate(times): ax = plt.subplot(1, nax, i + 1) tp, cn = plot_topomap(data[:, i], pos, vmin=vmin, vmax=vmax, sensors=sensors, res=res, names=names, show_names=show_names, cmap=cmap, mask=mask_[:, i] if mask is not None else None, mask_params=mask_params, axis=ax, outlines=outlines, image_mask=image_mask, contours=contours, image_interp=image_interp) images.append(tp) if cn is not None: contours_.append(cn) if time_format is not None: plt.title(time_format % (t * scale_time)) if colorbar: cax = plt.subplot(1, n + 1, n + 1) plt.colorbar(images[-1], ax=cax, cax=cax, ticks=[vmin, 0, vmax], format=format) # resize the colorbar (by default the color fills the whole axes) cpos = cax.get_position() if size <= 1: cpos.x0 = 1 - (.7 + .1 / size) / nax cpos.x1 = cpos.x0 + .1 / nax cpos.y0 = .1 cpos.y1 = .7 cax.set_position(cpos) if unit is not None: cax.set_title(unit) if proj == 'interactive': _check_delayed_ssp(evoked) params = dict(evoked=evoked, fig=fig, projs=evoked.info['projs'], picks=picks, images=images, contours=contours_, time_idx=time_idx, scale=scale, merge_grads=merge_grads, res=res, pos=pos, image_mask=image_mask, plot_update_proj_callback=_plot_update_evoked_topomap) _draw_proj_checkbox(None, params) if title is not None: plt.suptitle(title, verticalalignment='top', size='x-large') tight_layout(pad=2 * size / 2.0, fig=fig) if show: plt.show() return fig
[ "matplotlib.pyplot.title", "numpy.abs", "numpy.arctan2", "numpy.invert", "matplotlib.pyplot.suptitle", "numpy.empty", "numpy.ones", "matplotlib.pyplot.figure", "numpy.sin", "numpy.arange", "matplotlib.pyplot.get_backend", "numpy.mean", "matplotlib.pyplot.gca", "numpy.unique", "numpy.atle...
[((683, 706), 'copy.deepcopy', 'copy.deepcopy', (['obj.info'], {}), '(obj.info)\n', (696, 706), False, 'import copy\n'), ((3015, 3034), 'numpy.meshgrid', 'np.meshgrid', (['xi', 'yi'], {}), '(xi, yi)\n', (3026, 3034), True, 'import numpy as np\n'), ((5363, 5389), 'math.ceil', 'math.ceil', (['(n_projs / nrows)'], {}), '(n_projs / nrows)\n', (5372, 5389), False, 'import math\n'), ((5401, 5410), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (5408, 5410), True, 'import matplotlib.pyplot as plt\n'), ((7132, 7147), 'numpy.asarray', 'np.asarray', (['pos'], {}), '(pos)\n', (7142, 7147), True, 'import numpy as np\n'), ((8825, 8850), 'numpy.ones', 'np.ones', (['npos'], {'dtype': 'bool'}), '(npos, dtype=bool)\n', (8832, 8850), True, 'import numpy as np\n'), ((9490, 9505), 'numpy.abs', 'np.abs', (['(d - d.T)'], {}), '(d - d.T)\n', (9496, 9505), True, 'import numpy as np\n'), ((9682, 9699), 'numpy.zeros_like', 'np.zeros_like', (['xi'], {}), '(xi)\n', (9695, 9699), True, 'import numpy as np\n'), ((9723, 9741), 'numpy.empty', 'np.empty', (['xy.shape'], {}), '(xy.shape)\n', (9731, 9741), True, 'import numpy as np\n'), ((13312, 13328), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (13322, 13328), True, 'import numpy as np\n'), ((13671, 13680), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (13678, 13680), True, 'import matplotlib.pyplot as plt\n'), ((13768, 13782), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (13778, 13782), True, 'import matplotlib.pyplot as plt\n'), ((13787, 13801), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (13797, 13801), True, 'import matplotlib.pyplot as plt\n'), ((14645, 14673), 'numpy.linspace', 'np.linspace', (['xmin', 'xmax', 'res'], {}), '(xmin, xmax, res)\n', (14656, 14673), True, 'import numpy as np\n'), ((14683, 14711), 'numpy.linspace', 'np.linspace', (['ymin', 'ymax', 'res'], {}), '(ymin, ymax, res)\n', (14694, 14711), True, 'import numpy as np\n'), ((14725, 14744), 'numpy.meshgrid', 'np.meshgrid', (['xi', 'yi'], {}), '(xi, yi)\n', (14736, 14744), True, 'import numpy as np\n'), ((17807, 17836), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(0.95)'}), '(top=0.95)\n', (17826, 17836), True, 'import matplotlib.pyplot as plt\n'), ((18244, 18261), 'numpy.invert', 'np.invert', (['inside'], {}), '(inside)\n', (18253, 18261), True, 'import numpy as np\n'), ((18306, 18328), 'numpy.any', 'np.any', (['outlier_points'], {}), '(outlier_points)\n', (18312, 18328), True, 'import numpy as np\n'), ((18501, 18533), 'numpy.zeros', 'np.zeros', (['(res, res)'], {'dtype': 'bool'}), '((res, res), dtype=bool)\n', (18509, 18533), True, 'import numpy as np\n'), ((18548, 18576), 'numpy.linspace', 'np.linspace', (['xmin', 'xmax', 'res'], {}), '(xmin, xmax, res)\n', (18559, 18576), True, 'import numpy as np\n'), ((18591, 18619), 'numpy.linspace', 'np.linspace', (['ymin', 'ymax', 'res'], {}), '(ymin, ymax, res)\n', (18602, 18619), True, 'import numpy as np\n'), ((18643, 18672), 'numpy.meshgrid', 'np.meshgrid', (['xi_mask', 'yi_mask'], {}), '(xi_mask, yi_mask)\n', (18654, 18672), True, 'import numpy as np\n'), ((22834, 22913), 'numpy.dot', 'np.dot', (['ica.mixing_matrix_[:, picks].T', 'ica.pca_components_[:ica.n_components_]'], {}), '(ica.mixing_matrix_[:, picks].T, ica.pca_components_[:ica.n_components_])\n', (22840, 22913), True, 'import numpy as np\n'), ((23461, 23480), 'numpy.atleast_2d', 'np.atleast_2d', (['data'], {}), '(data)\n', (23474, 23480), True, 'import numpy as np\n'), ((36657, 36692), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(width, height)'}), '(figsize=(width, height))\n', (36667, 36692), True, 'import matplotlib.pyplot as plt\n'), ((5331, 5349), 'math.sqrt', 'math.sqrt', (['n_projs'], {}), '(n_projs)\n', (5340, 5349), False, 'import math\n'), ((6386, 6418), 'matplotlib.pyplot.subplot', 'plt.subplot', (['nrows', 'ncols', '(k + 1)'], {}), '(nrows, ncols, k + 1)\n', (6397, 6418), True, 'import matplotlib.pyplot as plt\n'), ((7247, 7283), 'numpy.arange', 'np.arange', (['(0)', '(2 * np.pi + step)', 'step'], {}), '(0, 2 * np.pi + step, step)\n', (7256, 7283), True, 'import numpy as np\n'), ((7426, 7483), 'numpy.array', 'np.array', (['[radius - 0.004, radius * 1.15, radius - 0.004]'], {}), '([radius - 0.004, radius * 1.15, radius - 0.004])\n', (7434, 7483), True, 'import numpy as np\n'), ((7498, 7577), 'numpy.array', 'np.array', (['[0.497, 0.51, 0.518, 0.5299, 0.5419, 0.54, 0.547, 0.532, 0.51, 0.489]'], {}), '([0.497, 0.51, 0.518, 0.5299, 0.5419, 0.54, 0.547, 0.532, 0.51, 0.489])\n', (7506, 7577), True, 'import numpy as np\n'), ((7611, 7710), 'numpy.array', 'np.array', (['[0.0555, 0.0775, 0.0783, 0.0746, 0.0555, -0.0055, -0.0932, -0.1313, -0.1384,\n -0.1199]'], {}), '([0.0555, 0.0775, 0.0783, 0.0746, 0.0555, -0.0055, -0.0932, -0.1313,\n -0.1384, -0.1199])\n', (7619, 7710), True, 'import numpy as np\n'), ((8994, 9014), 'numpy.where', 'np.where', (['check_mask'], {}), '(check_mask)\n', (9002, 9014), True, 'import numpy as np\n'), ((9163, 9193), 'numpy.arctan2', 'np.arctan2', (['contoury', 'contourx'], {}), '(contoury, contourx)\n', (9173, 9193), True, 'import numpy as np\n'), ((9210, 9226), 'numpy.unwrap', 'np.unwrap', (['angle'], {}), '(angle)\n', (9219, 9226), True, 'import numpy as np\n'), ((13925, 13934), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (13932, 13934), True, 'import matplotlib.pyplot as plt\n'), ((16700, 16785), 'matplotlib.patches.Circle', 'patches.Circle', (['(0.5, 0.4687)'], {'radius': '(0.46)', 'clip_on': '(True)', 'transform': 'ax.transAxes'}), '((0.5, 0.4687), radius=0.46, clip_on=True, transform=ax.transAxes\n )\n', (16714, 16785), False, 'from matplotlib import patches\n'), ((17988, 18022), 'numpy.min', 'np.min', (['np.r_[np.inf, mask_[:, 0]]'], {}), '(np.r_[np.inf, mask_[:, 0]])\n', (17994, 18022), True, 'import numpy as np\n'), ((18042, 18077), 'numpy.max', 'np.max', (['np.r_[-np.inf, mask_[:, 0]]'], {}), '(np.r_[-np.inf, mask_[:, 0]])\n', (18048, 18077), True, 'import numpy as np\n'), ((18097, 18131), 'numpy.min', 'np.min', (['np.r_[np.inf, mask_[:, 1]]'], {}), '(np.r_[np.inf, mask_[:, 1]])\n', (18103, 18131), True, 'import numpy as np\n'), ((18151, 18186), 'numpy.max', 'np.max', (['np.r_[-np.inf, mask_[:, 1]]'], {}), '(np.r_[-np.inf, mask_[:, 1]])\n', (18157, 18186), True, 'import numpy as np\n'), ((18428, 18445), 'numpy.invert', 'np.invert', (['inside'], {}), '(inside)\n', (18437, 18445), True, 'import numpy as np\n'), ((22778, 22796), 'numpy.isscalar', 'np.isscalar', (['picks'], {}), '(picks)\n', (22789, 22796), True, 'import numpy as np\n'), ((24790, 24800), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (24798, 24800), True, 'import matplotlib.pyplot as plt\n'), ((30123, 30135), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (30133, 30135), True, 'import matplotlib.pyplot as plt\n'), ((30565, 30588), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (30584, 30588), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((30668, 30720), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax', 'format': '"""%3.2f"""', 'cmap': 'cmap'}), "(im, cax=cax, format='%3.2f', cmap=cmap)\n", (30680, 30720), True, 'import matplotlib.pyplot as plt\n'), ((30854, 30864), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (30862, 30864), True, 'import matplotlib.pyplot as plt\n'), ((35859, 35909), 'numpy.linspace', 'np.linspace', (['evoked.times[0]', 'evoked.times[-1]', '(10)'], {}), '(evoked.times[0], evoked.times[-1], 10)\n', (35870, 35909), True, 'import numpy as np\n'), ((35919, 35937), 'numpy.isscalar', 'np.isscalar', (['times'], {}), '(times)\n', (35930, 35937), True, 'import numpy as np\n'), ((37749, 37775), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', 'nax', '(i + 1)'], {}), '(1, nax, i + 1)\n', (37760, 37775), True, 'import matplotlib.pyplot as plt\n'), ((38476, 38504), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(n + 1)', '(n + 1)'], {}), '(1, n + 1, n + 1)\n', (38487, 38504), True, 'import matplotlib.pyplot as plt\n'), ((38513, 38592), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['images[-1]'], {'ax': 'cax', 'cax': 'cax', 'ticks': '[vmin, 0, vmax]', 'format': 'format'}), '(images[-1], ax=cax, cax=cax, ticks=[vmin, 0, vmax], format=format)\n', (38525, 38592), True, 'import matplotlib.pyplot as plt\n'), ((39470, 39530), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['title'], {'verticalalignment': '"""top"""', 'size': '"""x-large"""'}), "(title, verticalalignment='top', size='x-large')\n", (39482, 39530), True, 'import matplotlib.pyplot as plt\n'), ((39602, 39612), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (39610, 39612), True, 'import matplotlib.pyplot as plt\n'), ((1160, 1210), 'numpy.unique', 'np.unique', (["[ch['coil_type'] for ch in info['chs']]"], {}), "([ch['coil_type'] for ch in info['chs']])\n", (1169, 1210), True, 'import numpy as np\n'), ((2565, 2608), 'numpy.ix_', 'np.ix_', (["params['picks']", "params['time_idx']"], {}), "(params['picks'], params['time_idx'])\n", (2571, 2608), True, 'import numpy as np\n'), ((2842, 2867), 'numpy.asarray', 'np.asarray', (["params['pos']"], {}), "(params['pos'])\n", (2852, 2867), True, 'import numpy as np\n'), ((6925, 6942), 'matplotlib.pyplot.get_backend', 'plt.get_backend', ([], {}), '()\n', (6940, 6942), True, 'import matplotlib.pyplot as plt\n'), ((7301, 7310), 'numpy.cos', 'np.cos', (['l'], {}), '(l)\n', (7307, 7310), True, 'import numpy as np\n'), ((7337, 7346), 'numpy.sin', 'np.sin', (['l'], {}), '(l)\n', (7343, 7346), True, 'import numpy as np\n'), ((7373, 7399), 'numpy.array', 'np.array', (['[0.18, 0, -0.18]'], {}), '([0.18, 0, -0.18])\n', (7381, 7399), True, 'import numpy as np\n'), ((9250, 9264), 'numpy.diff', 'np.diff', (['angle'], {}), '(angle)\n', (9257, 9264), True, 'import numpy as np\n'), ((9297, 9310), 'numpy.abs', 'np.abs', (['total'], {}), '(total)\n', (9303, 9310), True, 'import numpy as np\n'), ((9570, 9579), 'numpy.log', 'np.log', (['d'], {}), '(d)\n', (9576, 9579), True, 'import numpy as np\n'), ((9808, 9848), 'numpy.abs', 'np.abs', (['(xi[i, j] + -1.0j * yi[i, j] - xy)'], {}), '(xi[i, j] + -1.0j * yi[i, j] - xy)\n', (9814, 9848), True, 'import numpy as np\n'), ((9953, 9969), 'numpy.log', 'np.log', (['d'], {'out': 'g'}), '(d, out=g)\n', (9959, 9969), True, 'import numpy as np\n'), ((14370, 14412), 'numpy.min', 'np.min', (['np.r_[xlim[0], mask_[:, 0] * 1.01]'], {}), '(np.r_[xlim[0], mask_[:, 0] * 1.01])\n', (14376, 14412), True, 'import numpy as np\n'), ((14436, 14478), 'numpy.max', 'np.max', (['np.r_[xlim[1], mask_[:, 0] * 1.01]'], {}), '(np.r_[xlim[1], mask_[:, 0] * 1.01])\n', (14442, 14478), True, 'import numpy as np\n'), ((14502, 14544), 'numpy.min', 'np.min', (['np.r_[ylim[0], mask_[:, 1] * 1.01]'], {}), '(np.r_[ylim[0], mask_[:, 1] * 1.01])\n', (14508, 14544), True, 'import numpy as np\n'), ((14568, 14610), 'numpy.max', 'np.max', (['np.r_[ylim[1], mask_[:, 1] * 1.01]'], {}), '(np.r_[ylim[1], mask_[:, 1] * 1.01])\n', (14574, 14610), True, 'import numpy as np\n'), ((24293, 24316), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (24312, 24316), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((24404, 24456), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax', 'format': '"""%3.2f"""', 'cmap': 'cmap'}), "(im, cax=cax, format='%3.2f', cmap=cmap)\n", (24416, 24456), True, 'import matplotlib.pyplot as plt\n'), ((29875, 29896), 'numpy.mean', 'np.mean', (['data'], {'axis': '(2)'}), '(data, axis=2)\n', (29882, 29896), True, 'import numpy as np\n'), ((37150, 37173), 'numpy.ix_', 'np.ix_', (['picks', 'time_idx'], {}), '(picks, time_idx)\n', (37156, 37173), True, 'import numpy as np\n'), ((37495, 37519), 'numpy.ix_', 'np.ix_', (['_picks', 'time_idx'], {}), '(_picks, time_idx)\n', (37501, 37519), True, 'import numpy as np\n'), ((38402, 38443), 'matplotlib.pyplot.title', 'plt.title', (['(time_format % (t * scale_time))'], {}), '(time_format % (t * scale_time))\n', (38411, 38443), True, 'import matplotlib.pyplot as plt\n'), ((6728, 6742), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (6740, 6742), True, 'import matplotlib.pyplot as plt\n'), ((8944, 8953), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (8950, 8953), True, 'import numpy as np\n'), ((9866, 9882), 'numpy.where', 'np.where', (['(d == 0)'], {}), '(d == 0)\n', (9874, 9882), True, 'import numpy as np\n'), ((17190, 17204), 'numpy.where', 'np.where', (['mask'], {}), '(mask)\n', (17198, 17204), True, 'import numpy as np\n'), ((17277, 17292), 'numpy.where', 'np.where', (['(~mask)'], {}), '(~mask)\n', (17285, 17292), True, 'import numpy as np\n'), ((17495, 17509), 'numpy.where', 'np.where', (['mask'], {}), '(mask)\n', (17503, 17509), True, 'import numpy as np\n'), ((29497, 29524), 'numpy.where', 'np.where', (['(tfr.times >= tmin)'], {}), '(tfr.times >= tmin)\n', (29505, 29524), True, 'import numpy as np\n'), ((29572, 29599), 'numpy.where', 'np.where', (['(tfr.times <= tmax)'], {}), '(tfr.times <= tmax)\n', (29580, 29599), True, 'import numpy as np\n'), ((29696, 29723), 'numpy.where', 'np.where', (['(tfr.freqs >= fmin)'], {}), '(tfr.freqs >= fmin)\n', (29704, 29723), True, 'import numpy as np\n'), ((29771, 29798), 'numpy.where', 'np.where', (['(tfr.freqs <= fmax)'], {}), '(tfr.freqs <= fmax)\n', (29779, 29798), True, 'import numpy as np\n'), ((36949, 36976), 'numpy.where', 'np.where', (['(evoked.times >= t)'], {}), '(evoked.times >= t)\n', (36957, 36976), True, 'import numpy as np\n'), ((2349, 2364), 'numpy.where', 'np.where', (['bools'], {}), '(bools)\n', (2357, 2364), True, 'import numpy as np\n'), ((8926, 8935), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (8932, 8935), True, 'import numpy as np\n'), ((8874, 8883), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (8880, 8883), True, 'import numpy as np\n'), ((8892, 8901), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (8898, 8901), True, 'import numpy as np\n')]
""" Tests module segmentation_analysis # Author: <NAME> # $Id$ """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from builtins import next from builtins import range #from past.utils import old_div __version__ = "$Revision$" from copy import copy, deepcopy import unittest import numpy import numpy.testing as np_test import scipy #from pyto.segmentation.grey import Grey #from pyto.segmentation.segment import Segment #from pyto.segmentation.hierarchy import Hierarchy #from pyto.segmentation.thresh_conn import ThreshConn #import common as common from pyto.scene.segmentation_analysis import SegmentationAnalysis import pyto.segmentation.test.common as seg_cmn from pyto.segmentation.cleft import Cleft from pyto.scene.cleft_regions import CleftRegions class TestSegmentationAnalysis(np_test.TestCase): """ """ def setUp(self): """ """ self.reorder_warning = True def makeCleftLayers(self): """ Returns a CleftRegions object made using image 1, boundary 1 """ cleft = Cleft(data=seg_cmn.bound_1.data, bound1Id=3, bound2Id=4, cleftId=5) cleft_layers = CleftRegions(image=seg_cmn.image_1, cleft=cleft) cleft_layers.makeLayers(nBoundLayers=1) cleft_layers.findDensity(regions=cleft_layers.regions) return cleft_layers def testTcSegmentAnalyze(self): """ Tests tcSegmentAnalyze() and also getLabels(). """ ###################################################### # # Image 1, boundary 1, order <, boundary >= 1 # # make CleftLayers cleft_layers = self.makeCleftLayers() # do tc segmentation and analysis se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=[3], distanceMode='min', cleftLayers=cleft_layers) tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', count=True, doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True, doCleftContacts=True) # make and test individual segments id_dict = {} for count in range(len(seg_cmn.threshold_1)): # make level new_se, level, curr_thresh = next(tc_iter) seg = new_se.segments # test parameters np_test.assert_equal(new_se.nBoundary, se.nBoundary) np_test.assert_equal(new_se.boundCount, se.boundCount) np_test.assert_equal(new_se.structElConn, se.structElConn) np_test.assert_equal(new_se.contactStructElConn, se.contactStructElConn) np_test.assert_equal(new_se.countStructElConn, se.countStructElConn) np_test.assert_equal(new_se.lengthContact, se.lengthContact) np_test.assert_equal(new_se.lengthLine, se.lengthLine) # test levels and threshold np_test.assert_equal(level, count) np_test.assert_equal(curr_thresh, seg_cmn.threshold_1[level]) # test getLabels() np_test.assert_equal(new_se.labels, new_se.segments) np_test.assert_equal(new_se.ids, new_se.segments.ids) # test ids id_dict = seg_cmn.id_correspondence(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1[level], current=id_dict) converted_ids = [id_dict[id_] for id_ in seg_cmn.levelIds_1[level]] #np_test.assert_equal(seg.ids, seg_cmn.levelIds_1[level]) np_test.assert_equal(seg.ids, converted_ids) # test segments try: np_test.assert_equal(seg.data[2:6, 1:9], seg_cmn.data_1[level]) except AssertionError: np_test.assert_equal(seg.data[2:6, 1:9]>0, seg_cmn.data_1[level]>0) if self.reorder_warning: print( "The exact id assignment is different from what it was " + "when this test was written, but this really depends " + "on internals of scipy.ndimage. Considering that the " + "segments are correct, most likely everything is ok.") self.reorder_warning = False np_test.assert_equal( seg.contacts.findSegments(boundaryIds=[3,4], nBoundary=1), seg_cmn.levelIds_1[level]) # test boundaries bound_found = seg.contacts.findBoundaries(segmentIds=seg.ids, nSegment=1) if level == 0: np_test.assert_equal(bound_found, []) elif level == 1: np_test.assert_equal(bound_found, [3]) else: np_test.assert_equal(bound_found, [3,4]) # test segment analysis np_test.assert_almost_equal(se._regionDensity.mean, seg_cmn.image_ar_inset_1.mean()) np_test.assert_almost_equal(new_se.regionDensity.mean, seg_cmn.image_ar_inset_1.mean()) np_test.assert_almost_equal(new_se.backgroundDensity.mean, seg_cmn.bkg_density_1[count]) if se._distance is not None: np_test.assert_almost_equal(se._distance.distance[seg.ids], seg_cmn.distance_to_3_min_1[seg.ids]) np_test.assert_almost_equal(new_se.distance.distance[seg.ids], seg_cmn.distance_to_3_min_1[seg.ids]) # test bound distance if (level >= 0) and (level < 2): np_test.assert_equal((se.boundDistance.distance > 0).sum(), 0) elif level == 2: dist = se.boundDistance.distance np_test.assert_equal((dist > 0).sum(), 1) np_test.assert_equal((dist[3:6] == 5).sum(), 1) elif level == 3: dist = se.boundDistance.distance np_test.assert_equal((dist[6:10] == 5).sum(), 2) elif level == 4: np_test.assert_equal((se._boundDistance.distance > 0).sum(), 2) dist = se.boundDistance.distance np_test.assert_equal(dist[10] == 5, True) np_test.assert_equal(dist[11] == 5, True) elif level > 4: dist = se._boundDistance.distance np_test.assert_equal((dist[12:] == 5).sum(), 1) # test contacts if level == 0: np_test.assert_equal(se._nContacts, [[0], [0], [0]]) np_test.assert_equal(se._surfaceDensityContacts, [0, 0, 0]) np_test.assert_equal(se._surfaceDensitySegments, [0, 0, 0]) if level == 1: np_test.assert_equal(se._nContacts, [[2, 1, 1], [2, 1, 1], [0, 0, 0]]) np_test.assert_equal(se._surfaceDensityContacts, [2./16, 2./8, 0]) np_test.assert_equal(se._surfaceDensitySegments, [2./8, 2./8, 2./8]) if level == 2: np_test.assert_equal(se._nContacts, [[4, 0, 0, 1, 2, 1], [2, 0, 0, 1, 1, 0], [2, 0, 0, 0, 1, 1]]) np_test.assert_equal(se._surfaceDensityContacts, [4./16, 2./8, 2./8]) np_test.assert_equal(se._surfaceDensitySegments, [3./8, 3./8, 3./8]) if level == 5: np_test.assert_equal(se._nContacts, [[6, 0,0,0,0,0,0,0,0,0,0,0, 6], [2, 0,0,0,0,0,0,0,0,0,0,0, 2], [4, 0,0,0,0,0,0,0,0,0,0,0, 4]]) np_test.assert_equal(se._surfaceDensityContacts, [6./16, 2./8, 4./8]) np_test.assert_equal(se._surfaceDensitySegments, [1./8, 1./8, 1./8]) # hierarchy tc = tc_iter.send(True) # test hierarchical segmentation converted_ids = [id_dict[id_] for id_ in seg_cmn.ids_1] np_test.assert_equal(tc.levelIds, seg_cmn.levelIds_1) # test analysis of the hierarchy np_test.assert_almost_equal(se.density.mean[tc.ids], seg_cmn.density_1[tc.ids]) np_test.assert_almost_equal(se.regionDensity.mean, seg_cmn.image_ar_inset_1.mean()) np_test.assert_equal(se.morphology.volume[1:], seg_cmn.volume_1[1:]) #print se.morphology.length # test distance to np_test.assert_almost_equal(se.distance.distance[tc.ids], seg_cmn.distance_to_3_min_1[converted_ids]) # test bound distance dist = se.boundDistance.distance np_test.assert_equal((dist == 5).sum(), 8) np_test.assert_equal((dist > 5).sum(), 0) np_test.assert_equal(((dist > 0) & (dist < 5)).sum(), 0) ########################################################## # # Same as above but multi distanceTo # # do tc segmentation and analysis se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=([3], [3,4]), distanceMode=('min', 'mean'), distanceName=('min_3', 'mean_3_4')) tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True) # make and test individual segments id_dict = {} for count in range(len(seg_cmn.threshold_1)): # make level new_se, level, curr_thresh = next(tc_iter) seg = new_se.segments id_dict = seg_cmn.id_correspondence(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1[level], current=id_dict) converted_ids = [id_dict[id_] for id_ in seg_cmn.levelIds_1[level]] # hierarchy tc = tc_iter.send(True) tc.useInset(inset=[slice(2,6), slice(1,9)], mode='abs', useFull=True, expand=True) np_test.assert_equal(tc.data>0, seg_cmn.data_1[-1]>0) converted_ids = [id_dict[id_] for id_ in seg_cmn.ids_1] # test distance to np_test.assert_almost_equal(se.min_3.distance[tc.ids], seg_cmn.distance_to_3_min_1[converted_ids]) np_test.assert_almost_equal(se.mean_3_4.distance[tc.ids], seg_cmn.distance_to_3_4_mean_1[converted_ids]) np_test.assert_almost_equal(se.mean_3_4.closestRegion[tc.ids], seg_cmn.closest_region_1[converted_ids]) ###################################################### # # Image 1, boundary 1, order >, multi distance # # do tc segmentation and analysis se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=([3], [3,4]), distanceMode=('min', 'mean'), distanceName=('min_3', 'mean_3_4')) tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='>', doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True) # make and test individual segments id_dict = {} for count in range(len(seg_cmn.threshold_1)): # make level #print 'Count: ', count new_se, level, curr_thresh = next(tc_iter) seg = new_se.segments # test levels and threshold np_test.assert_equal(level, 0) np_test.assert_equal(curr_thresh, seg_cmn.threshold_1[-count-1]) # test ids id_dict = seg_cmn.id_correspondence(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1[-count-1], current=id_dict) inv_id_dict = dict([(val, key) for key, val in list(id_dict.items())]) converted_ids = [inv_id_dict[id_] for id_ in seg.ids] # test segments try: desired = seg.reorder(data=seg_cmn.data_1[-count-1], order=id_dict) np_test.assert_equal(seg.data[2:6, 1:9], desired) except AssertionError: np_test.assert_equal(seg.data[2:6, 1:9]>0, seg_cmn.data_1[-count-1]>0) if self.reorder_warning: print( "The exact id assignment is different from what it was " + "when this test was written, but this really depends " + "on internals of scipy.ndimage. Considering that the " + "segments are correct, most likely everything is ok.") self.reorder_warning = False np_test.assert_equal( seg.contacts.findSegments(boundaryIds=[3,4], nBoundary=1), seg.ids) # test boundaries bound_found = seg.contacts.findBoundaries(segmentIds=seg.ids, nSegment=1) if len(seg_cmn.threshold_1)-count-1 == 0: np_test.assert_equal(bound_found, []) elif len(seg_cmn.threshold_1)-count-1 == 1: np_test.assert_equal(bound_found, [3]) else: np_test.assert_equal(bound_found, [3,4]) # test segment analysis np_test.assert_almost_equal(se._regionDensity.mean, seg_cmn.image_ar_inset_1.mean()) if se._min_3 is not None: np_test.assert_almost_equal(se._min_3.distance[seg.ids], seg_cmn.distance_to_3_min_1[converted_ids]) np_test.assert_almost_equal(new_se.min_3.distance[seg.ids], seg_cmn.distance_to_3_min_1[converted_ids]) # hierarchy tc = tc_iter.send(True) converted_ids = [id_dict[id_] for id_ in seg_cmn.ids_1] # test analysis of the hierarchy np_test.assert_almost_equal(se.density.mean[converted_ids], seg_cmn.density_1[tc.ids]) np_test.assert_equal(se.morphology.volume[converted_ids], seg_cmn.volume_1[tc.ids]) # test distance to np_test.assert_almost_equal(se.min_3.distance[converted_ids], seg_cmn.distance_to_3_min_1[tc.ids]) np_test.assert_almost_equal(se.mean_3_4.distance[converted_ids], seg_cmn.distance_to_3_4_mean_1[tc.ids]) np_test.assert_almost_equal(se.mean_3_4.closestRegion[converted_ids], seg_cmn.closest_region_1[tc.ids]) def testClassify(self): """ Tests classify and all individual classification methods """ # prepare for tc segmentation se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=[3], distanceMode='min') tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True) # make hierarchy id_dict = {} for count in range(len(seg_cmn.threshold_1)): seg, level, curr_thresh = next(tc_iter) tc = tc_iter.send(True) ####################################################### # # Volume + bound ids # # set classification parameters and desired results se.addClassificationParameters(type='volume', args={'volumes':[0, 10, 50]}) se.addClassificationParameters(type='contacted_ids', args={'ids':[3], 'rest':True}) desired_names = ['_vol-0-10_bound-3', '_vol-0-10_bound-rest', '_vol-10-50_bound-3', '_vol-10-50_bound-rest'] desired_ids = [[1,2,3,4,6,7,10], [5,8,9], [11,12,13,14], []] # classify and test ind = 0 for hi, name in se.classify(hierarchy=tc): np_test.assert_equal(name, desired_names[ind]) np_test.assert_equal(hi.ids, desired_ids[ind]) np_test.assert_equal(hi.contacts.segments, hi.ids) ind += 1 ####################################################### # # Volume + n bound # # make a hierarchy tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True) for count in range(len(seg_cmn.threshold_1)): seg, level, curr_thresh = next(tc_iter) tc = tc_iter.send(True) # set classification parameters and desired results se.removeClassificationParameters() se.addClassificationParameters(type='volume', args={'volumes':[2, 10, 20], 'names':['small', 'big']}) se.addClassificationParameters(type='n_contacted', args={'nContacted':[1,2], 'names':['teth', 'conn']}) desired_names = ['_small_teth', '_small_conn', '_big_teth', '_big_conn'] desired_ids = [[2,3], [4,6,7,10], [], [11,12]] # classify and test ind = 0 for hi, name in se.classify(hierarchy=tc): np_test.assert_equal(name, desired_names[ind]) np_test.assert_equal(hi.ids, desired_ids[ind]) np_test.assert_equal(hi.contacts.segments, hi.ids) ind += 1 ####################################################### # # New + volume + bound ids # # make a hierarchy tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True) for count in range(len(seg_cmn.threshold_1)): seg, level, curr_thresh = next(tc_iter) tc = tc_iter.send(True) # set classification parameters and desired results se.removeClassificationParameters() se.addClassificationParameters(type='keep', args={'mode':'new'}) se.addClassificationParameters(type='volume', args={'volumes':[1, 2, 10], 'names':['tiny', 'small']}) se.addClassificationParameters(type='contacted_ids', args={'ids':[3], 'rest':True, 'names':['con-3', 'rest']}) desired_names = ['_new_tiny_con-3', '_new_tiny_rest', '_new_small_con-3', '_new_small_rest'] desired_ids = [[1], [5,8,9], [2], []] # classify and test ind = 0 for hi, name in se.classify(hierarchy=tc): np_test.assert_equal(name, desired_names[ind]) np_test.assert_equal(hi.ids, desired_ids[ind]) np_test.assert_equal(hi.contacts.segments, hi.ids) ind += 1 def testClassifyAnalyze(self): """ Tests classifyAnalyze() method, and also getLabels() """ # make CleftLayers and set desired cleft contacts cleft_layers = self.makeCleftLayers() desired_n_contacts = [ [[12, 1, 1, 1, 2, 0, 2, 2, 0, 0, 3], [7, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1], [5, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2]], [[3, 0, 0, 0, 0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 1, 1]], [[21, 0,0,0,0,0,0,0,0,0,0, 3, 6, 6, 6], [7, 0,0,0,0,0,0,0,0,0,0, 1, 2, 2, 2], [14, 0,0,0,0,0,0,0,0,0,0, 2, 4, 4, 4]], [[0], [0], [0]]] desired_surface_density_contacts = [ [12/16., 7/8., 5/8.], [3/16., 0, 3/8.], [21/16., 7/8., 14/8.], [0, 0, 0]] desired_surface_density_segments = [ [7/8., 7/8., 7/8.], [3/8., 3/8., 3/8.], [4/8., 4/8., 4/8.], [0, 0, 0]] ######################################################## # # Scenario 1: # - segment and analyze # - classify # prepare for tc segmentation se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=([3], [3,4]), distanceMode=('min', 'mean'), distanceName=('min_3', 'mean_3_4'), cleftLayers=cleft_layers) tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', count=True, doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True, doCleftContacts=True) # make hierarchy id_dict = {} for count in range(len(seg_cmn.threshold_1)): seg, level, curr_thresh = next(tc_iter) tc = tc_iter.send(True) # set classification parameters and desired results se.addClassificationParameters(type='volume', args={'volumes':[0, 10, 50]}) se.addClassificationParameters(type='contacted_ids', args={'ids':[3], 'rest':True}) desired_names = ['_vol-0-10_bound-3', '_vol-0-10_bound-rest', '_vol-10-50_bound-3', '_vol-10-50_bound-rest'] desired_ids = [[1,2,3,4,6,7,10], [5,8,9], [11,12,13,14], []] # classify and test ind = 0 for new, name in se.classifyAnalyze(hierarchy=tc, doDensity=False, doMorphology=False, doLength=False, doTopology=False, doDistanceTo=False, doBoundDistance=True, doCleftContacts=True): # test classification np_test.assert_equal(name, desired_names[ind]) np_test.assert_equal(new.hierarchy.ids, desired_ids[ind]) # test getLabels() np_test.assert_equal(new.labels, new.hierarchy) np_test.assert_equal(new.ids, new.hierarchy.ids) # test analysis np_test.assert_almost_equal( new.morphology.volume[new.morphology.ids], seg_cmn.volume_1[new.hierarchy.ids]) np_test.assert_almost_equal( new.topology.euler[new.topology.ids], seg_cmn.euler_1[new.hierarchy.ids]) np_test.assert_almost_equal( new.topology.nFaces[new.topology.ids], seg_cmn.n_faces_1[new.hierarchy.ids]) np_test.assert_almost_equal(new.density.mean[new.density.ids], seg_cmn.density_1[new.hierarchy.ids]) np_test.assert_almost_equal( new.min_3.distance[new.min_3.ids], seg_cmn.distance_to_3_min_1[new.hierarchy.ids]) np_test.assert_almost_equal( new.mean_3_4.distance[new.mean_3_4.ids], seg_cmn.distance_to_3_4_mean_1[new.hierarchy.ids]) np_test.assert_almost_equal( new.mean_3_4.closestRegion[new.mean_3_4.ids], seg_cmn.closest_region_1[new.hierarchy.ids]) # test cleft contacts np_test.assert_almost_equal(new.nContacts, desired_n_contacts[ind]) np_test.assert_almost_equal(new.surfaceDensityContacts, desired_surface_density_contacts[ind]) np_test.assert_almost_equal(new.surfaceDensitySegments, desired_surface_density_segments[ind]) ind += 1 ###################################################### # # Scenario 2: # - segment wo analysis # - classify and analyze # prepare for tc segmentation se = SegmentationAnalysis(image=seg_cmn.image_1, boundary=seg_cmn.bound_1) se.setSegmentationParameters(boundaryIds=[3, 4], nBoundary=1, boundCount='at_least', mask=5) se.setAnalysisParameters(distanceRegion=seg_cmn.bound_1, distanceId=([3], [3,4]), distanceMode=('min', 'mean'), distanceName=('min_3', 'mean_3_4'), cleftLayers=cleft_layers) tc_iter = se.tcSegmentAnalyze( thresh=seg_cmn.threshold_1, order='<', count=True, doDensity=False, doMorphology=False, doLength=False, doTopology=False, doDistanceTo=False, doBoundDistance=True, doCleftContacts=False) # make hierarchy for count in range(len(seg_cmn.threshold_1)): seg, level, curr_thresh = next(tc_iter) tc = tc_iter.send(True) # set classification parameters and desired results se.addClassificationParameters(type='volume', args={'volumes':[0, 10, 50]}) se.addClassificationParameters(type='contacted_ids', args={'ids':[3], 'rest':True}) desired_names = ['_vol-0-10_bound-3', '_vol-0-10_bound-rest', '_vol-10-50_bound-3', '_vol-10-50_bound-rest'] desired_ids = [[1,2,3,4,6,7,10], [5,8,9], [11,12,13,14], []] # classify and test ind = 0 for new_2, name in se.classifyAnalyze(hierarchy=tc, doDensity=True, doMorphology=True, doLength=True, doTopology=True, doDistanceTo=True, doBoundDistance=True, doCleftContacts=True): # test classification np_test.assert_equal(name, desired_names[ind]) np_test.assert_equal(new_2.hierarchy.ids, desired_ids[ind]) # test analysis np_test.assert_almost_equal( new_2.morphology.volume[new_2.morphology.ids], seg_cmn.volume_1[new_2.hierarchy.ids]) np_test.assert_almost_equal( new_2.topology.euler[new_2.topology.ids], seg_cmn.euler_1[new_2.hierarchy.ids]) if len(new_2.hierarchy.ids) > 0: np_test.assert_almost_equal( new_2.topology.nFaces[new_2.topology.ids,:], seg_cmn.n_faces_1[new_2.hierarchy.ids]) else: np_test.assert_equal(len(new_2.topology.nFaces), 0) np_test.assert_almost_equal( new_2.density.mean[new_2.density.ids], seg_cmn.density_1[new_2.hierarchy.ids]) np_test.assert_almost_equal( new_2.min_3.distance[new_2.min_3.ids], seg_cmn.distance_to_3_min_1[new_2.hierarchy.ids]) np_test.assert_almost_equal( new_2.mean_3_4.distance[new_2.mean_3_4.ids], seg_cmn.distance_to_3_4_mean_1[new_2.hierarchy.ids]) np_test.assert_almost_equal( new_2.mean_3_4.closestRegion[new_2.mean_3_4.ids], seg_cmn.closest_region_1[new_2.hierarchy.ids]) # test cleft contacts np_test.assert_almost_equal(new_2.nContacts, desired_n_contacts[ind]) np_test.assert_almost_equal(new_2.surfaceDensityContacts, desired_surface_density_contacts[ind]) np_test.assert_almost_equal(new_2.surfaceDensitySegments, desired_surface_density_segments[ind]) ind += 1 if __name__ == '__main__': suite = \ unittest.TestLoader().loadTestsFromTestCase(TestSegmentationAnalysis) unittest.TextTestRunner(verbosity=2).run(suite)
[ "unittest.TextTestRunner", "numpy.testing.assert_almost_equal", "pyto.segmentation.test.common.id_correspondence", "pyto.scene.cleft_regions.CleftRegions", "builtins.next", "pyto.segmentation.test.common.image_ar_inset_1.mean", "unittest.TestLoader", "numpy.testing.assert_equal", "pyto.segmentation....
[((1118, 1185), 'pyto.segmentation.cleft.Cleft', 'Cleft', ([], {'data': 'seg_cmn.bound_1.data', 'bound1Id': '(3)', 'bound2Id': '(4)', 'cleftId': '(5)'}), '(data=seg_cmn.bound_1.data, bound1Id=3, bound2Id=4, cleftId=5)\n', (1123, 1185), False, 'from pyto.segmentation.cleft import Cleft\n'), ((1232, 1280), 'pyto.scene.cleft_regions.CleftRegions', 'CleftRegions', ([], {'image': 'seg_cmn.image_1', 'cleft': 'cleft'}), '(image=seg_cmn.image_1, cleft=cleft)\n', (1244, 1280), False, 'from pyto.scene.cleft_regions import CleftRegions\n'), ((1806, 1875), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (1826, 1875), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((9007, 9060), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['tc.levelIds', 'seg_cmn.levelIds_1'], {}), '(tc.levelIds, seg_cmn.levelIds_1)\n', (9027, 9060), True, 'import numpy.testing as np_test\n'), ((9111, 9190), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.density.mean[tc.ids]', 'seg_cmn.density_1[tc.ids]'], {}), '(se.density.mean[tc.ids], seg_cmn.density_1[tc.ids])\n', (9138, 9190), True, 'import numpy.testing as np_test\n'), ((9365, 9433), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se.morphology.volume[1:]', 'seg_cmn.volume_1[1:]'], {}), '(se.morphology.volume[1:], seg_cmn.volume_1[1:])\n', (9385, 9433), True, 'import numpy.testing as np_test\n'), ((9506, 9612), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.distance.distance[tc.ids]', 'seg_cmn.distance_to_3_min_1[converted_ids]'], {}), '(se.distance.distance[tc.ids], seg_cmn.\n distance_to_3_min_1[converted_ids])\n', (9533, 9612), True, 'import numpy.testing as np_test\n'), ((10073, 10142), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (10093, 10142), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((11387, 11444), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['(tc.data > 0)', '(seg_cmn.data_1[-1] > 0)'], {}), '(tc.data > 0, seg_cmn.data_1[-1] > 0)\n', (11407, 11444), True, 'import numpy.testing as np_test\n'), ((11541, 11644), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.min_3.distance[tc.ids]', 'seg_cmn.distance_to_3_min_1[converted_ids]'], {}), '(se.min_3.distance[tc.ids], seg_cmn.\n distance_to_3_min_1[converted_ids])\n', (11568, 11644), True, 'import numpy.testing as np_test\n'), ((11685, 11794), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.mean_3_4.distance[tc.ids]', 'seg_cmn.distance_to_3_4_mean_1[converted_ids]'], {}), '(se.mean_3_4.distance[tc.ids], seg_cmn.\n distance_to_3_4_mean_1[converted_ids])\n', (11712, 11794), True, 'import numpy.testing as np_test\n'), ((11833, 11941), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.mean_3_4.closestRegion[tc.ids]', 'seg_cmn.closest_region_1[converted_ids]'], {}), '(se.mean_3_4.closestRegion[tc.ids], seg_cmn.\n closest_region_1[converted_ids])\n', (11860, 11941), True, 'import numpy.testing as np_test\n'), ((12177, 12246), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (12197, 12246), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((15775, 15866), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.density.mean[converted_ids]', 'seg_cmn.density_1[tc.ids]'], {}), '(se.density.mean[converted_ids], seg_cmn.\n density_1[tc.ids])\n', (15802, 15866), True, 'import numpy.testing as np_test\n'), ((15907, 15995), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se.morphology.volume[converted_ids]', 'seg_cmn.volume_1[tc.ids]'], {}), '(se.morphology.volume[converted_ids], seg_cmn.volume_1[\n tc.ids])\n', (15927, 15995), True, 'import numpy.testing as np_test\n'), ((16057, 16160), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.min_3.distance[converted_ids]', 'seg_cmn.distance_to_3_min_1[tc.ids]'], {}), '(se.min_3.distance[converted_ids], seg_cmn.\n distance_to_3_min_1[tc.ids])\n', (16084, 16160), True, 'import numpy.testing as np_test\n'), ((16201, 16310), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.mean_3_4.distance[converted_ids]', 'seg_cmn.distance_to_3_4_mean_1[tc.ids]'], {}), '(se.mean_3_4.distance[converted_ids], seg_cmn.\n distance_to_3_4_mean_1[tc.ids])\n', (16228, 16310), True, 'import numpy.testing as np_test\n'), ((16349, 16456), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se.mean_3_4.closestRegion[converted_ids]', 'seg_cmn.closest_region_1[tc.ids]'], {}), '(se.mean_3_4.closestRegion[converted_ids],\n seg_cmn.closest_region_1[tc.ids])\n', (16376, 16456), True, 'import numpy.testing as np_test\n'), ((16659, 16728), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (16679, 16728), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((22659, 22728), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (22679, 22728), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((26536, 26605), 'pyto.scene.segmentation_analysis.SegmentationAnalysis', 'SegmentationAnalysis', ([], {'image': 'seg_cmn.image_1', 'boundary': 'seg_cmn.bound_1'}), '(image=seg_cmn.image_1, boundary=seg_cmn.bound_1)\n', (26556, 26605), False, 'from pyto.scene.segmentation_analysis import SegmentationAnalysis\n'), ((2690, 2703), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (2694, 2703), False, 'from builtins import next\n'), ((2781, 2833), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.nBoundary', 'se.nBoundary'], {}), '(new_se.nBoundary, se.nBoundary)\n', (2801, 2833), True, 'import numpy.testing as np_test\n'), ((2846, 2900), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.boundCount', 'se.boundCount'], {}), '(new_se.boundCount, se.boundCount)\n', (2866, 2900), True, 'import numpy.testing as np_test\n'), ((2913, 2971), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.structElConn', 'se.structElConn'], {}), '(new_se.structElConn, se.structElConn)\n', (2933, 2971), True, 'import numpy.testing as np_test\n'), ((2984, 3056), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.contactStructElConn', 'se.contactStructElConn'], {}), '(new_se.contactStructElConn, se.contactStructElConn)\n', (3004, 3056), True, 'import numpy.testing as np_test\n'), ((3103, 3171), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.countStructElConn', 'se.countStructElConn'], {}), '(new_se.countStructElConn, se.countStructElConn)\n', (3123, 3171), True, 'import numpy.testing as np_test\n'), ((3184, 3244), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.lengthContact', 'se.lengthContact'], {}), '(new_se.lengthContact, se.lengthContact)\n', (3204, 3244), True, 'import numpy.testing as np_test\n'), ((3257, 3311), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.lengthLine', 'se.lengthLine'], {}), '(new_se.lengthLine, se.lengthLine)\n', (3277, 3311), True, 'import numpy.testing as np_test\n'), ((3365, 3399), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['level', 'count'], {}), '(level, count)\n', (3385, 3399), True, 'import numpy.testing as np_test\n'), ((3412, 3473), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['curr_thresh', 'seg_cmn.threshold_1[level]'], {}), '(curr_thresh, seg_cmn.threshold_1[level])\n', (3432, 3473), True, 'import numpy.testing as np_test\n'), ((3518, 3570), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.labels', 'new_se.segments'], {}), '(new_se.labels, new_se.segments)\n', (3538, 3570), True, 'import numpy.testing as np_test\n'), ((3583, 3636), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_se.ids', 'new_se.segments.ids'], {}), '(new_se.ids, new_se.segments.ids)\n', (3603, 3636), True, 'import numpy.testing as np_test\n'), ((3683, 3788), 'pyto.segmentation.test.common.id_correspondence', 'seg_cmn.id_correspondence', ([], {'actual': 'seg.data[2:6, 1:9]', 'desired': 'seg_cmn.data_1[level]', 'current': 'id_dict'}), '(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1\n [level], current=id_dict)\n', (3708, 3788), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((3975, 4019), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['seg.ids', 'converted_ids'], {}), '(seg.ids, converted_ids)\n', (3995, 4019), True, 'import numpy.testing as np_test\n'), ((5645, 5738), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_se.backgroundDensity.mean', 'seg_cmn.bkg_density_1[count]'], {}), '(new_se.backgroundDensity.mean, seg_cmn.\n bkg_density_1[count])\n', (5672, 5738), True, 'import numpy.testing as np_test\n'), ((9324, 9355), 'pyto.segmentation.test.common.image_ar_inset_1.mean', 'seg_cmn.image_ar_inset_1.mean', ([], {}), '()\n', (9353, 9355), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((10933, 10946), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (10937, 10946), False, 'from builtins import next\n'), ((11004, 11109), 'pyto.segmentation.test.common.id_correspondence', 'seg_cmn.id_correspondence', ([], {'actual': 'seg.data[2:6, 1:9]', 'desired': 'seg_cmn.data_1[level]', 'current': 'id_dict'}), '(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1\n [level], current=id_dict)\n', (11029, 11109), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((13073, 13086), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (13077, 13086), False, 'from builtins import next\n'), ((13174, 13204), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['level', '(0)'], {}), '(level, 0)\n', (13194, 13204), True, 'import numpy.testing as np_test\n'), ((13217, 13283), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['curr_thresh', 'seg_cmn.threshold_1[-count - 1]'], {}), '(curr_thresh, seg_cmn.threshold_1[-count - 1])\n', (13237, 13283), True, 'import numpy.testing as np_test\n'), ((13328, 13438), 'pyto.segmentation.test.common.id_correspondence', 'seg_cmn.id_correspondence', ([], {'actual': 'seg.data[2:6, 1:9]', 'desired': 'seg_cmn.data_1[-count - 1]', 'current': 'id_dict'}), '(actual=seg.data[2:6, 1:9], desired=seg_cmn.data_1\n [-count - 1], current=id_dict)\n', (13353, 13438), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((17401, 17414), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (17405, 17414), False, 'from builtins import next\n'), ((18199, 18245), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['name', 'desired_names[ind]'], {}), '(name, desired_names[ind])\n', (18219, 18245), True, 'import numpy.testing as np_test\n'), ((18258, 18304), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.ids', 'desired_ids[ind]'], {}), '(hi.ids, desired_ids[ind])\n', (18278, 18304), True, 'import numpy.testing as np_test\n'), ((18317, 18367), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.contacts.segments', 'hi.ids'], {}), '(hi.contacts.segments, hi.ids)\n', (18337, 18367), True, 'import numpy.testing as np_test\n'), ((18845, 18858), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (18849, 18858), False, 'from builtins import next\n'), ((19661, 19707), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['name', 'desired_names[ind]'], {}), '(name, desired_names[ind])\n', (19681, 19707), True, 'import numpy.testing as np_test\n'), ((19720, 19766), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.ids', 'desired_ids[ind]'], {}), '(hi.ids, desired_ids[ind])\n', (19740, 19766), True, 'import numpy.testing as np_test\n'), ((19779, 19829), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.contacts.segments', 'hi.ids'], {}), '(hi.contacts.segments, hi.ids)\n', (19799, 19829), True, 'import numpy.testing as np_test\n'), ((20315, 20328), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (20319, 20328), False, 'from builtins import next\n'), ((21222, 21268), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['name', 'desired_names[ind]'], {}), '(name, desired_names[ind])\n', (21242, 21268), True, 'import numpy.testing as np_test\n'), ((21281, 21327), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.ids', 'desired_ids[ind]'], {}), '(hi.ids, desired_ids[ind])\n', (21301, 21327), True, 'import numpy.testing as np_test\n'), ((21340, 21390), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['hi.contacts.segments', 'hi.ids'], {}), '(hi.contacts.segments, hi.ids)\n', (21360, 21390), True, 'import numpy.testing as np_test\n'), ((23564, 23577), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (23568, 23577), False, 'from builtins import next\n'), ((24466, 24512), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['name', 'desired_names[ind]'], {}), '(name, desired_names[ind])\n', (24486, 24512), True, 'import numpy.testing as np_test\n'), ((24525, 24582), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new.hierarchy.ids', 'desired_ids[ind]'], {}), '(new.hierarchy.ids, desired_ids[ind])\n', (24545, 24582), True, 'import numpy.testing as np_test\n'), ((24635, 24682), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new.labels', 'new.hierarchy'], {}), '(new.labels, new.hierarchy)\n', (24655, 24682), True, 'import numpy.testing as np_test\n'), ((24695, 24743), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new.ids', 'new.hierarchy.ids'], {}), '(new.ids, new.hierarchy.ids)\n', (24715, 24743), True, 'import numpy.testing as np_test\n'), ((24793, 24904), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.morphology.volume[new.morphology.ids]', 'seg_cmn.volume_1[new.hierarchy.ids]'], {}), '(new.morphology.volume[new.morphology.ids],\n seg_cmn.volume_1[new.hierarchy.ids])\n', (24820, 24904), True, 'import numpy.testing as np_test\n'), ((24947, 25053), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.topology.euler[new.topology.ids]', 'seg_cmn.euler_1[new.hierarchy.ids]'], {}), '(new.topology.euler[new.topology.ids], seg_cmn.\n euler_1[new.hierarchy.ids])\n', (24974, 25053), True, 'import numpy.testing as np_test\n'), ((25095, 25204), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.topology.nFaces[new.topology.ids]', 'seg_cmn.n_faces_1[new.hierarchy.ids]'], {}), '(new.topology.nFaces[new.topology.ids], seg_cmn.\n n_faces_1[new.hierarchy.ids])\n', (25122, 25204), True, 'import numpy.testing as np_test\n'), ((25246, 25351), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.density.mean[new.density.ids]', 'seg_cmn.density_1[new.hierarchy.ids]'], {}), '(new.density.mean[new.density.ids], seg_cmn.\n density_1[new.hierarchy.ids])\n', (25273, 25351), True, 'import numpy.testing as np_test\n'), ((25400, 25515), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.min_3.distance[new.min_3.ids]', 'seg_cmn.distance_to_3_min_1[new.hierarchy.ids]'], {}), '(new.min_3.distance[new.min_3.ids], seg_cmn.\n distance_to_3_min_1[new.hierarchy.ids])\n', (25427, 25515), True, 'import numpy.testing as np_test\n'), ((25557, 25680), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.mean_3_4.distance[new.mean_3_4.ids]', 'seg_cmn.distance_to_3_4_mean_1[new.hierarchy.ids]'], {}), '(new.mean_3_4.distance[new.mean_3_4.ids],\n seg_cmn.distance_to_3_4_mean_1[new.hierarchy.ids])\n', (25584, 25680), True, 'import numpy.testing as np_test\n'), ((25723, 25845), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.mean_3_4.closestRegion[new.mean_3_4.ids]', 'seg_cmn.closest_region_1[new.hierarchy.ids]'], {}), '(new.mean_3_4.closestRegion[new.mean_3_4.ids],\n seg_cmn.closest_region_1[new.hierarchy.ids])\n', (25750, 25845), True, 'import numpy.testing as np_test\n'), ((25931, 25998), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.nContacts', 'desired_n_contacts[ind]'], {}), '(new.nContacts, desired_n_contacts[ind])\n', (25958, 25998), True, 'import numpy.testing as np_test\n'), ((26011, 26109), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.surfaceDensityContacts', 'desired_surface_density_contacts[ind]'], {}), '(new.surfaceDensityContacts,\n desired_surface_density_contacts[ind])\n', (26038, 26109), True, 'import numpy.testing as np_test\n'), ((26159, 26257), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new.surfaceDensitySegments', 'desired_surface_density_segments[ind]'], {}), '(new.surfaceDensitySegments,\n desired_surface_density_segments[ind])\n', (26186, 26257), True, 'import numpy.testing as np_test\n'), ((27426, 27439), 'builtins.next', 'next', (['tc_iter'], {}), '(tc_iter)\n', (27430, 27439), False, 'from builtins import next\n'), ((28313, 28359), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['name', 'desired_names[ind]'], {}), '(name, desired_names[ind])\n', (28333, 28359), True, 'import numpy.testing as np_test\n'), ((28372, 28431), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['new_2.hierarchy.ids', 'desired_ids[ind]'], {}), '(new_2.hierarchy.ids, desired_ids[ind])\n', (28392, 28431), True, 'import numpy.testing as np_test\n'), ((28473, 28590), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.morphology.volume[new_2.morphology.ids]', 'seg_cmn.volume_1[new_2.hierarchy.ids]'], {}), '(new_2.morphology.volume[new_2.morphology.ids],\n seg_cmn.volume_1[new_2.hierarchy.ids])\n', (28500, 28590), True, 'import numpy.testing as np_test\n'), ((28633, 28744), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.topology.euler[new_2.topology.ids]', 'seg_cmn.euler_1[new_2.hierarchy.ids]'], {}), '(new_2.topology.euler[new_2.topology.ids],\n seg_cmn.euler_1[new_2.hierarchy.ids])\n', (28660, 28744), True, 'import numpy.testing as np_test\n'), ((29105, 29216), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.density.mean[new_2.density.ids]', 'seg_cmn.density_1[new_2.hierarchy.ids]'], {}), '(new_2.density.mean[new_2.density.ids], seg_cmn.\n density_1[new_2.hierarchy.ids])\n', (29132, 29216), True, 'import numpy.testing as np_test\n'), ((29258, 29379), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.min_3.distance[new_2.min_3.ids]', 'seg_cmn.distance_to_3_min_1[new_2.hierarchy.ids]'], {}), '(new_2.min_3.distance[new_2.min_3.ids], seg_cmn.\n distance_to_3_min_1[new_2.hierarchy.ids])\n', (29285, 29379), True, 'import numpy.testing as np_test\n'), ((29421, 29550), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.mean_3_4.distance[new_2.mean_3_4.ids]', 'seg_cmn.distance_to_3_4_mean_1[new_2.hierarchy.ids]'], {}), '(new_2.mean_3_4.distance[new_2.mean_3_4.ids],\n seg_cmn.distance_to_3_4_mean_1[new_2.hierarchy.ids])\n', (29448, 29550), True, 'import numpy.testing as np_test\n'), ((29593, 29722), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.mean_3_4.closestRegion[new_2.mean_3_4.ids]', 'seg_cmn.closest_region_1[new_2.hierarchy.ids]'], {}), '(new_2.mean_3_4.closestRegion[new_2.mean_3_4.ids\n ], seg_cmn.closest_region_1[new_2.hierarchy.ids])\n', (29620, 29722), True, 'import numpy.testing as np_test\n'), ((29799, 29868), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.nContacts', 'desired_n_contacts[ind]'], {}), '(new_2.nContacts, desired_n_contacts[ind])\n', (29826, 29868), True, 'import numpy.testing as np_test\n'), ((29922, 30022), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.surfaceDensityContacts', 'desired_surface_density_contacts[ind]'], {}), '(new_2.surfaceDensityContacts,\n desired_surface_density_contacts[ind])\n', (29949, 30022), True, 'import numpy.testing as np_test\n'), ((30072, 30172), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.surfaceDensitySegments', 'desired_surface_density_segments[ind]'], {}), '(new_2.surfaceDensitySegments,\n desired_surface_density_segments[ind])\n', (30099, 30172), True, 'import numpy.testing as np_test\n'), ((30284, 30305), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (30303, 30305), False, 'import unittest\n'), ((30358, 30394), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (30381, 30394), False, 'import unittest\n'), ((4083, 4146), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['seg.data[2:6, 1:9]', 'seg_cmn.data_1[level]'], {}), '(seg.data[2:6, 1:9], seg_cmn.data_1[level])\n', (4103, 4146), True, 'import numpy.testing as np_test\n'), ((5108, 5145), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[]'], {}), '(bound_found, [])\n', (5128, 5145), True, 'import numpy.testing as np_test\n'), ((5459, 5490), 'pyto.segmentation.test.common.image_ar_inset_1.mean', 'seg_cmn.image_ar_inset_1.mean', ([], {}), '()\n', (5488, 5490), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((5600, 5631), 'pyto.segmentation.test.common.image_ar_inset_1.mean', 'seg_cmn.image_ar_inset_1.mean', ([], {}), '()\n', (5629, 5631), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((5832, 5934), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se._distance.distance[seg.ids]', 'seg_cmn.distance_to_3_min_1[seg.ids]'], {}), '(se._distance.distance[seg.ids], seg_cmn.\n distance_to_3_min_1[seg.ids])\n', (5859, 5934), True, 'import numpy.testing as np_test\n'), ((5988, 6093), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_se.distance.distance[seg.ids]', 'seg_cmn.distance_to_3_min_1[seg.ids]'], {}), '(new_se.distance.distance[seg.ids], seg_cmn.\n distance_to_3_min_1[seg.ids])\n', (6015, 6093), True, 'import numpy.testing as np_test\n'), ((7121, 7173), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._nContacts', '[[0], [0], [0]]'], {}), '(se._nContacts, [[0], [0], [0]])\n', (7141, 7173), True, 'import numpy.testing as np_test\n'), ((7190, 7249), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensityContacts', '[0, 0, 0]'], {}), '(se._surfaceDensityContacts, [0, 0, 0])\n', (7210, 7249), True, 'import numpy.testing as np_test\n'), ((7266, 7325), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensitySegments', '[0, 0, 0]'], {}), '(se._surfaceDensitySegments, [0, 0, 0])\n', (7286, 7325), True, 'import numpy.testing as np_test\n'), ((7369, 7439), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._nContacts', '[[2, 1, 1], [2, 1, 1], [0, 0, 0]]'], {}), '(se._nContacts, [[2, 1, 1], [2, 1, 1], [0, 0, 0]])\n', (7389, 7439), True, 'import numpy.testing as np_test\n'), ((7571, 7643), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensityContacts', '[2.0 / 16, 2.0 / 8, 0]'], {}), '(se._surfaceDensityContacts, [2.0 / 16, 2.0 / 8, 0])\n', (7591, 7643), True, 'import numpy.testing as np_test\n'), ((7692, 7769), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensitySegments', '[2.0 / 8, 2.0 / 8, 2.0 / 8]'], {}), '(se._surfaceDensitySegments, [2.0 / 8, 2.0 / 8, 2.0 / 8])\n', (7712, 7769), True, 'import numpy.testing as np_test\n'), ((7842, 7943), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._nContacts', '[[4, 0, 0, 1, 2, 1], [2, 0, 0, 1, 1, 0], [2, 0, 0, 0, 1, 1]]'], {}), '(se._nContacts, [[4, 0, 0, 1, 2, 1], [2, 0, 0, 1, 1, 0],\n [2, 0, 0, 0, 1, 1]])\n', (7862, 7943), True, 'import numpy.testing as np_test\n'), ((8071, 8149), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensityContacts', '[4.0 / 16, 2.0 / 8, 2.0 / 8]'], {}), '(se._surfaceDensityContacts, [4.0 / 16, 2.0 / 8, 2.0 / 8])\n', (8091, 8149), True, 'import numpy.testing as np_test\n'), ((8195, 8272), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensitySegments', '[3.0 / 8, 3.0 / 8, 3.0 / 8]'], {}), '(se._surfaceDensitySegments, [3.0 / 8, 3.0 / 8, 3.0 / 8])\n', (8215, 8272), True, 'import numpy.testing as np_test\n'), ((8345, 8514), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._nContacts', '[[6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 2], [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4]]'], {}), '(se._nContacts, [[6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6\n ], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [4, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 4]])\n', (8365, 8514), True, 'import numpy.testing as np_test\n'), ((8608, 8686), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensityContacts', '[6.0 / 16, 2.0 / 8, 4.0 / 8]'], {}), '(se._surfaceDensityContacts, [6.0 / 16, 2.0 / 8, 4.0 / 8])\n', (8628, 8686), True, 'import numpy.testing as np_test\n'), ((8732, 8809), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['se._surfaceDensitySegments', '[1.0 / 8, 1.0 / 8, 1.0 / 8]'], {}), '(se._surfaceDensitySegments, [1.0 / 8, 1.0 / 8, 1.0 / 8])\n', (8752, 8809), True, 'import numpy.testing as np_test\n'), ((13826, 13875), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['seg.data[2:6, 1:9]', 'desired'], {}), '(seg.data[2:6, 1:9], desired)\n', (13846, 13875), True, 'import numpy.testing as np_test\n'), ((14849, 14886), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[]'], {}), '(bound_found, [])\n', (14869, 14886), True, 'import numpy.testing as np_test\n'), ((15227, 15258), 'pyto.segmentation.test.common.image_ar_inset_1.mean', 'seg_cmn.image_ar_inset_1.mean', ([], {}), '()\n', (15256, 15258), True, 'import pyto.segmentation.test.common as seg_cmn\n'), ((15314, 15419), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['se._min_3.distance[seg.ids]', 'seg_cmn.distance_to_3_min_1[converted_ids]'], {}), '(se._min_3.distance[seg.ids], seg_cmn.\n distance_to_3_min_1[converted_ids])\n', (15341, 15419), True, 'import numpy.testing as np_test\n'), ((15467, 15575), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_se.min_3.distance[seg.ids]', 'seg_cmn.distance_to_3_min_1[converted_ids]'], {}), '(new_se.min_3.distance[seg.ids], seg_cmn.\n distance_to_3_min_1[converted_ids])\n', (15494, 15575), True, 'import numpy.testing as np_test\n'), ((28852, 28969), 'numpy.testing.assert_almost_equal', 'np_test.assert_almost_equal', (['new_2.topology.nFaces[new_2.topology.ids, :]', 'seg_cmn.n_faces_1[new_2.hierarchy.ids]'], {}), '(new_2.topology.nFaces[new_2.topology.ids, :],\n seg_cmn.n_faces_1[new_2.hierarchy.ids])\n', (28879, 28969), True, 'import numpy.testing as np_test\n'), ((4198, 4269), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['(seg.data[2:6, 1:9] > 0)', '(seg_cmn.data_1[level] > 0)'], {}), '(seg.data[2:6, 1:9] > 0, seg_cmn.data_1[level] > 0)\n', (4218, 4269), True, 'import numpy.testing as np_test\n'), ((5191, 5229), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[3]'], {}), '(bound_found, [3])\n', (5211, 5229), True, 'import numpy.testing as np_test\n'), ((5264, 5305), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[3, 4]'], {}), '(bound_found, [3, 4])\n', (5284, 5305), True, 'import numpy.testing as np_test\n'), ((13927, 14003), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['(seg.data[2:6, 1:9] > 0)', '(seg_cmn.data_1[-count - 1] > 0)'], {}), '(seg.data[2:6, 1:9] > 0, seg_cmn.data_1[-count - 1] > 0)\n', (13947, 14003), True, 'import numpy.testing as np_test\n'), ((14959, 14997), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[3]'], {}), '(bound_found, [3])\n', (14979, 14997), True, 'import numpy.testing as np_test\n'), ((15032, 15073), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['bound_found', '[3, 4]'], {}), '(bound_found, [3, 4])\n', (15052, 15073), True, 'import numpy.testing as np_test\n'), ((6806, 6847), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['(dist[10] == 5)', '(True)'], {}), '(dist[10] == 5, True)\n', (6826, 6847), True, 'import numpy.testing as np_test\n'), ((6864, 6905), 'numpy.testing.assert_equal', 'np_test.assert_equal', (['(dist[11] == 5)', '(True)'], {}), '(dist[11] == 5, True)\n', (6884, 6905), True, 'import numpy.testing as np_test\n')]
import pdb import time import os import subprocess import re import random import json import numpy as np import glob from tensorboard.backend.event_processing.event_accumulator import EventAccumulator import socket import argparse import threading import _thread import signal from datetime import datetime import csv parser = argparse.ArgumentParser(description='TCP client') parser.add_argument('--tc', metavar='TESTCASE', type=str, help='select testcase') args = parser.parse_args() with open('../job_trace/job_queue_50.json', 'r') as fp: #TODO queue = json.load(fp) queue_dict = {} arrival_time = 0 for item in queue: arrival_time += np.random.poisson(30) queue_dict[item] = arrival_time queue_timer = time.time() queue_delay = {} for item in queue: queue_delay[str(item)] = 0 multigpu_list = ['1', '2', '3']#, '4', '5', '6', '7'] #TODO job_start = {} #{'49': time1, '15': time2...} JCT = {} for item in queue: JCT[str(item)] = 0 completion = {} for item in queue: completion[str(item)] = 0 overhead = {} # initialize so that every job starts with 0s overhead time for item in queue: overhead[str(item)] = 0 ovhd_start = {} # initialize this to 0 as well for item in queue: ovhd_start[str(item)] = 0 b_start = {} # initialize this to 0 as well for item in queue: b_start[str(item)] = 0 c_start = {} # initialize this to 0 as well for item in queue: c_start[str(item)] = 0 d_start = {} # initialize this to 0 as well for item in queue: d_start[str(item)] = 0 ovhd_a = {} # {1: [10, 12, ...], 2: [xx]} for item in queue: ovhd_a[str(item)] = [] ovhd_b = {} # {1: [10, 12, ...], 2: [xx]} for item in queue: ovhd_b[str(item)] = [] ovhd_c = {} # {1: [10, 12, ...], 2: [xx]} for item in queue: ovhd_c[str(item)] = [] ovhd_d = {} # {1: [10, 12, ...], 2: [xx]} for item in queue: ovhd_d[str(item)] = [] ovhd_total = {} # {1: [10, 12, ...], 2: [xx]} for item in queue: ovhd_total[str(item)] = [] k80_1st = {} for item in queue: k80_1st[str(item)] = [] v100_1st = {} for item in queue: v100_1st[str(item)] = [] num_mig = {} # initialize migration time to 0 for item in queue: num_mig[str(item)] = 0 queue_start = {} # initialize this to 0 as well for item in queue: queue_start[str(item)] = 0 queue_time = {} # initialize this to 0 as well for item in queue: queue_time[str(item)] = 0 K80_start_time = {} for item in queue: K80_start_time[str(item)] = 0 V100_start_time = {} for item in queue: V100_start_time[str(item)] = 0 K80_time = {} for item in queue: K80_time[str(item)] = 0 V100_time = {} for item in queue: V100_time[str(item)] = 0 gpu_usage_time = [] # don't initialize this gpu_usage = [] gpu_usage_completion = [] index = 0 K80_cap = 8 #TODO V100_cap = 4 K80_used = 0 V100_used = 0 K80_per_node = 8 V100_per_node = 4 K80_job = {} for i in range(K80_cap): K80_job[str(i)] = 'idle' V100_job = {} for i in range(V100_cap): V100_job[str(i)] = 'idle' qualified_job = [] pc_job = [] K80_node = ['c2177']#, 'c2182'] V100_node = ['d1006']#, 'd1015'] host_node = 'c0147' testcase = args.tc ### also, change .h5 file folder in jobs ### INTERVAL = 30 # make decision every 30s # function to detect if there are two free or reserved GPUs in a node # returns an empty list if there is none, otherwise returns list with gpu id in V100/K80_jobs def detect_2_gpus(gpu_dict, gpu_per_node, status='idle'): job_list = list(gpu_dict.values()) num_nodes = int(len(job_list) / gpu_per_node) for i in range(num_nodes): start = i * gpu_per_node end = start + gpu_per_node sliced_list = job_list[start:end] occurence = sliced_list.count(status) if occurence >= 2: # only take the first two elements indexs = [j for j, e in enumerate(sliced_list) if e == status] return [str(j + start) for j in indexs] return [] def K80_LUT(gpu): quotient = int(gpu) // 8 remainder = int(gpu) % 8 real_node = K80_node[quotient] real_gpu = str(remainder) return real_node, real_gpu def V100_LUT(gpu): quotient = int(gpu) // 4 remainder = int(gpu) % 4 real_node = V100_node[quotient] real_gpu = str(remainder) return real_node, real_gpu def send_signal(node, cmd): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 10000 # Connect the socket to the port where the server is listening server_address = (node, int(port)) print('connecting to {} port {}'.format(*server_address)) sock.connect(server_address) try: # Send data message = cmd.encode('utf-8') #b'save 35' #b'start 35 gpu 6'#b'save 35' print('sending {!r}'.format(message)) sock.sendall(message) while True: data = sock.recv(32) if 'success' in data.decode('utf-8'): # print('received {!r}'.format(data)) break else: print('waiting for success signal') time.sleep(1) finally: #print('closing socket') sock.close() def get_avail_id(gpu_dict): # input is K80_job or V100_job (dict) key_list = list(gpu_dict.keys()) value_list = list(gpu_dict.values()) indexs = [j for j, e in enumerate(value_list) if e == 'reserved' or e == 'idle'] return [key_list[j] for j in indexs] # 2-gpu jobs in new_pool have duplicated items # returns mapping def K80_placement(K80_avail, new_pool): mapping = {} skip = False res_group = [] # group reserved GPU together for i in range(len(K80_avail)): if skip: skip = False continue else: # two gpus from the same node if i!=len(K80_avail)-1 and int(K80_avail[i])//K80_per_node==int(K80_avail[i+1])//K80_per_node: skip = True res_group.append([K80_avail[i], K80_avail[i+1]]) else: res_group.append([K80_avail[i]]) group_1gpu = [i for i in res_group if len(i) == 1] # 1gpu id group_2gpu = [i for i in res_group if len(i) == 2] # 2gpu id pool_1gpu = [i for i in new_pool if i not in multigpu_list] # 1gpu job pool_2gpu = [i for i in new_pool if i in multigpu_list] # 2gpu job if len(K80_avail) < len(new_pool) or 2*len(group_2gpu) < len(pool_2gpu): raise ValueError('Bug with K80 placement for new jobs, more jobs than free gpus') # if there is no 2-gpu job if set(new_pool).isdisjoint(multigpu_list): for i in range(len(new_pool)): mapping[new_pool[i]] = K80_avail[i] else: # first, fill in all 1gpu slots with 1-gpu jobs as much as possible for i in group_1gpu[:]: if len(pool_1gpu) > 0: mapping[pool_1gpu[0]] = i[0] pool_1gpu.pop(0) for i in group_2gpu[:]: if len(pool_2gpu) > 1: mapping[pool_2gpu[0]] = ','.join(i) pool_2gpu = [i for i in pool_2gpu if i != pool_2gpu[0]] elif len(pool_1gpu) > 0: mapping[pool_1gpu[0]] = i[0] if len(pool_1gpu) > 1: mapping[pool_1gpu[1]] = i[1] pool_1gpu.pop(1) pool_1gpu.pop(0) return mapping #aa = K80_placement(['0','1','2','3','4'], ['3','3','1','1','50']) # jobs in K80 and in new pool compete for reserved V100 spots by random chance # for 2-gpu jobs, the job will have duplicated entry in new_pool and promote_list # V100_avail is a list with gpuid that is reserved or idle # random promo does not have job demotion # 1st return: list of job that starts on V100. 2nd return: list of job that promotes to V100 # 3rd return: dict of mapping {'50':'5', '3':'1,2'} means job50 runs on gpuid 5, job3 runs on gpuid 1,2 def random_promotion(V100_avail, new_pool, promote_list): V100_pool = new_pool + promote_list mapping = {} ####### this is only used in specific cases ########## # group two gpus in same node together # [1,2,3,5,8] -> [[1,2],[3],[5,8]] skip = False res_group = [] # group reserved GPU together for i in range(len(V100_avail)): if skip: skip = False continue else: # two gpus from the same node if i!=len(V100_avail)-1 and int(V100_avail[i])//V100_per_node==int(V100_avail[i+1])//V100_per_node: skip = True res_group.append([V100_avail[i], V100_avail[i+1]]) else: res_group.append([V100_avail[i]]) group_1gpu = [i for i in res_group if len(i) == 1] # 1gpu id group_2gpu = [i for i in res_group if len(i) == 2] # 2gpu id pool_1gpu = [i for i in V100_pool if i not in multigpu_list] # 1gpu job pool_2gpu = [i for i in V100_pool if i in multigpu_list] # 2gpu job ######################################################## if len(V100_avail) >= len(V100_pool) and 2*len(group_2gpu) >= len(pool_2gpu): # this means all jobs get to run on V100 sorted_pool = V100_pool # if there is no 2-gpu job if set(V100_pool).isdisjoint(multigpu_list): for i in range(len(sorted_pool)): mapping[sorted_pool[i]] = V100_avail[i] # there are 2-gpu jobs else: # first, fill in all 1gpu slots with 1-gpu jobs as much as possible for i in group_1gpu[:]: if len(pool_1gpu) > 0: mapping[pool_1gpu[0]] = i[0] pool_1gpu.pop(0) for i in group_2gpu[:]: if len(pool_2gpu) > 1: mapping[pool_2gpu[0]] = ','.join(i) pool_2gpu = [i for i in pool_2gpu if i != pool_2gpu[0]] elif len(pool_1gpu) > 0: mapping[pool_1gpu[0]] = i[0] if len(pool_1gpu) > 1: mapping[pool_1gpu[1]] = i[1] pool_1gpu.pop(1) pool_1gpu.pop(0) else: # if there are no 2-gpu jobs at all if set(V100_pool).isdisjoint(multigpu_list): sorted_pool = random.sample(V100_pool, len(V100_avail)) for i in range(len(sorted_pool)): mapping[sorted_pool[i]] = V100_avail[i] # if there are 2-gpu jobs but no reserved spots for it elif len(group_2gpu) == 0: # remove 2-gpu jobs from V100_pool V100_pool = [i for i in V100_pool if i not in multigpu_list] num_sample = min(len(V100_avail), len(V100_pool)) # in case jobs are less than slots after reduction sorted_pool = random.sample(V100_pool, num_sample) for i in range(len(sorted_pool)): mapping[sorted_pool[i]] = V100_avail[i] # if there are 2-gpu jobs with available spots else: print('there are 2-gpu jobs with available 2-gpu slots') print('V100 pool:', V100_pool) sorted_pool = [] for i in group_1gpu[:]: if len(pool_1gpu) > 0: picked = random.choice(pool_1gpu) sorted_pool.append(picked) pool_1gpu.remove(picked) V100_pool.remove(picked) mapping[picked] = i[0] for i in group_2gpu[:]: picked = random.choice(V100_pool) if picked in pool_2gpu: sorted_pool.append(picked) sorted_pool.append(picked) V100_pool = [i for i in V100_pool if i != picked] pool_2gpu = [i for i in pool_2gpu if i != picked] mapping[picked] = ','.join(i) else: # pick another 1-gpu job to fill in the 2-gpu slot sorted_pool.append(picked) pool_1gpu.remove(picked) V100_pool.remove(picked) mapping[picked] = i[0] picked_2 = random.choice(pool_1gpu) sorted_pool.append(picked_2) pool_1gpu.remove(picked_2) V100_pool.remove(picked_2) mapping[picked_2] = i[1] print('picked jobs:', sorted_pool) start_list = list(set(sorted_pool).intersection(new_pool)) promo_list = list(set(sorted_pool).intersection(promote_list)) return start_list, promo_list, mapping #d, e, f = random_promotion(['0','1','4','8'], ['3','3','1','1'], []) def save_job(node, job): # save_job('c2176', '50') # first wait for the job to be qualified for checkpointing while True: # wait for ckpt_qual to be available global ckpt_qual_dict if ckpt_qual_dict['job'+job] == 1: ckpt_qual_dict['job'+job] = 0 break time.sleep(5) global pid_dict pid = pid_dict['job'+job] send_signal(node, 'save ' + job + ' pid ' + pid) # 'save 50 pid 10000' global ovhd_start ovhd_start[job] = time.time() time.sleep(3) # in case epoch_waste is communicate too frequently # resume job def resume_job(node, gpu, job): # resume_job('c2176', '3', '50') cmd = 'resume ' + job + ' gpu ' + gpu send_signal(node, cmd) # start job def start_job(node, gpu, job): cmd = 'start ' + job + ' gpu ' + gpu send_signal(node, cmd) ############### first clear finish status of all jobs #################### pid_dict = {} for i in range(len(queue)): job_name = 'job' + str(i + 1) pid_dict[job_name] = 0 checkpoint_dict = {} for i in range(len(queue)): job_name = 'job' + str(i + 1) checkpoint_dict[job_name] = 0 ckpt_qual_dict = {} for i in range(len(queue)): job_name = 'job' + str(i + 1) ckpt_qual_dict[job_name] = 0 finish_dict = {} for i in range(len(queue)): job_name = 'job' + str(i + 1) finish_dict[job_name] = 0 epoch_waste_dict = {} for i in range(len(queue)): job_name = 'job' + str(i + 1) epoch_waste_dict[job_name] = 0 #################### background thread running TCP socket ######################## def thread_function(): # here listen on the socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host_node, 10002) print('starting up on {} port {}'.format(*server_address)) sock.bind(server_address) sock.listen(5) while True: # Wait for a connection connection, client_address = sock.accept() try: while True: data = connection.recv(32) if data: data_str = data.decode('utf-8') global K80_start_time global V100_start_time global K80_job global V100_job global K80_time global V100_time global ovhd_a, ovhd_b, ovhd_c, ovhd_d, k80_1st, v100_1st, ovhd_start, overhead, ovhd_total global b_start, c_start, d_start, completion if 'ckpt_qual' in data_str: global ckpt_qual_dict job_name = data_str.split(' ')[0] ckpt_qual_dict[job_name] = 1 elif 'finish' in data_str: global finish_dict job_name = data_str.split(' ')[0] job = job_name.replace('job','') finish_dict[job_name] = 1 JCT[job] = int(time.time() - job_start[job]) if job in list(K80_job.values()): K80_time[job] += int(time.time() - K80_start_time[job]) elif job in list(V100_job.values()): V100_time[job] += int(time.time() - V100_start_time[job]) elif 'pid' in data_str: global pid_dict job_name = data_str.split(' ')[0] pid = data_str.split(' ')[2] pid_dict[job_name] = pid elif 'checkpoint' in data_str: # can only be received after save signal is sent global checkpoint_dict job_name = data_str.split(' ')[0] job = job_name.replace('job','') checkpoint_dict[job_name] = 1 ovhd_a[job].append(int(time.time() - ovhd_start[job])) b_start[job] = time.time() elif 'waste' in data_str: global epoch_waste_dict job_name = data_str.split(' ')[0] epoch_waste_time = data_str.split(' ')[2] epoch_waste_dict[job_name] += int(epoch_waste_time) elif 'b_end' in data_str: job_name = data_str.split(' ')[0] job = job_name.replace('job','') ovhd_b[job].append(int(time.time() - b_start[job])) c_start[job] = time.time() elif 'c_end' in data_str: job_name = data_str.split(' ')[0] job = job_name.replace('job','') ovhd_c[job].append(int(time.time() - c_start[job])) d_start[job] = time.time() elif 'd_end' in data_str: job_name = data_str.split(' ')[0] job = job_name.replace('job','') ovhd_d[job].append(int(time.time() - d_start[job])) ovhd_total[job].append(int(time.time() - ovhd_start[job])) if ovhd_start[job] != 0: overhead[job] += int(time.time() - ovhd_start[job]) ovhd_start[job] = 0 if job in list(K80_job.values()): K80_start_time[job] = time.time() elif job in list(V100_job.values()): V100_start_time[job] = time.time() elif '1st_epoch' in data_str: # 'job50 1st_epoch 35' job_name = data_str.split(' ')[0] job = job_name.replace('job','') epoch_time = int(data_str.split(' ')[2]) if job in list(K80_job.values()): k80_1st[job].append(epoch_time) elif job in list(V100_job.values()): v100_1st[job].append(epoch_time) elif 'completion' in data_str: # 'job50 completion 0.33' job_name = data_str.split(' ')[0] job = job_name.replace('job','') completion_portion = float(data_str.split(' ')[2]) completion[job] = completion_portion # if 'ckpt_qual' in data_str or 'finish' in data_str or 'checkpoint' in data_str: # print('received ' + data_str) connection.sendall(b'success') #time.sleep(5) else: break finally: connection.close() x = threading.Thread(target=thread_function, daemon=True) x.start() ############################################################################### ###################################################################### while True: # termination condition: # all the jobs have finished ################### check for finished jobs on K80 and V100 ############################## for gpu, job in K80_job.items(): if job != 'idle': if finish_dict['job'+job] == 1: K80_used -= 1 K80_job[gpu] = 'idle' print('K80 finished job: ' + job) for gpu, job in V100_job.items(): if job != 'idle': if finish_dict['job'+job] == 1: V100_used -= 1 V100_job[gpu] = 'idle' print('V100 finished job: ' + job) ################ ################ submit new jobs to vacant K80 GPUs ############################ # check if there are vacant K80s ## yes: submit jobs from queue ## no: do nothing # here, just check how many new jobs can get started on idle GPUs and put them in new_pool[]. # But do not allocate any GPU for the jobs yet. new_pool = [] if V100_used < V100_cap: V100_free = V100_cap - V100_used for i in range(V100_free): time_passed = int(time.time() - queue_timer) if index < len(queue) and queue_dict[queue[index]] < time_passed: # make sure job has arrived in the queue job_new = str(queue[index]) if job_new in multigpu_list: idle_gpus = detect_2_gpus(V100_job, V100_per_node)[:2] if len(idle_gpus) > 0: index += 1 qualified_job.append(job_new) # new_pool will have duplicated job for 2-gpu ones for gpu in idle_gpus: new_pool.append(job_new) V100_job[gpu] = 'reserved' V100_used += 1 else: for gpu, job in V100_job.items(): if job == 'idle': # schedule new job here if idle new_pool.append(job_new) qualified_job.append(job_new) V100_job[gpu] = 'reserved' index += 1 V100_used += 1 break if K80_used < K80_cap: K80_free = K80_cap - K80_used for i in range(K80_free): time_passed = int(time.time() - queue_timer) if index < len(queue) and queue_dict[queue[index]] < time_passed: # make sure job has arrived in the queue job_new = str(queue[index]) if job_new in multigpu_list: idle_gpus = detect_2_gpus(K80_job, K80_per_node)[:2] if len(idle_gpus) > 0: index += 1 qualified_job.append(job_new) for gpu in idle_gpus: new_pool.append(job_new) K80_job[gpu] = 'reserved' K80_used += 1 else: for gpu, job in K80_job.items(): if job == 'idle': # schedule new job here if idle new_pool.append(job_new) qualified_job.append(job_new) K80_job[gpu] = 'reserved' index += 1 K80_used += 1 break # make promotion decisions V100_avail = get_avail_id(V100_job) promote_list = [i for i in list(K80_job.values()) if i in qualified_job] if len(promote_list) > 0 or len(new_pool) > 0: # started and promoted do not have duplicated elements started, promoted, mapping = random_promotion(V100_avail, new_pool, promote_list) if len(started) > 0: print('jobs starting on V100: ', started) if len(promoted) > 0: print('promoted jobs: ', promoted) # stop all promoted jobs on K80 checkpoint_finish_check = [] for job in promoted[:]: if job not in multigpu_list: # need to find its current gpu on K80 current_gpu = '' for gpu, job_K in K80_job.items(): if job_K == job: current_gpu = gpu break real_node, real_gpu = K80_LUT(current_gpu) K80_job[current_gpu] = 'idle' K80_used -= 1 else: current_gpu = [] for gpu, job_K in K80_job.items(): if job_K == job: current_gpu.append(gpu) real_node, real_gpu = K80_LUT(current_gpu[0]) for item in current_gpu: K80_job[item] = 'idle' K80_used -= 1 save_job(real_node, job) if finish_dict['job'+job] != 1: K80_time[job] += int(time.time() - K80_start_time[job]) checkpoint_finish_check.append(job) # wait for all GPUs to be available if len(checkpoint_finish_check) > 0: while True: time.sleep(5) for job in checkpoint_finish_check[:]: if checkpoint_dict['job'+job] == 1: # checkpoint has finished, gpu is free print(job + ' checkpointed successfully') checkpoint_dict['job'+job] = 0 # reset it checkpoint_finish_check.remove(job) # also check if job already finished before sending checkpoint signal elif finish_dict['job'+job] == 1: print(job + ' finished before receiving checkpoint signal') checkpoint_finish_check.remove(job) if len(checkpoint_finish_check) == 0: break # give it some time to cleanup old checkpointed jobs time.sleep(3) # 1. deal with all V100 jobs (started, promoted). The job-gpu mapping is already known for job in started[:]: # new jobs gpu = mapping[job] if job not in multigpu_list: real_node, real_gpu = V100_LUT(gpu) start_job(real_node, real_gpu, job) V100_job[gpu] = job job_start[job] = time.time() queue_delay[job] = int(time.time() - queue_timer - queue_dict[int(job)]) V100_start_time[job] = time.time() new_pool.remove(job) else: gpu_split = gpu.split(',') node_string = '' for g in gpu_split: real_node, real_gpu = V100_LUT(g) if g == gpu_split[1]: gpu_str += real_gpu node_string = real_node job_start[job] = time.time() queue_delay[job] = int(time.time() - queue_timer - queue_dict[int(job)]) V100_start_time[job] = time.time() else: gpu_str = real_gpu + ',' V100_job[g] = job new_pool.remove(job) start_job(node_string, gpu_str, job) started.remove(job) # resume promoted jobs for job in promoted[:]: if finish_dict['job'+job] != 1: gpu = mapping[job] if job not in multigpu_list: real_node, real_gpu = V100_LUT(gpu) resume_job(real_node, real_gpu, job) V100_job[gpu] = job V100_used += 1 else: gpu_split = gpu.split(',') node_string = '' for g in gpu_split: real_node, real_gpu = V100_LUT(g) if g == gpu_split[1]: gpu_str += real_gpu node_string = real_node else: gpu_str = real_gpu + ',' V100_job[g] = job V100_used += 1 resume_job(node_string, gpu_str, job) promoted.remove(job) num_mig[job] += 1 else: # job finished before checkpointing promoted.remove(job) # 2. find all mapping of remaining new jobs (current new_pool list) that are going to start on K80 # first make sure there are remaining new jobs if len(new_pool) > 0: K80_avail = get_avail_id(K80_job) K_mapping = K80_placement(K80_avail, new_pool) remain_pool = list(set(new_pool).intersection(new_pool)) # just to get rid of duplicated 2-gpu job items for job in remain_pool[:]: # new jobs gpu = K_mapping[job] if job not in multigpu_list: real_node, real_gpu = K80_LUT(gpu) start_job(real_node, real_gpu, job) K80_job[gpu] = job job_start[job] = time.time() queue_delay[job] = int(time.time() - queue_timer - queue_dict[int(job)]) K80_start_time[job] = time.time() new_pool.remove(job) else: gpu_split = gpu.split(',') node_string = '' for g in gpu_split: real_node, real_gpu = K80_LUT(g) if g == gpu_split[1]: gpu_str += real_gpu node_string = real_node job_start[job] = time.time() queue_delay[job] = int(time.time() - queue_timer - queue_dict[int(job)]) K80_start_time[job] = time.time() else: gpu_str = real_gpu + ',' K80_job[g] = job new_pool.remove(job) start_job(node_string, gpu_str, job) # 3. change 'reserved' status to 'idle' if there are any for key, value in K80_job.items(): if value == 'reserved': K80_job[key] = 'idle' for key, value in V100_job.items(): if value == 'reserved': V100_job[key] = 'idle' # perform a check, make sure all promoted/demoted jobs are scheduled if len(promoted) > 0 or len(new_pool) > 0: raise ValueError('Bug with promotion scheme, more jobs than free gpus') ############## monitor GPU usage ############ usage = K80_used + V100_used time_stamp = int(time.time() - queue_timer) gpu_usage_time.append(time_stamp) gpu_usage.append(usage) total_completion = np.sum(list(completion.values())) gpu_usage_completion.append(total_completion) ############### wait for next iteration time.sleep(INTERVAL) ################ check if termination condition is met ################ K80_idle_num = sum(value == 'idle' for value in K80_job.values()) V100_idle_num = sum(value == 'idle' for value in V100_job.values()) if K80_idle_num == K80_cap and V100_idle_num == V100_cap and index == len(queue): print('all jobs are finished!') break # get average JCT average_JCT = np.average(list(JCT.values())) JCT['average'] = average_JCT average_overhead = np.average(list(overhead.values())) overhead['average'] = average_overhead average_queue_delay = np.average(list(queue_delay.values())) queue_delay['average'] = average_queue_delay # after everything is finished print('finished all runs') JCT_name = testcase + '_JCT.json' overhead_name = testcase + '_overhead.json' num_mig_name = testcase + '_num_mig.json' epoch_waste_name = testcase + '_epoch_waste.json' ckpt_qual_name = 'ckpt_qual.json' finish_name = 'finish.json' K80_time_name = testcase + '_K80_time.json' V100_time_name = testcase + '_V100_time.json' gpu_usage_name = testcase + '_gpu_usage.csv' completion_name = 'completion.json' ovhd_a_name = testcase + '_ovhd_a.json' ovhd_b_name = testcase + '_ovhd_b.json' ovhd_c_name = testcase + '_ovhd_c.json' ovhd_d_name = testcase + '_ovhd_d.json' ovhd_total_name = testcase + '_ovhd_total.json' k80_1st_name = testcase + '_k80_1st.json' v100_1st_name = testcase + '_v100_1st.json' queue_delay_name = testcase + '_queue_delay.json' with open(JCT_name, 'w') as fp1: json.dump(JCT, fp1, sort_keys=True, indent=4) with open(overhead_name, 'w') as fp3: json.dump(overhead, fp3, sort_keys=True, indent=4) with open(num_mig_name, 'w') as fp3: json.dump(num_mig, fp3, sort_keys=True, indent=4) with open(epoch_waste_name, 'w') as fp3: json.dump(epoch_waste_dict, fp3, sort_keys=True, indent=4) with open(ckpt_qual_name, 'w') as fp1: json.dump(ckpt_qual_dict, fp1, sort_keys=True, indent=4) with open(finish_name, 'w') as fp1: json.dump(finish_dict, fp1, sort_keys=True, indent=4) with open(K80_time_name, 'w') as fp3: json.dump(K80_time, fp3, sort_keys=True, indent=4) with open(V100_time_name, 'w') as fp3: json.dump(V100_time, fp3, sort_keys=True, indent=4) with open(ovhd_a_name, 'w') as fp3: json.dump(ovhd_a, fp3, sort_keys=True, indent=4) with open(ovhd_b_name, 'w') as fp3: json.dump(ovhd_b, fp3, sort_keys=True, indent=4) with open(ovhd_c_name, 'w') as fp3: json.dump(ovhd_c, fp3, sort_keys=True, indent=4) with open(ovhd_d_name, 'w') as fp3: json.dump(ovhd_d, fp3, sort_keys=True, indent=4) with open(ovhd_total_name, 'w') as fp3: json.dump(ovhd_total, fp3, sort_keys=True, indent=4) with open(k80_1st_name, 'w') as fp3: json.dump(k80_1st, fp3, sort_keys=True, indent=4) with open(v100_1st_name, 'w') as fp3: json.dump(v100_1st, fp3, sort_keys=True, indent=4) with open(completion_name, 'w') as fp1: json.dump(completion, fp1, sort_keys=True, indent=4) with open(queue_delay_name, 'w') as fp1: json.dump(queue_delay, fp1, sort_keys=True, indent=4) gpu_usage_time = np.asarray(gpu_usage_time) gpu_usage = np.asarray(gpu_usage) gpu_usage_completion = np.asarray(gpu_usage_completion) rows = zip(gpu_usage_time, gpu_usage, gpu_usage_completion) with open(gpu_usage_name, 'w') as f: writer = csv.writer(f) for row in rows: writer.writerow(row)
[ "threading.Thread", "json.dump", "json.load", "argparse.ArgumentParser", "csv.writer", "random.sample", "numpy.asarray", "socket.socket", "random.choice", "time.time", "time.sleep", "numpy.random.poisson" ]
[((329, 378), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""TCP client"""'}), "(description='TCP client')\n", (352, 378), False, 'import argparse\n'), ((722, 733), 'time.time', 'time.time', ([], {}), '()\n', (731, 733), False, 'import time\n'), ((19384, 19437), 'threading.Thread', 'threading.Thread', ([], {'target': 'thread_function', 'daemon': '(True)'}), '(target=thread_function, daemon=True)\n', (19400, 19437), False, 'import threading\n'), ((33826, 33852), 'numpy.asarray', 'np.asarray', (['gpu_usage_time'], {}), '(gpu_usage_time)\n', (33836, 33852), True, 'import numpy as np\n'), ((33865, 33886), 'numpy.asarray', 'np.asarray', (['gpu_usage'], {}), '(gpu_usage)\n', (33875, 33886), True, 'import numpy as np\n'), ((33910, 33942), 'numpy.asarray', 'np.asarray', (['gpu_usage_completion'], {}), '(gpu_usage_completion)\n', (33920, 33942), True, 'import numpy as np\n'), ((563, 576), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (572, 576), False, 'import json\n'), ((650, 671), 'numpy.random.poisson', 'np.random.poisson', (['(30)'], {}), '(30)\n', (667, 671), True, 'import numpy as np\n'), ((4327, 4376), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (4340, 4376), False, 'import socket\n'), ((13047, 13058), 'time.time', 'time.time', ([], {}), '()\n', (13056, 13058), False, 'import time\n'), ((13064, 13077), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (13074, 13077), False, 'import time\n'), ((14188, 14237), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (14201, 14237), False, 'import socket\n'), ((30739, 30759), 'time.sleep', 'time.sleep', (['INTERVAL'], {}), '(INTERVAL)\n', (30749, 30759), False, 'import time\n'), ((32261, 32306), 'json.dump', 'json.dump', (['JCT', 'fp1'], {'sort_keys': '(True)', 'indent': '(4)'}), '(JCT, fp1, sort_keys=True, indent=4)\n', (32270, 32306), False, 'import json\n'), ((32349, 32399), 'json.dump', 'json.dump', (['overhead', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(overhead, fp3, sort_keys=True, indent=4)\n', (32358, 32399), False, 'import json\n'), ((32441, 32490), 'json.dump', 'json.dump', (['num_mig', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(num_mig, fp3, sort_keys=True, indent=4)\n', (32450, 32490), False, 'import json\n'), ((32536, 32594), 'json.dump', 'json.dump', (['epoch_waste_dict', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(epoch_waste_dict, fp3, sort_keys=True, indent=4)\n', (32545, 32594), False, 'import json\n'), ((32638, 32694), 'json.dump', 'json.dump', (['ckpt_qual_dict', 'fp1'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ckpt_qual_dict, fp1, sort_keys=True, indent=4)\n', (32647, 32694), False, 'import json\n'), ((32735, 32788), 'json.dump', 'json.dump', (['finish_dict', 'fp1'], {'sort_keys': '(True)', 'indent': '(4)'}), '(finish_dict, fp1, sort_keys=True, indent=4)\n', (32744, 32788), False, 'import json\n'), ((32831, 32881), 'json.dump', 'json.dump', (['K80_time', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(K80_time, fp3, sort_keys=True, indent=4)\n', (32840, 32881), False, 'import json\n'), ((32925, 32976), 'json.dump', 'json.dump', (['V100_time', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(V100_time, fp3, sort_keys=True, indent=4)\n', (32934, 32976), False, 'import json\n'), ((33017, 33065), 'json.dump', 'json.dump', (['ovhd_a', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ovhd_a, fp3, sort_keys=True, indent=4)\n', (33026, 33065), False, 'import json\n'), ((33106, 33154), 'json.dump', 'json.dump', (['ovhd_b', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ovhd_b, fp3, sort_keys=True, indent=4)\n', (33115, 33154), False, 'import json\n'), ((33195, 33243), 'json.dump', 'json.dump', (['ovhd_c', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ovhd_c, fp3, sort_keys=True, indent=4)\n', (33204, 33243), False, 'import json\n'), ((33284, 33332), 'json.dump', 'json.dump', (['ovhd_d', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ovhd_d, fp3, sort_keys=True, indent=4)\n', (33293, 33332), False, 'import json\n'), ((33377, 33429), 'json.dump', 'json.dump', (['ovhd_total', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(ovhd_total, fp3, sort_keys=True, indent=4)\n', (33386, 33429), False, 'import json\n'), ((33471, 33520), 'json.dump', 'json.dump', (['k80_1st', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(k80_1st, fp3, sort_keys=True, indent=4)\n', (33480, 33520), False, 'import json\n'), ((33563, 33613), 'json.dump', 'json.dump', (['v100_1st', 'fp3'], {'sort_keys': '(True)', 'indent': '(4)'}), '(v100_1st, fp3, sort_keys=True, indent=4)\n', (33572, 33613), False, 'import json\n'), ((33657, 33709), 'json.dump', 'json.dump', (['completion', 'fp1'], {'sort_keys': '(True)', 'indent': '(4)'}), '(completion, fp1, sort_keys=True, indent=4)\n', (33666, 33709), False, 'import json\n'), ((33754, 33807), 'json.dump', 'json.dump', (['queue_delay', 'fp1'], {'sort_keys': '(True)', 'indent': '(4)'}), '(queue_delay, fp1, sort_keys=True, indent=4)\n', (33763, 33807), False, 'import json\n'), ((34053, 34066), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (34063, 34066), False, 'import csv\n'), ((12858, 12871), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (12868, 12871), False, 'import time\n'), ((25649, 25662), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (25659, 25662), False, 'import time\n'), ((30489, 30500), 'time.time', 'time.time', ([], {}), '()\n', (30498, 30500), False, 'import time\n'), ((5050, 5063), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (5060, 5063), False, 'import time\n'), ((10673, 10709), 'random.sample', 'random.sample', (['V100_pool', 'num_sample'], {}), '(V100_pool, num_sample)\n', (10686, 10709), False, 'import random\n'), ((24856, 24869), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (24866, 24869), False, 'import time\n'), ((26047, 26058), 'time.time', 'time.time', ([], {}), '()\n', (26056, 26058), False, 'import time\n'), ((26187, 26198), 'time.time', 'time.time', ([], {}), '()\n', (26196, 26198), False, 'import time\n'), ((11392, 11416), 'random.choice', 'random.choice', (['V100_pool'], {}), '(V100_pool)\n', (11405, 11416), False, 'import random\n'), ((20766, 20777), 'time.time', 'time.time', ([], {}), '()\n', (20775, 20777), False, 'import time\n'), ((22045, 22056), 'time.time', 'time.time', ([], {}), '()\n', (22054, 22056), False, 'import time\n'), ((28873, 28884), 'time.time', 'time.time', ([], {}), '()\n', (28882, 28884), False, 'import time\n'), ((29020, 29031), 'time.time', 'time.time', ([], {}), '()\n', (29029, 29031), False, 'import time\n'), ((11126, 11150), 'random.choice', 'random.choice', (['pool_1gpu'], {}), '(pool_1gpu)\n', (11139, 11150), False, 'import random\n'), ((12045, 12069), 'random.choice', 'random.choice', (['pool_1gpu'], {}), '(pool_1gpu)\n', (12058, 12069), False, 'import random\n'), ((24643, 24654), 'time.time', 'time.time', ([], {}), '()\n', (24652, 24654), False, 'import time\n'), ((26595, 26606), 'time.time', 'time.time', ([], {}), '()\n', (26604, 26606), False, 'import time\n'), ((26751, 26762), 'time.time', 'time.time', ([], {}), '()\n', (26760, 26762), False, 'import time\n'), ((26098, 26109), 'time.time', 'time.time', ([], {}), '()\n', (26107, 26109), False, 'import time\n'), ((29467, 29478), 'time.time', 'time.time', ([], {}), '()\n', (29476, 29478), False, 'import time\n'), ((29630, 29641), 'time.time', 'time.time', ([], {}), '()\n', (29639, 29641), False, 'import time\n'), ((28928, 28939), 'time.time', 'time.time', ([], {}), '()\n', (28937, 28939), False, 'import time\n'), ((15559, 15570), 'time.time', 'time.time', ([], {}), '()\n', (15568, 15570), False, 'import time\n'), ((16580, 16591), 'time.time', 'time.time', ([], {}), '()\n', (16589, 16591), False, 'import time\n'), ((26654, 26665), 'time.time', 'time.time', ([], {}), '()\n', (26663, 26665), False, 'import time\n'), ((15696, 15707), 'time.time', 'time.time', ([], {}), '()\n', (15705, 15707), False, 'import time\n'), ((29530, 29541), 'time.time', 'time.time', ([], {}), '()\n', (29539, 29541), False, 'import time\n'), ((15842, 15853), 'time.time', 'time.time', ([], {}), '()\n', (15851, 15853), False, 'import time\n'), ((17162, 17173), 'time.time', 'time.time', ([], {}), '()\n', (17171, 17173), False, 'import time\n'), ((16509, 16520), 'time.time', 'time.time', ([], {}), '()\n', (16518, 16520), False, 'import time\n'), ((17450, 17461), 'time.time', 'time.time', ([], {}), '()\n', (17459, 17461), False, 'import time\n'), ((17094, 17105), 'time.time', 'time.time', ([], {}), '()\n', (17103, 17105), False, 'import time\n'), ((17382, 17393), 'time.time', 'time.time', ([], {}), '()\n', (17391, 17393), False, 'import time\n'), ((18076, 18087), 'time.time', 'time.time', ([], {}), '()\n', (18085, 18087), False, 'import time\n'), ((17670, 17681), 'time.time', 'time.time', ([], {}), '()\n', (17679, 17681), False, 'import time\n'), ((17750, 17761), 'time.time', 'time.time', ([], {}), '()\n', (17759, 17761), False, 'import time\n'), ((17880, 17891), 'time.time', 'time.time', ([], {}), '()\n', (17889, 17891), False, 'import time\n'), ((18208, 18219), 'time.time', 'time.time', ([], {}), '()\n', (18217, 18219), False, 'import time\n')]
import numpy as np import math def sample_top(a=[], top_k=10): idx = np.argsort(a)[::-1] idx = idx[:top_k] probs = a[idx] probs = probs / np.sum(probs) choice = np.random.choice(idx, p=probs) return choice # fajie def sample_top_k(a=[], top_k=10): idx = np.argsort(a)[::-1] idx = idx[:top_k] # probs = a[idx] # probs = probs / np.sum(probs) # choice = np.random.choice(idx, p=probs) return idx print("print in utils", sample_top_k(np.array([0.02,0.01,0.01,0.16,0.8]),3)) def cau_recall_mrr_org(preds, labels): recall5, recall20 = [], [] mrr5, mrr20 = [], [] ndcg5, ndcg20 = [], [] rank_l = [] batch_predict=[] for batch, b_label in zip(preds, labels): batch_predict.append(np.argmax(batch)) ranks = (batch[b_label] < batch).sum() + 1 # 比label对应的值大的有多少个 rank_l.append(ranks) # if ranks == 1: # f = open('prestosee.txt', "w") # f.write("min pres="+str(min(batch))+'\n') # f.write("max pres="+str(max(batch))+'\n') # f.write("batch[label]="+str(batch[b_label])+'\n') # for p in batch: # f.write(str(p)+'\n') recall5.append(ranks <= 5) recall20.append(ranks <= 20) mrr5.append(1 / ranks if ranks <= 5 else 0.0) mrr20.append(1 / ranks if ranks <= 20 else 0.0) ndcg5.append(1/math.log(ranks + 1, 2) if ranks <= 5 else 0.0) ndcg20.append(1/math.log(ranks + 1, 2) if ranks <= 20 else 0.0) return rank_l, batch_predict, recall5, recall20, mrr5, mrr20, ndcg5, ndcg20
[ "numpy.sum", "numpy.argmax", "numpy.argsort", "numpy.array", "numpy.random.choice", "math.log" ]
[((182, 212), 'numpy.random.choice', 'np.random.choice', (['idx'], {'p': 'probs'}), '(idx, p=probs)\n', (198, 212), True, 'import numpy as np\n'), ((74, 87), 'numpy.argsort', 'np.argsort', (['a'], {}), '(a)\n', (84, 87), True, 'import numpy as np\n'), ((155, 168), 'numpy.sum', 'np.sum', (['probs'], {}), '(probs)\n', (161, 168), True, 'import numpy as np\n'), ((284, 297), 'numpy.argsort', 'np.argsort', (['a'], {}), '(a)\n', (294, 297), True, 'import numpy as np\n'), ((482, 521), 'numpy.array', 'np.array', (['[0.02, 0.01, 0.01, 0.16, 0.8]'], {}), '([0.02, 0.01, 0.01, 0.16, 0.8])\n', (490, 521), True, 'import numpy as np\n'), ((759, 775), 'numpy.argmax', 'np.argmax', (['batch'], {}), '(batch)\n', (768, 775), True, 'import numpy as np\n'), ((1402, 1424), 'math.log', 'math.log', (['(ranks + 1)', '(2)'], {}), '(ranks + 1, 2)\n', (1410, 1424), False, 'import math\n'), ((1473, 1495), 'math.log', 'math.log', (['(ranks + 1)', '(2)'], {}), '(ranks + 1, 2)\n', (1481, 1495), False, 'import math\n')]
from typing import List, Optional, TypeVar import numpy as np import torch import torch.nn as nn from torecsys.inputs.base import BaseInput class MultiIndicesEmbedding(BaseInput): """ Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding. """ MultiIndicesEmbedding = TypeVar('MultiIndicesEmbedding') def __init__(self, embed_size: Optional[int] = None, field_sizes: Optional[List[int]] = None, nn_embedding: Optional[nn.Parameter] = None, device: str = 'cpu', flatten: Optional[bool] = False, **kwargs): """ Initialize MultiIndicesEmbedding. Args: embed_size (int): size of embedding tensor. Defaults to None field_sizes (List[int]): list of inputs fields' sizes. Defaults to None nn_embedding (nn.Parameter, optional): pretrained embedding values. Defaults to None device (str): device of torch. Defaults to cpu flatten (bool, optional): whether outputs is reshape to (B, 1, N * E) or not before return. Defaults to False Attributes: length (int): size of embedding tensor multiply by number of fields if flatten is True, else Size of embedding tensor embedding (torch.nn.Module): embedding layer flatten (bool): flag to show outputs will be flatten or not offsets (T): tensor of offsets to adjust values of inputs to fit the indices of embedding tensors """ super().__init__() if nn_embedding is not None: self.embedding = nn.Embedding.from_pretrained(nn_embedding) elif sum(field_sizes) is not None and embed_size is not None: self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs) else: raise ValueError('missing required arguments') self.embedding = self.embedding.to(device) self.offsets = torch.Tensor((0, *np.cumsum(field_sizes)[:-1])).long() self.offsets.names = ('N',) self.offsets = self.offsets.unflatten('N', (('B', 1,), ('N', self.offsets.size('N'),),)) self.offsets = self.offsets.to(device) self.flatten = flatten self.field_size = self.embedding.num_embeddings self.embed_size = self.embedding.embedding_dim self.padding_idx = self.embedding.padding_idx self.length = self.embed_size * len(field_sizes) if self.flatten else self.embed_size def cuda(self, device=None) -> MultiIndicesEmbedding: """ Set MultiIndicesEmbedding to GPU Returns: MultiIndicesEmbedding: self """ super().cuda(device=device) self.offsets = self.offsets.cuda(device) return self def cpu(self) -> MultiIndicesEmbedding: """ Set MultiIndicesEmbedding to CPU Returns: MultiIndicesEmbedding: self """ super().cpu() self.offsets = self.offsets.cpu() return self def forward(self, inputs: torch.Tensor) -> torch.Tensor: """ Forward calculation of MultiIndicesEmbedding Args: inputs (T), shape = (B, N), data_type = torch.long: tensor of indices in inputs fields Returns: T, shape = (B, 1, N * E) | (B, N, E), data_type = torch.float: outputs of MultiIndicesEmbedding """ inputs = inputs + self.offsets outputs = self.embedding(inputs.rename(None)) outputs.names = ('B', 'N', 'E',) if self.flatten: outputs = outputs.flatten(('N', 'E',), 'E').rename(None).unsqueeze(1) outputs.names = ('B', 'N', 'E',) return outputs
[ "typing.TypeVar", "torch.nn.Embedding.from_pretrained", "numpy.cumsum" ]
[((381, 413), 'typing.TypeVar', 'TypeVar', (['"""MultiIndicesEmbedding"""'], {}), "('MultiIndicesEmbedding')\n", (388, 413), False, 'from typing import List, Optional, TypeVar\n'), ((1773, 1815), 'torch.nn.Embedding.from_pretrained', 'nn.Embedding.from_pretrained', (['nn_embedding'], {}), '(nn_embedding)\n', (1801, 1815), True, 'import torch.nn as nn\n'), ((2135, 2157), 'numpy.cumsum', 'np.cumsum', (['field_sizes'], {}), '(field_sizes)\n', (2144, 2157), True, 'import numpy as np\n')]
import torch import pytest import numpy as np @pytest.fixture def random_state(): return np.random.RandomState(None) # (1249563438) def test_complex_fft(random_state): shape, axis = (2, 3, 256, 2, 2), 2 np_x = random_state.randn(*shape) + 1j * random_state.randn(*shape) tr_x = torch.tensor(np.stack([np_x.real, np_x.imag], axis=-1)) np_fft = np.fft.fft(np_x, axis=axis) tr_fft = torch.fft(tr_x.transpose(axis, -2), signal_ndim=1).transpose(axis, -2) assert torch.allclose(tr_fft[..., 0], torch.from_numpy(np_fft.real)) assert torch.allclose(tr_fft[..., 1], torch.from_numpy(np_fft.imag)) def test_hamming_window(random_state=None): from scipy.signal.windows import hamming n_window = 1024 np_window = hamming(n_window, False).astype(np.float64) tr_window = torch.hamming_window(n_window, periodic=True, dtype=torch.float64) assert torch.allclose(tr_window, torch.from_numpy(np_window)) np_window = hamming(n_window, True).astype(np.float64) tr_window = torch.hamming_window(n_window, periodic=False, dtype=torch.float64) assert torch.allclose(tr_window, torch.from_numpy(np_window)) def test_pwelch(random_state): from cplxmodule.utils.spectrum import pwelch from scipy.signal import welch # https://www.mathworks.com/help/signal/ref/pwelch.html#btulskp-6 fs = 1000. tt = np.r_[:5 * fs - 1] / fs shape = 2, len(tt) epsilon = random_state.randn(*shape) + 1j * random_state.randn(*shape) np_x = np.cos(2 * np.pi * 100 * tt)[np.newaxis] + epsilon * 0.01 tr_x = torch.tensor(np.stack([np_x.real, np_x.imag], axis=-1)) tr_x.requires_grad = False tr_window = torch.hamming_window(500, periodic=False, dtype=tr_x.dtype) tr_ff, tr_px = pwelch(tr_x, 1, tr_window, fs=fs, scaling="density", n_overlap=300) np_ff, np_px = welch(np_x, fs=fs, axis=-1, window=tr_window.numpy(), nfft=None, nperseg=None, scaling="density", noverlap=300, detrend=False, return_onesided=False) assert torch.allclose(tr_px, torch.from_numpy(np_px)) assert torch.allclose(tr_ff, torch.from_numpy(np_ff)) tr_ff, tr_px = pwelch(tr_x, 1, tr_window, fs=fs, scaling="spectrum", n_overlap=499) np_ff, np_px = welch(np_x, fs=fs, axis=-1, window=tr_window.numpy(), nfft=None, nperseg=None, scaling="spectrum", noverlap=499, detrend=False, return_onesided=False) assert torch.allclose(tr_px, torch.from_numpy(np_px)) assert torch.allclose(tr_ff, torch.from_numpy(np_ff))
[ "numpy.stack", "numpy.fft.fft", "torch.hamming_window", "scipy.signal.windows.hamming", "numpy.random.RandomState", "cplxmodule.utils.spectrum.pwelch", "numpy.cos", "torch.from_numpy" ]
[((95, 122), 'numpy.random.RandomState', 'np.random.RandomState', (['None'], {}), '(None)\n', (116, 122), True, 'import numpy as np\n'), ((370, 397), 'numpy.fft.fft', 'np.fft.fft', (['np_x'], {'axis': 'axis'}), '(np_x, axis=axis)\n', (380, 397), True, 'import numpy as np\n'), ((841, 907), 'torch.hamming_window', 'torch.hamming_window', (['n_window'], {'periodic': '(True)', 'dtype': 'torch.float64'}), '(n_window, periodic=True, dtype=torch.float64)\n', (861, 907), False, 'import torch\n'), ((1088, 1155), 'torch.hamming_window', 'torch.hamming_window', (['n_window'], {'periodic': '(False)', 'dtype': 'torch.float64'}), '(n_window, periodic=False, dtype=torch.float64)\n', (1108, 1155), False, 'import torch\n'), ((1781, 1840), 'torch.hamming_window', 'torch.hamming_window', (['(500)'], {'periodic': '(False)', 'dtype': 'tr_x.dtype'}), '(500, periodic=False, dtype=tr_x.dtype)\n', (1801, 1840), False, 'import torch\n'), ((1861, 1928), 'cplxmodule.utils.spectrum.pwelch', 'pwelch', (['tr_x', '(1)', 'tr_window'], {'fs': 'fs', 'scaling': '"""density"""', 'n_overlap': '(300)'}), "(tr_x, 1, tr_window, fs=fs, scaling='density', n_overlap=300)\n", (1867, 1928), False, 'from cplxmodule.utils.spectrum import pwelch\n'), ((2311, 2379), 'cplxmodule.utils.spectrum.pwelch', 'pwelch', (['tr_x', '(1)', 'tr_window'], {'fs': 'fs', 'scaling': '"""spectrum"""', 'n_overlap': '(499)'}), "(tr_x, 1, tr_window, fs=fs, scaling='spectrum', n_overlap=499)\n", (2317, 2379), False, 'from cplxmodule.utils.spectrum import pwelch\n'), ((313, 354), 'numpy.stack', 'np.stack', (['[np_x.real, np_x.imag]'], {'axis': '(-1)'}), '([np_x.real, np_x.imag], axis=-1)\n', (321, 354), True, 'import numpy as np\n'), ((548, 577), 'torch.from_numpy', 'torch.from_numpy', (['np_fft.real'], {}), '(np_fft.real)\n', (564, 577), False, 'import torch\n'), ((621, 650), 'torch.from_numpy', 'torch.from_numpy', (['np_fft.imag'], {}), '(np_fft.imag)\n', (637, 650), False, 'import torch\n'), ((983, 1010), 'torch.from_numpy', 'torch.from_numpy', (['np_window'], {}), '(np_window)\n', (999, 1010), False, 'import torch\n'), ((1231, 1258), 'torch.from_numpy', 'torch.from_numpy', (['np_window'], {}), '(np_window)\n', (1247, 1258), False, 'import torch\n'), ((1690, 1731), 'numpy.stack', 'np.stack', (['[np_x.real, np_x.imag]'], {'axis': '(-1)'}), '([np_x.real, np_x.imag], axis=-1)\n', (1698, 1731), True, 'import numpy as np\n'), ((2208, 2231), 'torch.from_numpy', 'torch.from_numpy', (['np_px'], {}), '(np_px)\n', (2224, 2231), False, 'import torch\n'), ((2266, 2289), 'torch.from_numpy', 'torch.from_numpy', (['np_ff'], {}), '(np_ff)\n', (2282, 2289), False, 'import torch\n'), ((2660, 2683), 'torch.from_numpy', 'torch.from_numpy', (['np_px'], {}), '(np_px)\n', (2676, 2683), False, 'import torch\n'), ((2718, 2741), 'torch.from_numpy', 'torch.from_numpy', (['np_ff'], {}), '(np_ff)\n', (2734, 2741), False, 'import torch\n'), ((781, 805), 'scipy.signal.windows.hamming', 'hamming', (['n_window', '(False)'], {}), '(n_window, False)\n', (788, 805), False, 'from scipy.signal.windows import hamming\n'), ((1029, 1052), 'scipy.signal.windows.hamming', 'hamming', (['n_window', '(True)'], {}), '(n_window, True)\n', (1036, 1052), False, 'from scipy.signal.windows import hamming\n'), ((1607, 1635), 'numpy.cos', 'np.cos', (['(2 * np.pi * 100 * tt)'], {}), '(2 * np.pi * 100 * tt)\n', (1613, 1635), True, 'import numpy as np\n')]
#!/usr/bin/env python3 """ knn_sklearn.py Performs K nearest neighbors on some given data. Uses sklearn's KNN. Author: <NAME> """ def _main(args): import numpy as np from sklearn.neighbors import KNeighborsClassifier # Load dataset from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() # Proccess dataset x_train = np.reshape(x_train,(60000,784)) x_test = np.reshape(x_test,(10000,784)) print("Reshaped x data into {}".format(x_train.shape)) # TODO: Create KNeighorsClassifier with neighbors 3, and n_jobs=-1 knn = KNeighborsClassifier(n_neighbors=3,n_jobs=-1) # Train with data. print("Begin fitting...") # TODO: Fit the data # Hint: knn.fit knn.fit(x_train, y_train) print("Classifier fitted.") # Evaluate on testing data. print("Begin predicting.") # TODO: Evaluate on testing data # Hint: knn.score acc = knn.score(x_test,y_test) print("Accuracy: {}".format(acc)) if(__name__ == '__main__'): import argparse parser = argparse.ArgumentParser() args = parser.parse_args() _main(args)
[ "keras.datasets.mnist.load_data", "sklearn.neighbors.KNeighborsClassifier", "numpy.reshape", "argparse.ArgumentParser" ]
[((333, 350), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (348, 350), False, 'from keras.datasets import mnist\n'), ((393, 426), 'numpy.reshape', 'np.reshape', (['x_train', '(60000, 784)'], {}), '(x_train, (60000, 784))\n', (403, 426), True, 'import numpy as np\n'), ((438, 470), 'numpy.reshape', 'np.reshape', (['x_test', '(10000, 784)'], {}), '(x_test, (10000, 784))\n', (448, 470), True, 'import numpy as np\n'), ((610, 656), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(3)', 'n_jobs': '(-1)'}), '(n_neighbors=3, n_jobs=-1)\n', (630, 656), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((1081, 1106), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1104, 1106), False, 'import argparse\n')]
# -*- encoding: utf-8 -*- import numpy as np import pandas as pd from copy import deepcopy from tqdm import tqdm as TQ ### --- Functions Copied from CentroidDetection.commons.DistanceFunctions --- ### def _EuclideanDistance_(startPoint : np.ndarray, targetPoint : np.ndarray) -> float: '''Calculates the Eulidean Distance b/w Two Points on an n-Dimensional Plane :param startPoint : Start Point, with [x, y, ... z] Coordinates :param targetPoint : Start Point, with [x, y, ... z] Coordinates Returns the Distance b/w two Points (unitless Quantity) ''' if (type(startPoint) != np.ndarray) or (type(targetPoint) != np.ndarray): startPoint = np.array(startPoint) targetPoint = np.array(targetPoint) return np.sqrt(np.sum((startPoint - targetPoint) ** 2)) def _ManhattanDistance_(startPoint : np.ndarray, targetPoint : np.ndarray) -> float: '''Calculates the Manhattan Distance b/w Two Points on an n-Dimensional Plane :param startPoint : Start Point, with [x, y, ... z] Coordinates :param targetPoint : Start Point, with [x, y, ... z] Coordinates Returns the Distance b/w two Points (unitless Quantity) ''' if (type(startPoint) != np.ndarray) or (type(targetPoint) != np.ndarray): startPoint = np.array(startPoint) targetPoint = np.array(targetPoint) return sum([abs(i) for i in (startPoint - targetPoint)]) def _ChooseDistanceMetric_(param : str): return { 'euclidean' : _EuclideanDistance_, 'manhattan' : _ManhattanDistance_, }.get(param) # if any ValueError is Passed, it is taken cared in the Main Function: dist_date_parser() def _CalculateVelocity_(tStart, tEnd, startPoint, endPoint, dist_metric) -> [float, float]: '''Given the Reqd. Values, calculates Distance & Velocity''' time = abs(tStart - tEnd) distance = dist_metric(np.array(startPoint), np.array(endPoint)) return distance, distance / time ### --- Main Functionalities --- ### def dist_date_parser(data : dict or pd.DataFrame, distance_type : str = 'euclidean', **kwargs) -> pd.DataFrame: '''Given a Data as per GenerateData.RandMOD01() Format This Function Calculates Distance (Euclidean/Manhattan) and Velocity The Data Expects Column Names as per the Required Format - if there is any Name-Change, Then use the kwargs to List out the Names. Parameters ---------- distance_type : either euclidean or manhattan, Default euclidean Keyword Arguments ----------------- keep_trip_sub_num : (bool) Keep the Column Named TripSubNum. Default False keep_data_indexed : (bool) Keep the Data Indexed [ParticleID, TripID]. Default False ''' if type(data) == dict: data = deepcopy(pd.DataFrame(data)) elif type(data) == pd.DataFrame: data = deepcopy(data) else: raise TypeError(f'Expects dtype dict or pd.DataFrame, got {type(data)}') # Selection of Ditance-Metric if distance_type not in ['euclidean', 'manhattan']: raise ValueError(f'Expects euclidean/manhattan, got {distance_type}') # Need to Append for both else: dist_metric = _ChooseDistanceMetric_(distance_type) # Setting the Keyword Arguments for the Column Names ParticleID = kwargs.get('ParticleID', 'ParticleID') TripID = kwargs.get('TripID', 'TripID') TimeStamp = kwargs.get('TimeStamp', 'TimeStamp') xStart = kwargs.get('xStart', 'xStart') yStart = kwargs.get('yStart', 'yStart') TripSubNum = kwargs.get('TripSubNum', 'TripSubNum') # Other Optional Keyword Arguments as Described keep_trip_sub_num = kwargs.get('keep_trip_sub_num', False) keep_data_indexed = kwargs.get('keep_data_indexed', False) # Parsed Values velocity = [] distances = [] for idx, row in TQ(data.iterrows(), desc = f'Appending Required Values to a DF of Shape {data.shape}'): if row[TripSubNum] == 0: # Determines Starting of the Trip velocity.append(0) distances.append(0) else: _prev_time = data.iloc[idx - 1][TimeStamp] _prev_xStart = data.iloc[idx - 1][xStart] _prev_yStart = data.iloc[idx - 1][yStart] d, v = _CalculateVelocity_(_prev_time, row[TimeStamp], [_prev_xStart, _prev_yStart], [row[xStart], row[yStart]], dist_metric) velocity.append(v) distances.append(d) data['Velocity'] = velocity data[f'{distance_type.capitalize()}Distance'] = distances if keep_data_indexed: data.set_index([ParticleID, TripID], inplace = True) return data
[ "pandas.DataFrame", "copy.deepcopy", "numpy.array", "numpy.sum" ]
[((652, 672), 'numpy.array', 'np.array', (['startPoint'], {}), '(startPoint)\n', (660, 672), True, 'import numpy as np\n'), ((689, 710), 'numpy.array', 'np.array', (['targetPoint'], {}), '(targetPoint)\n', (697, 710), True, 'import numpy as np\n'), ((728, 767), 'numpy.sum', 'np.sum', (['((startPoint - targetPoint) ** 2)'], {}), '((startPoint - targetPoint) ** 2)\n', (734, 767), True, 'import numpy as np\n'), ((1220, 1240), 'numpy.array', 'np.array', (['startPoint'], {}), '(startPoint)\n', (1228, 1240), True, 'import numpy as np\n'), ((1257, 1278), 'numpy.array', 'np.array', (['targetPoint'], {}), '(targetPoint)\n', (1265, 1278), True, 'import numpy as np\n'), ((1778, 1798), 'numpy.array', 'np.array', (['startPoint'], {}), '(startPoint)\n', (1786, 1798), True, 'import numpy as np\n'), ((1800, 1818), 'numpy.array', 'np.array', (['endPoint'], {}), '(endPoint)\n', (1808, 1818), True, 'import numpy as np\n'), ((2604, 2622), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (2616, 2622), True, 'import pandas as pd\n'), ((2667, 2681), 'copy.deepcopy', 'deepcopy', (['data'], {}), '(data)\n', (2675, 2681), False, 'from copy import deepcopy\n')]
import yaml import numpy as np import collections import os from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove import copy import shutil ### edit this path plr_path = "/cluster/home/jonfrey/PLR3" template_path =plr_path + '/yaml/exp/exp_ws_deepim_leon.yml' save_dir = plr_path+'/yaml/auto' model_base_path = '/cluster/work/riner/users/PLR-2020/jonfrey/models/runs' #pruge ansible folder first shutil.rmtree(save_dir) #open the template with open(template_path) as f: data = yaml.load(f, Loader=yaml.FullLoader) print(data) jobs = [] ########################### EDIT YOUR EXPERIMENTS HERE ##################### #4h_load_<MODELNAME>_exp_<you_conduct> folder_name = 'deep_im_lr' tag = 'TAG' host = 'leonhard' #'jonas' yash ram = 64 scratch = 350 cores = 20 gpus = 1 time = '3:59' # '23:59' os.makedirs(f'{save_dir}/{folder_name}', exist_ok=True) #lr = np.linspace(start=0.005, stop=0.00001, num=6).tolist() ls_lr = np.logspace(start=-6, stop=-8, num=3,base=10).tolist() i = [0] def send(i,tag,data): #baseline with open(f'{save_dir}/{folder_name}/{i[0]}_{tag}.yml' , 'w') as f: jobs.append( {'exp': f'{save_dir}/{folder_name}/{i[0]}_{tag}.yml'} ) data['model_path'] = f'{model_base_path}/{folder_name}/{i[0]}_{tag}' yaml.dump(data, f, default_flow_style=False, sort_keys=False) i[0] = i[0] +1 for lr in ls_lr: data['lr'] = lr send(i,f'lr_{lr}',data) ################################## DONE ################################ bsub = f'bsub -n {int(cores)} -W {time} -R "rusage[mem={int(ram*1000/cores)},ngpus_excl_p={int(gpus)}]" -R "rusage[scratch={int(scratch*1000/cores)}]" $HOME/PLR3/scripts/leonhard/submit.sh ' for job in jobs: exp = job['exp'] arg = f' --env=yaml/env/env_leonhard_jonas.yml --exp {exp}' print("Send command: ", bsub+arg, "\n \n") os.system(bsub+arg)
[ "yaml.load", "os.makedirs", "numpy.logspace", "yaml.dump", "os.system", "shutil.rmtree" ]
[((438, 461), 'shutil.rmtree', 'shutil.rmtree', (['save_dir'], {}), '(save_dir)\n', (451, 461), False, 'import shutil\n'), ((842, 897), 'os.makedirs', 'os.makedirs', (['f"""{save_dir}/{folder_name}"""'], {'exist_ok': '(True)'}), "(f'{save_dir}/{folder_name}', exist_ok=True)\n", (853, 897), False, 'import os\n'), ((523, 559), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.FullLoader'}), '(f, Loader=yaml.FullLoader)\n', (532, 559), False, 'import yaml\n'), ((1840, 1861), 'os.system', 'os.system', (['(bsub + arg)'], {}), '(bsub + arg)\n', (1849, 1861), False, 'import os\n'), ((967, 1013), 'numpy.logspace', 'np.logspace', ([], {'start': '(-6)', 'stop': '(-8)', 'num': '(3)', 'base': '(10)'}), '(start=-6, stop=-8, num=3, base=10)\n', (978, 1013), True, 'import numpy as np\n'), ((1286, 1347), 'yaml.dump', 'yaml.dump', (['data', 'f'], {'default_flow_style': '(False)', 'sort_keys': '(False)'}), '(data, f, default_flow_style=False, sort_keys=False)\n', (1295, 1347), False, 'import yaml\n')]
import numpy as np import WetterStation_KN.Read_TXT as rtxt def read_historical_txt_file(path, return_all=False, showPeaks=True, scan=False): assert path.__contains__("02712") # check ID is Konstanz! rainsum_month = np.zeros(12, dtype=np.float32) # Monthly rainfall all_data = [] # each measurement sum = 0 n_rain = 0 max_value = 0 # max ammount of rainfall date = None # open file fp = open(path, "r") headers = fp.readline() #STATIONS_ID;MESS_DATUM_BEGINN;MESS_DATUM_ENDE;QN;RS_01;RTH_01;RWH_01;RS_IND_01;eor for line in fp: datum, value = rtxt.get_data(line,rainfallIndex=4) all_data.append(value) sum += value if value > 0.0: n_rain += 1 month = int(datum[4:6]) - 1 rainsum_month[month] += value if value > max_value: max_value = value date = datum if value > 2.50 and showPeaks: print(rtxt.convert_date_pretty(datum), value) if scan: scan_for_irregularidades(line) fp.close() if return_all: return rainsum_month, all_data, date, max_value, n_rain return rainsum_month def vis_statistic_month(all_data, n_rain, max_value, date, month_id, rainsum_reference=None, showDetails=True, showHeader=True): np_data = np.array(all_data, dtype=np.float32) if showDetails: print("Ausgewerteter Monat: {}".format(str(month_id).zfill(2))) print("maximalwert: {:1.2f} erreicht am {}".format(max_value, rtxt.convert_date_pretty(date))) print("Regen/gesamt: {:1.2f}%".format(int(n_rain * 100 / np_data.size))) print("gesamt Regenmenge: {:1.2f}".format(np_data.sum())) print("Durchschnittliche regenmenge: {:1.2f}".format(np_data.sum() / np_data.size)) print("Durchschnittliche Regenmenge (bei Regen): {:1.2f}".format(np_data.sum() / n_rain)) if rainsum_reference is not None: if showHeader: print("Monat\tRef.\tMess.\tDiff.") rel_err = -1 if rainsum_reference > 0: rel_err = abs((rainsum_reference - np_data.sum()) / rainsum_reference) print(" {} \t{}\t{:1.2f}\t{:1.2f}".format(str(i).zfill(2), rainsum_reference, np_data.sum(), rel_err)) return def scan_for_irregularidades(line,): a = line.split(";") output="" if(a[3] != ' 3'): output += "QN != 3 " if(a[5] != ' -999' or a[6] != ' -999'): output += "RWH || RTH != -999" if output != "": print(output, line) if __name__ == '__main__': #Placeholder for month and day filename = "historical\\produkt_ein_min_rr_2017{}01_2017{}{}_02712" lastDayOfMonth=np.array([31,28,31,30,31,30,31,31,30,31,30,31]) #ToDo regenreferenz einbauen: for i in range(1,13): rsm, all_data, max_date, max_value, n_rain= read_historical_txt_file(filename.format(str(i).zfill(2), str(i).zfill(2), lastDayOfMonth[i-1])+".txt", True, showPeaks=False, scan=True) vis_statistic_month(all_data, n_rain, max_value, max_date, month_id=i, rainsum_reference=10.0, showDetails=False, showHeader=(i==1))
[ "numpy.array", "WetterStation_KN.Read_TXT.get_data", "numpy.zeros", "WetterStation_KN.Read_TXT.convert_date_pretty" ]
[((239, 269), 'numpy.zeros', 'np.zeros', (['(12)'], {'dtype': 'np.float32'}), '(12, dtype=np.float32)\n', (247, 269), True, 'import numpy as np\n'), ((1423, 1459), 'numpy.array', 'np.array', (['all_data'], {'dtype': 'np.float32'}), '(all_data, dtype=np.float32)\n', (1431, 1459), True, 'import numpy as np\n'), ((2892, 2950), 'numpy.array', 'np.array', (['[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]'], {}), '([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])\n', (2900, 2950), True, 'import numpy as np\n'), ((682, 718), 'WetterStation_KN.Read_TXT.get_data', 'rtxt.get_data', (['line'], {'rainfallIndex': '(4)'}), '(line, rainfallIndex=4)\n', (695, 718), True, 'import WetterStation_KN.Read_TXT as rtxt\n'), ((1054, 1085), 'WetterStation_KN.Read_TXT.convert_date_pretty', 'rtxt.convert_date_pretty', (['datum'], {}), '(datum)\n', (1078, 1085), True, 'import WetterStation_KN.Read_TXT as rtxt\n'), ((1673, 1703), 'WetterStation_KN.Read_TXT.convert_date_pretty', 'rtxt.convert_date_pretty', (['date'], {}), '(date)\n', (1697, 1703), True, 'import WetterStation_KN.Read_TXT as rtxt\n')]
import matplotlib.pyplot as plt import numpy as np from solve_functions import eigenvalue_solve, static_solve from system_functions import build_system_matrix k_full_target, m_full_target = build_system_matrix([1.0,1.0,1.0]) eigenmodes_target, eigenfrequencies_target = eigenvalue_solve(k_full_target, m_full_target) static_deformation_target = static_solve(k_full_target) k_full_initial, m_full_initial = build_system_matrix([0.001,0.0012,0.0014]) #k_full_initial, m_full_initial = build_system_matrix([0.999,0.97,0.99]) eigenmodes_initial, eigenfrequencies_initial = eigenvalue_solve(k_full_initial, m_full_initial) static_deformation_initial = static_solve(k_full_initial) x = [0.0, 1.0, 2.0, 3.0] def evaluate_residual(a_cur, a_tar): return np.linalg.norm(np.subtract(a_cur, a_tar))/np.amax(np.absolute(a_tar)) print('Eigenvalue solve results') for idx, freq in enumerate(eigenfrequencies_target): print(' Mode: ', str(idx+1)) print(' Eigenfeq: ') print(' Target: ', str(eigenfrequencies_target[idx])) print(' Initial: ', str(eigenfrequencies_initial[idx])) print(' Res y: ', str(evaluate_residual(eigenmodes_initial['y'][idx], eigenmodes_target['y'][idx]))) print(' Res g: ', str(evaluate_residual(eigenmodes_initial['g'][idx], eigenmodes_target['g'][idx]))) if idx == 0: fig, axs = plt.subplots(2) fig.suptitle('Eigenvalue solve') axs[0].plot(x, eigenmodes_target['y'][idx],'k--', label='target') axs[0].plot(x, eigenmodes_initial['y'][idx],'r-', label='initial') axs[1].plot(x, eigenmodes_target['g'][idx], 'k--', label='target') axs[1].plot(x, eigenmodes_initial['g'][idx], 'r-', label='initial') plt.legend() plt.show() print('Static solve results') print('Res y: ', str(evaluate_residual(static_deformation_initial['y'],static_deformation_target['y']))) print('Res g: ', str(evaluate_residual(static_deformation_initial['g'],static_deformation_target['g']))) fig, axs = plt.subplots(2) fig.suptitle('Static solve') axs[0].plot(x, static_deformation_target['y'],'k--', label='target') axs[0].plot(x, static_deformation_initial['y'],'r-', label='initial') axs[1].plot(x, static_deformation_target['g'], 'k--', label='target') axs[1].plot(x, static_deformation_initial['g'], 'r-', label='initial') plt.legend() plt.show()
[ "numpy.absolute", "matplotlib.pyplot.show", "numpy.subtract", "matplotlib.pyplot.legend", "system_functions.build_system_matrix", "solve_functions.static_solve", "solve_functions.eigenvalue_solve", "matplotlib.pyplot.subplots" ]
[((192, 228), 'system_functions.build_system_matrix', 'build_system_matrix', (['[1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0])\n', (211, 228), False, 'from system_functions import build_system_matrix\n'), ((272, 318), 'solve_functions.eigenvalue_solve', 'eigenvalue_solve', (['k_full_target', 'm_full_target'], {}), '(k_full_target, m_full_target)\n', (288, 318), False, 'from solve_functions import eigenvalue_solve, static_solve\n'), ((347, 374), 'solve_functions.static_solve', 'static_solve', (['k_full_target'], {}), '(k_full_target)\n', (359, 374), False, 'from solve_functions import eigenvalue_solve, static_solve\n'), ((409, 453), 'system_functions.build_system_matrix', 'build_system_matrix', (['[0.001, 0.0012, 0.0014]'], {}), '([0.001, 0.0012, 0.0014])\n', (428, 453), False, 'from system_functions import build_system_matrix\n'), ((572, 620), 'solve_functions.eigenvalue_solve', 'eigenvalue_solve', (['k_full_initial', 'm_full_initial'], {}), '(k_full_initial, m_full_initial)\n', (588, 620), False, 'from solve_functions import eigenvalue_solve, static_solve\n'), ((650, 678), 'solve_functions.static_solve', 'static_solve', (['k_full_initial'], {}), '(k_full_initial)\n', (662, 678), False, 'from solve_functions import eigenvalue_solve, static_solve\n'), ((2029, 2044), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (2041, 2044), True, 'import matplotlib.pyplot as plt\n'), ((2354, 2366), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2364, 2366), True, 'import matplotlib.pyplot as plt\n'), ((2367, 2377), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2375, 2377), True, 'import matplotlib.pyplot as plt\n'), ((1377, 1392), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (1389, 1392), True, 'import matplotlib.pyplot as plt\n'), ((1742, 1754), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1752, 1754), True, 'import matplotlib.pyplot as plt\n'), ((1763, 1773), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1771, 1773), True, 'import matplotlib.pyplot as plt\n'), ((770, 795), 'numpy.subtract', 'np.subtract', (['a_cur', 'a_tar'], {}), '(a_cur, a_tar)\n', (781, 795), True, 'import numpy as np\n'), ((805, 823), 'numpy.absolute', 'np.absolute', (['a_tar'], {}), '(a_tar)\n', (816, 823), True, 'import numpy as np\n')]
import sys sys.path.append('./python') import skyhook.common as lib import json import numpy import os, os.path import requests import skimage.io, skimage.transform import torch import torch.optim import torch.utils import skyhook.pytorch.model as model import skyhook.pytorch.util as util import skyhook.pytorch.dataset as skyhook_dataset import skyhook.pytorch.augment as skyhook_augment url = sys.argv[1] local_port = int(sys.argv[2]) batch_size = int(sys.argv[3]) local_url = 'http://127.0.0.1:{}'.format(local_port) # Get parameters. resp = requests.get(local_url + '/config') config = resp.json() params = config['Params'] arch = config['Arch'] comps = config['Components'] datasets = config['Inputs'] parent_models = config['ParentModels'] out_dataset_id = config['Output']['ID'] train_split = config['TrainSplit'] valid_split = config['ValidSplit'] arch = arch['Params'] # overwrite parameters in arch['Components'][idx]['Params'] with parameters # from params['Components'][idx] if params.get('Components', None): overwrite_comp_params = {int(k): v for k, v in params['Components'].items()} for comp_idx, comp_spec in enumerate(arch['Components']): comp_params = {} if comp_spec['Params']: comp_params = json.loads(comp_spec['Params']) if overwrite_comp_params.get(comp_idx, None): comp_params.update(json.loads(overwrite_comp_params[comp_idx])) comp_spec['Params'] = json.dumps(comp_params) device = torch.device('cuda:0') #device = torch.device('cpu') # get train and val Datasets print('loading datasets') dataset_provider = skyhook_dataset.providers[params['Dataset']['Op']] dataset_params = json.loads(params['Dataset']['Params']) train_set, val_set = dataset_provider(url, datasets, dataset_params, train_split, valid_split) datatypes = train_set.get_datatypes() # get data augmentation steps # this is a list of objects that provide forward() function # we will apply the forward function on batches from DataLoader print('loading data augmentations') ds_augments = [] torch_augments = [] for spec in params['Augment']: cls_func = skyhook_augment.augmentations[spec['Op']] obj = cls_func(json.loads(spec['Params']), datatypes) if obj.pre_torch: ds_augments.append(obj) else: torch_augments.append(obj) train_set.set_augments(ds_augments) val_set.set_augments(ds_augments) # apply data augmentation on validation set # this is because some augmentations are random but we want a consistent validation set # here we assume the validation set fits in system memory, but not necessarily GPU memory # so we apply augmentation on CPU, whereas during training we will apply on GPU train_params = json.loads(params['Train']['Params']) print('preparing validation set') val_loader = torch.utils.data.DataLoader( val_set, batch_size=batch_size, num_workers=4, collate_fn=val_set.collate_fn, # drop last unless we'd end up with 0 batches drop_last=len(val_set) > batch_size ) val_batches = [] for batch in val_loader: for obj in torch_augments: batch = obj.forward(batch) val_batches.append(batch) ''' batch = val_batches[0] for i in range(32): im = batch[0][i, :, :, :].cpu().numpy().transpose(1, 2, 0) prefix = sum(batch[1]['counts'][0:i]) detections = batch[1]['detections'][prefix:prefix+batch[1]['counts'][i]] for d in detections: cls, sx, sy, ex, ey = d sx = int(sx*im.shape[1]) sy = int(sy*im.shape[0]) ex = int(ex*im.shape[1]) ey = int(ey*im.shape[0]) im[sy:sy+2, sx:ex, :] = [255, 0, 0] im[ey-2:ey, sx:ex, :] = [255, 0, 0] im[sy:ey, sx:sx+2, :] = [255, 0, 0] im[sy:ey, ex-2:ex, :] = [255, 0, 0] skimage.io.imsave('/home/ubuntu/vis/{}.jpg'.format(i), im) ''' ''' batch = val_batches[0] for i in range(32): im1 = batch[0][i, :, :, :].cpu().numpy().transpose(1, 2, 0) im2 = (batch[1][i, 0, :, :].cpu().numpy() > 0).astype('uint8')*255 skimage.io.imsave('/home/ubuntu/vis/{}_im.jpg'.format(i), im1) skimage.io.imsave('/home/ubuntu/vis/{}_mask.png'.format(i), im2) ''' print('initialize model') train_loader = torch.utils.data.DataLoader( train_set, batch_size=batch_size, shuffle=True, num_workers=4, collate_fn=train_set.collate_fn, # drop last unless we'd end up with 0 batches drop_last=len(train_set) > batch_size ) for example_inputs in train_loader: break util.inputs_to_device(example_inputs, device) example_metadatas = train_set.get_metadatas(0) net = model.Net(arch, comps, example_inputs, example_metadatas, device=device) net.to(device) learning_rate = train_params.get('LearningRate', 1e-3) optimizer_name = train_params.get('Optimizer', 'adam') if optimizer_name == 'adam': optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate) updated_lr = False class StopCondition(object): def __init__(self, params): self.max_epochs = params.get('MaxEpochs', 0) # if score improves by less than score_epsilon for score_max_epochs epochs, # then we stop self.score_epsilon = params.get('ScoreEpsilon', 0) self.score_max_epochs = params.get('ScoreMaxEpochs', 25) # last score seen where we reset the score_epochs # this is less than the best_score only when score_epsilon > 0 # (if a higher score is within epsilon of the last reset score) self.last_score = None # best score seen ever self.best_score = None self.epochs = 0 self.score_epochs = 0 def update(self, score): print( 'epochs: {}/{} ... score: {}/{} (epochs since reset: {}/{}; best score: {})'.format( self.epochs, self.max_epochs, score, self.last_score, self.score_epochs, self.score_max_epochs, self.best_score )) self.epochs += 1 if self.max_epochs and self.epochs >= self.max_epochs: return True if self.best_score is None or score > self.best_score: self.best_score = score score_threshold = None if self.last_score is not None: score_threshold = self.last_score if self.score_epsilon is not None: score_threshold += self.score_epsilon if score_threshold is None or score > score_threshold: self.score_epochs = 0 self.last_score = self.best_score else: self.score_epochs += 1 if self.score_max_epochs and self.score_epochs >= self.score_max_epochs: return True return False def save_model(): # Save to a different filename first to reduce the chance of model being corrupted # if job is terminated. out_dir = os.path.join('data/items', str(out_dataset_id)) torch.save(net.get_save_dict(), os.path.join(out_dir, 'model_.pt')) os.rename(os.path.join(out_dir, 'model_.pt'), os.path.join(out_dir, 'model.pt')) class ModelSaver(object): def __init__(self, params): # either "latest" or "best" self.mode = params.get('Mode', 'best') self.best_score = None def update(self, net, score): should_save = False if self.mode == 'latest': should_save = True elif self.mode == 'best': if self.best_score is None or score > self.best_score: self.best_score = score should_save = True if should_save: save_model() stop_condition = StopCondition(train_params['StopCondition']) model_saver = ModelSaver(train_params['ModelSaver']) rate_decay_params = train_params['RateDecay'] scheduler = None if rate_decay_params['Op'] == 'step': scheduler = torch.optim.lr_scheduler.StepLR(optimizer, rate_decay_params['StepSize'], gamma=rate_decay_params['StepGamma']) elif rate_decay_params['Op'] == 'plateau': scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, mode='max', factor=rate_decay_params['PlateauFactor'], patience=rate_decay_params['PlateauPatience'], threshold=rate_decay_params['PlateauThreshold'], min_lr=rate_decay_params['PlateauMin'] ) if params.get('Restore', None) and parent_models: for i, restore in enumerate(params['Restore']): if i >= len(parent_models): # could happen if user configured restore but then removed parent continue parent_model = parent_models[i] src_prefix = restore['SrcPrefix'] dst_prefix = restore['DstPrefix'] skip_prefixes = [prefix.strip() for prefix in restore['SkipPrefixes'].split(',') if prefix.strip()] print('restore model to', dst_prefix) # load save dict based on dataset ID fname = 'data/items/{}/model.pt'.format(parent_model['ID']) save_dict = torch.load(fname) # update the parameter names based on src/dst/skip prefixes state_dict = save_dict['model'] new_dict = {} for k, v in state_dict.items(): if not k.startswith(src_prefix): continue # check skip prefixes skip = False for prefix in skip_prefixes: if k.startswith(prefix): skip = True break if skip: continue # remove src_prefix and add dst_prefix k = k[len(src_prefix):] k = dst_prefix+k new_dict[k] = v missing_keys, unexpected_keys = net.load_state_dict(new_dict, strict=False) if missing_keys: print('... warning: got missing keys:', missing_keys) if unexpected_keys: print('... warning: got unexpected keys:', unexpected_keys) epoch = 0 def get_loss_avgs(losses): loss_avgs = {} for k in losses[0].keys(): loss_avgs[k] = numpy.mean([d[k] for d in losses]) return loss_avgs print('begin training') save_model() while True: train_losses = [] net.train() for inputs in train_loader: util.inputs_to_device(inputs, device) for obj in torch_augments: inputs = obj.forward(inputs) optimizer.zero_grad() loss_dict, _ = net(*inputs[0:arch['NumInputs']], targets=inputs[arch['NumInputs']:]) loss_dict['loss'].backward() optimizer.step() train_losses.append({k: v.item() for k, v in loss_dict.items()}) val_losses = [] net.eval() for inputs in val_batches: util.inputs_to_device(inputs, device) loss_dict, _ = net(*inputs[0:arch['NumInputs']], targets=inputs[arch['NumInputs']:]) val_losses.append({k: v.item() for k, v in loss_dict.items()}) train_loss_avgs = get_loss_avgs(train_losses) val_loss_avgs = get_loss_avgs(val_losses) json_loss = json.dumps({ 'train': train_loss_avgs, 'val': val_loss_avgs, }) print('jsonloss' + json_loss) val_loss = val_loss_avgs['loss'] score = val_loss_avgs['score'] if stop_condition.update(score): break model_saver.update(net, score) if scheduler is not None: scheduler.step(score) print('lr={}'.format(optimizer.param_groups[0]['lr'])) epoch += 1
[ "sys.path.append", "torch.optim.lr_scheduler.StepLR", "json.loads", "torch.load", "skyhook.pytorch.model.Net", "torch.optim.lr_scheduler.ReduceLROnPlateau", "json.dumps", "numpy.mean", "requests.get", "torch.device", "os.path.join", "skyhook.pytorch.util.inputs_to_device" ]
[((11, 38), 'sys.path.append', 'sys.path.append', (['"""./python"""'], {}), "('./python')\n", (26, 38), False, 'import sys\n'), ((553, 588), 'requests.get', 'requests.get', (["(local_url + '/config')"], {}), "(local_url + '/config')\n", (565, 588), False, 'import requests\n'), ((1437, 1459), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1449, 1459), False, 'import torch\n'), ((1633, 1672), 'json.loads', 'json.loads', (["params['Dataset']['Params']"], {}), "(params['Dataset']['Params'])\n", (1643, 1672), False, 'import json\n'), ((2645, 2682), 'json.loads', 'json.loads', (["params['Train']['Params']"], {}), "(params['Train']['Params'])\n", (2655, 2682), False, 'import json\n'), ((4262, 4307), 'skyhook.pytorch.util.inputs_to_device', 'util.inputs_to_device', (['example_inputs', 'device'], {}), '(example_inputs, device)\n', (4283, 4307), True, 'import skyhook.pytorch.util as util\n'), ((4361, 4433), 'skyhook.pytorch.model.Net', 'model.Net', (['arch', 'comps', 'example_inputs', 'example_metadatas'], {'device': 'device'}), '(arch, comps, example_inputs, example_metadatas, device=device)\n', (4370, 4433), True, 'import skyhook.pytorch.model as model\n'), ((7144, 7259), 'torch.optim.lr_scheduler.StepLR', 'torch.optim.lr_scheduler.StepLR', (['optimizer', "rate_decay_params['StepSize']"], {'gamma': "rate_decay_params['StepGamma']"}), "(optimizer, rate_decay_params['StepSize'],\n gamma=rate_decay_params['StepGamma'])\n", (7175, 7259), False, 'import torch\n'), ((9811, 9871), 'json.dumps', 'json.dumps', (["{'train': train_loss_avgs, 'val': val_loss_avgs}"], {}), "({'train': train_loss_avgs, 'val': val_loss_avgs})\n", (9821, 9871), False, 'import json\n'), ((1403, 1426), 'json.dumps', 'json.dumps', (['comp_params'], {}), '(comp_params)\n', (1413, 1426), False, 'import json\n'), ((2135, 2161), 'json.loads', 'json.loads', (["spec['Params']"], {}), "(spec['Params'])\n", (2145, 2161), False, 'import json\n'), ((6366, 6400), 'os.path.join', 'os.path.join', (['out_dir', '"""model_.pt"""'], {}), "(out_dir, 'model_.pt')\n", (6378, 6400), False, 'import os, os.path\n'), ((6413, 6447), 'os.path.join', 'os.path.join', (['out_dir', '"""model_.pt"""'], {}), "(out_dir, 'model_.pt')\n", (6425, 6447), False, 'import os, os.path\n'), ((6449, 6482), 'os.path.join', 'os.path.join', (['out_dir', '"""model.pt"""'], {}), "(out_dir, 'model.pt')\n", (6461, 6482), False, 'import os, os.path\n'), ((7312, 7570), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'torch.optim.lr_scheduler.ReduceLROnPlateau', (['optimizer'], {'mode': '"""max"""', 'factor': "rate_decay_params['PlateauFactor']", 'patience': "rate_decay_params['PlateauPatience']", 'threshold': "rate_decay_params['PlateauThreshold']", 'min_lr': "rate_decay_params['PlateauMin']"}), "(optimizer, mode='max', factor=\n rate_decay_params['PlateauFactor'], patience=rate_decay_params[\n 'PlateauPatience'], threshold=rate_decay_params['PlateauThreshold'],\n min_lr=rate_decay_params['PlateauMin'])\n", (7354, 7570), False, 'import torch\n'), ((8147, 8164), 'torch.load', 'torch.load', (['fname'], {}), '(fname)\n', (8157, 8164), False, 'import torch\n'), ((8963, 8997), 'numpy.mean', 'numpy.mean', (['[d[k] for d in losses]'], {}), '([d[k] for d in losses])\n', (8973, 8997), False, 'import numpy\n'), ((9129, 9166), 'skyhook.pytorch.util.inputs_to_device', 'util.inputs_to_device', (['inputs', 'device'], {}), '(inputs, device)\n', (9150, 9166), True, 'import skyhook.pytorch.util as util\n'), ((9516, 9553), 'skyhook.pytorch.util.inputs_to_device', 'util.inputs_to_device', (['inputs', 'device'], {}), '(inputs, device)\n', (9537, 9553), True, 'import skyhook.pytorch.util as util\n'), ((1232, 1263), 'json.loads', 'json.loads', (["comp_spec['Params']"], {}), "(comp_spec['Params'])\n", (1242, 1263), False, 'import json\n'), ((1334, 1377), 'json.loads', 'json.loads', (['overwrite_comp_params[comp_idx]'], {}), '(overwrite_comp_params[comp_idx])\n', (1344, 1377), False, 'import json\n')]
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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. """Contains methods for packaging data from a DataSource for the API.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import numpy as np from scipy import signal from eeg_modelling.eeg_viewer import utils from eeg_modelling.pyprotos import data_pb2 # The double banana refers to a common montage used to display EEG data. # Each tuple represents a 'standard' in the montage, which is a subtraction of # the signals from two EEG leads placed on the scalp. # Elements containing '|' allow for differences in lead naming conventions # between datasets. _DOUBLE_BANANA = [('FP1', 'F7'), ('F7', 'T3|T7'), ('T3|T7', 'T5|P7'), ('T5|P7', 'O1'), ('FP2', 'F8'), ('F8', 'T4|T8'), ('T4|T8', 'T6|P8'), ('T6|P8', 'O2'), ('FP1', 'F3'), ('F3', 'C3'), ('C3', 'P3'), ('P3', 'O1'), ('FP2', 'F4'), ('F4', 'C4'), ('C4', 'P4'), ('P4', 'O2'), ('FZ', 'CZ'), ('CZ', 'PZ'), ('EKG1', 'EKG2')] # The standard set of leads for a 12 lead ECG _ECG_12_LEAD = [('I',), ('II',), ('III',), ('AVR',), ('AVL',), ('AVF',), ('V1',), ('V2',), ('V3',), ('V4',), ('V5',), ('V6',)] def _FilterData(row_data, index, data_source, low_cut, high_cut, notch): """Runs full segment data through low and high pass filters. Args: row_data: Full segment data for a single channel. index: The index for a single channel. data_source: The DataSource for the waveform data. low_cut: lower frequency to apply a band-pass filter. high_cut: higher frequency to apply a band-pass filter. notch: frequency to apply a notch filter. Returns: Filtered input row data. """ nyquist_freq = data_source.GetChannelSamplingFrequency(index) / 2 low_val = low_cut / nyquist_freq high_val = high_cut / nyquist_freq notch_val = notch / nyquist_freq pad_len = int(nyquist_freq) if int(nyquist_freq) else 1 padded_data = np.pad(row_data, (pad_len, pad_len), 'symmetric') if low_val > 0 and low_val < 1: # Using a 1st-order forward pass filter to match NK viewer b, a = signal.butter(1, [low_val], btype='high', analog=False) padded_data = signal.lfilter(b, a, padded_data) if high_val > 0 and high_val < 1: # Using a 1st-order forward pass filter to match NK viewer b, a = signal.butter(1, [high_val], btype='low', analog=False) padded_data = signal.lfilter(b, a, padded_data) if notch_val > 0 and notch_val < 1: b, a = signal.iirnotch(notch_val, 30) padded_data = signal.lfilter(b, a, padded_data) return padded_data[pad_len:-pad_len] def _GetChannelIndicesInChannelDataIdList(id_list): """Returns a list of all the unique channel indices requested.""" channel_indices = [] for ch in id_list: if ch.HasField('bipolar_channel'): request_indices = [ ch.bipolar_channel.index, ch.bipolar_channel.referential_index ] else: request_indices = [ch.single_channel.index] channel_indices = channel_indices + request_indices return list(set(channel_indices)) def _CreateChannelData(data_source, channel_data_ids, low_cut, high_cut, notch, start=0, duration=None, max_samples=None): """Returns a list of channel names and a dictionary of their values. Args: data_source: The DataSource for the waveform data. channel_data_ids: ChannelDataIds list. low_cut: lower frequency to apply a band-pass filter. high_cut: higher frequency to apply a band-pass filter. notch: frequency to apply a notch filter. start: start time to crop the data, relative to the start of the file (in seconds). Defaults to the start of the file. duration: duration to crop from the data, in seconds. If None, will get the whole file data. max_samples: The maximum number of samples in one channel response. If None, there is no maximum limit. Returns: A dictionary of channel names mapped to the requested time slice of their data and an ordered list of the channel names. Raises: ValueError: Too many feature keys provided (only handles raw features or subtraction of two features). """ if duration is None: duration = data_source.GetLength() channel_indices = _GetChannelIndicesInChannelDataIdList(channel_data_ids) single_channel_data = data_source.GetChannelData( channel_indices, start, duration) subsampling = 1 if max_samples is None else utils.GetSubsamplingRate( len(list(single_channel_data.values())[0]), max_samples) def _GetFilteredData(index): """Wrapper to call _FilterData function. Args: index: the index for the selected channel. Returns: Filtered data for the selected channel. """ return _FilterData(single_channel_data[str(index)], index, data_source, low_cut, high_cut, notch) req_channel_data = {} channel_names = [] for channel_data_id in channel_data_ids: if channel_data_id.HasField('bipolar_channel'): primary_index = channel_data_id.bipolar_channel.index primary_data = _GetFilteredData(primary_index) ref_index = channel_data_id.bipolar_channel.referential_index ref_data = _GetFilteredData(ref_index) channel_data = [reference - primary for (primary, reference) in zip(primary_data, ref_data)] channel_name = '-'.join(data_source.GetChannelName(index) for index in [primary_index, ref_index]) elif channel_data_id.HasField('single_channel'): index = channel_data_id.single_channel.index channel_data = _GetFilteredData(index) channel_name = data_source.GetChannelName(index) else: raise ValueError('Unfamiliary channel type %s' % channel_data_id) req_channel_data[channel_name] = channel_data[::subsampling] channel_names.append(channel_name) return req_channel_data, channel_names def _AddDataTableSeries(channel_data, output_data): """Adds series to the DataTable inputs. Args: channel_data: A dictionary of channel names to their data. Each value in the dictionary has the same sampling frequency and the same time slice. output_data: Current graph data for DataTable API. Returns: The edited output_data dictionary where the first index represents the time axis value and the second the series value. """ for i in range(len(list(channel_data.values())[0])): output_data[i].update({channel_name: data[i] for channel_name, data in channel_data.items()}) return output_data def GetSamplingFrequency(data_source, channel_data_ids): """Returns the sampling frequency for a group of channels. Args: data_source: DataSource instance. channel_data_ids: Channels to get the sampling freq from. Returns: Sampling frequency for all the channels (must be the same). """ channel_indices = _GetChannelIndicesInChannelDataIdList(channel_data_ids) return data_source.GetSamplingFrequency(channel_indices) def _CreateChunkDataTableJSon(data_source, request, max_samples): """Creates a DataTable in JSON format which contains the data specified. Data can be specified by a list of minuends and subtrahends of montage standards and/or a list of channel keys. Args: data_source: The DataSource for the waveform data. request: A DataRequest proto instance. max_samples: The maximum number of samples in one channel response. Returns: JSON format DataTable loaded with montage data. Raises: ValueError: The requested channels have multiple frequency types. """ sample_freq = GetSamplingFrequency(data_source, request.channel_data_ids) # Initialize Dygraph data with a time axis of sampling frequency. output_data, _ = utils.InitDataTableInputsWithTimeAxis( sample_freq, request.chunk_duration_secs, request.chunk_start, max_samples) columns_order = ['seconds'] channel_data, channel_names = _CreateChannelData( data_source, request.channel_data_ids, request.low_cut, request.high_cut, request.notch, start=request.chunk_start, duration=request.chunk_duration_secs, max_samples=max_samples) output_data = _AddDataTableSeries(channel_data, output_data) columns_order.extend(channel_names) return (utils.ConvertToDataTableJSon(output_data, columns_order), sample_freq) def GetMetadata(data_source, max_samples): """Returns metadata consistent across the predictions. Args: data_source: The DataSource for the waveform data. max_samples: The maximum number of samples in one channel response. Returns: A PredictionMetadata instance filled with PredictionOutput data. """ response = data_pb2.WaveformMetadata() response.abs_start = data_source.GetStartTime() response.labels.extend(data_source.GetAnnotations()) for index, channel in data_source.GetChannelIndexDict().iteritems(): response.channel_dict[index] = channel response.file_type = data_source.GetFileType() response.nav_timeline_datatable = utils.CreateEmptyTable( data_source.GetLength(), max_samples) response.num_secs = data_source.GetLength() response.patient_id = data_source.GetPatientId() response.sstable_key = data_source.GetFileKey() return response def _GetChannelIndexFromNameOptions(channel_opts, data_source): indices = [data_source.GetChannelIndexFromName(opt) for opt in channel_opts.split('|') if data_source.GetChannelIndexFromName(opt)] return indices[0] if indices else None def _GetChannelDataIdFromNameOptions(channel_name, data_source): """Creates a ChannelDataId for a channel name string with name options. Sometimes channel naming conventions for the same electrode placement vary between institutions, so the options allow us to cover all cases. Args: channel_name: A tuple of strings with channel name options joined on '|'. data_source: The DataSource for the waveform data. Returns: A ChannelDataId filled out with the indices for the given name tuple. """ channel_id = None if len(channel_name) == 2: primary_index = _GetChannelIndexFromNameOptions(channel_name[0], data_source) ref_index = _GetChannelIndexFromNameOptions(channel_name[1], data_source) if primary_index is not None and ref_index is not None: channel_id = data_pb2.ChannelDataId() channel_id.bipolar_channel.index = int(primary_index) channel_id.bipolar_channel.referential_index = int(ref_index) if len(channel_name) == 1: index = _GetChannelIndexFromNameOptions(channel_name[0], data_source) if index is not None: channel_id = data_pb2.ChannelDataId() channel_id.single_channel.index = int(index) return channel_id def _GetDefaultChannelDataIdList(data_source): """Returns the list of default features when a request does not specify. When a data request is made for the first time with a set of file parameters, the client does not have the lookup table with the channel indices, therefore the client cannot specify channels until after the initial load. To deal with this case, when no channel indices are provided, we generate a list of channel indices using the lookup table and default channel requests that are hardcoded for each medical waveform data type. Those channel indices will be used as the request indices. Args: data_source: The DataSource for the waveform data. """ default_channel_names = [] if data_source.GetFileType() == 'EEG': default_channel_names = _DOUBLE_BANANA elif (data_source.GetFileType() == 'EKG' or data_source.GetFileType() == 'ECG'): default_channel_names = _ECG_12_LEAD default_channel_ids = [_GetChannelDataIdFromNameOptions(x, data_source) for x in default_channel_names] return [channel_id for channel_id in default_channel_ids if channel_id] def GetChunk(data_source, request, max_samples): """Returns all graph data for current chunk. Args: data_source: The DataSource for the waveform data. request: A DataRequest proto instance. max_samples: The maximum number of samples in one channel response. Returns: A WaveformChunkResponse specified by the Request proto. Raises: ValueError: If chunk duration is not a positive integer. """ if (request.chunk_start >= data_source.GetLength() or request.chunk_start + request.chunk_duration_secs <= 0): raise ValueError('Chunk starting at %s is out of bounds' % request.chunk_start) if not request.channel_data_ids: default_channels = _GetDefaultChannelDataIdList(data_source) logging.info('Loading default channels') request.channel_data_ids.extend(default_channels) response = data_pb2.WaveformChunk() waveform_datatable, sampling_freq = _CreateChunkDataTableJSon(data_source, request, max_samples) response.waveform_datatable = waveform_datatable response.sampling_freq = sampling_freq response.channel_data_ids.extend(request.channel_data_ids) return response def GetChunkDataAsNumpy(data_source, channel_data_ids, low_cut, high_cut, notch): """Extract data from a data source as a numpy array. Args: data_source: A DataSource instance. channel_data_ids: ChannelDataIds list. low_cut: lower frequency to apply a band-pass filter. high_cut: higher frequency to apply a band-pass filter. notch: frequency to apply a notch filter. Returns: Numpy array of shape (n_channels, n_data) with the waveform data. """ channel_data, channel_names = _CreateChannelData(data_source, channel_data_ids, low_cut, high_cut, notch) data = [channel_data[channel_name] for channel_name in channel_names] data = np.array(data, dtype=np.float32) return data
[ "numpy.pad", "scipy.signal.lfilter", "scipy.signal.iirnotch", "absl.logging.info", "eeg_modelling.eeg_viewer.utils.InitDataTableInputsWithTimeAxis", "numpy.array", "eeg_modelling.eeg_viewer.utils.ConvertToDataTableJSon", "eeg_modelling.pyprotos.data_pb2.WaveformChunk", "eeg_modelling.pyprotos.data_p...
[((2642, 2691), 'numpy.pad', 'np.pad', (['row_data', '(pad_len, pad_len)', '"""symmetric"""'], {}), "(row_data, (pad_len, pad_len), 'symmetric')\n", (2648, 2691), True, 'import numpy as np\n'), ((8702, 8820), 'eeg_modelling.eeg_viewer.utils.InitDataTableInputsWithTimeAxis', 'utils.InitDataTableInputsWithTimeAxis', (['sample_freq', 'request.chunk_duration_secs', 'request.chunk_start', 'max_samples'], {}), '(sample_freq, request.\n chunk_duration_secs, request.chunk_start, max_samples)\n', (8739, 8820), False, 'from eeg_modelling.eeg_viewer import utils\n'), ((9669, 9696), 'eeg_modelling.pyprotos.data_pb2.WaveformMetadata', 'data_pb2.WaveformMetadata', ([], {}), '()\n', (9694, 9696), False, 'from eeg_modelling.pyprotos import data_pb2\n'), ((13767, 13791), 'eeg_modelling.pyprotos.data_pb2.WaveformChunk', 'data_pb2.WaveformChunk', ([], {}), '()\n', (13789, 13791), False, 'from eeg_modelling.pyprotos import data_pb2\n'), ((15060, 15092), 'numpy.array', 'np.array', (['data'], {'dtype': 'np.float32'}), '(data, dtype=np.float32)\n', (15068, 15092), True, 'import numpy as np\n'), ((2800, 2855), 'scipy.signal.butter', 'signal.butter', (['(1)', '[low_val]'], {'btype': '"""high"""', 'analog': '(False)'}), "(1, [low_val], btype='high', analog=False)\n", (2813, 2855), False, 'from scipy import signal\n'), ((2874, 2907), 'scipy.signal.lfilter', 'signal.lfilter', (['b', 'a', 'padded_data'], {}), '(b, a, padded_data)\n', (2888, 2907), False, 'from scipy import signal\n'), ((3018, 3073), 'scipy.signal.butter', 'signal.butter', (['(1)', '[high_val]'], {'btype': '"""low"""', 'analog': '(False)'}), "(1, [high_val], btype='low', analog=False)\n", (3031, 3073), False, 'from scipy import signal\n'), ((3092, 3125), 'scipy.signal.lfilter', 'signal.lfilter', (['b', 'a', 'padded_data'], {}), '(b, a, padded_data)\n', (3106, 3125), False, 'from scipy import signal\n'), ((3175, 3205), 'scipy.signal.iirnotch', 'signal.iirnotch', (['notch_val', '(30)'], {}), '(notch_val, 30)\n', (3190, 3205), False, 'from scipy import signal\n'), ((3224, 3257), 'scipy.signal.lfilter', 'signal.lfilter', (['b', 'a', 'padded_data'], {}), '(b, a, padded_data)\n', (3238, 3257), False, 'from scipy import signal\n'), ((9251, 9307), 'eeg_modelling.eeg_viewer.utils.ConvertToDataTableJSon', 'utils.ConvertToDataTableJSon', (['output_data', 'columns_order'], {}), '(output_data, columns_order)\n', (9279, 9307), False, 'from eeg_modelling.eeg_viewer import utils\n'), ((13659, 13699), 'absl.logging.info', 'logging.info', (['"""Loading default channels"""'], {}), "('Loading default channels')\n", (13671, 13699), False, 'from absl import logging\n'), ((11360, 11384), 'eeg_modelling.pyprotos.data_pb2.ChannelDataId', 'data_pb2.ChannelDataId', ([], {}), '()\n', (11382, 11384), False, 'from eeg_modelling.pyprotos import data_pb2\n'), ((11661, 11685), 'eeg_modelling.pyprotos.data_pb2.ChannelDataId', 'data_pb2.ChannelDataId', ([], {}), '()\n', (11683, 11685), False, 'from eeg_modelling.pyprotos import data_pb2\n')]
from . import utils from sklearn.model_selection import train_test_split import pandas as pd import numpy as np import matplotlib matplotlib.use("agg") import os import json def get_array(tensor, keys): utils.check_mandatory_keys(tensor, keys) return [tensor[key] for key in keys] def to_hdf5(dictionary, path): import h5py with h5py.File(path, "w") as f: for key, data in dictionary.items(): f.create_dataset(key, data=data, dtype=data.dtype, compression="gzip") def from_hdf5(path): import h5py with h5py.File(path, "r") as f: data = {k: f[k][...] for k in f.keys()} return data letterDict = { "A": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "K": 9, "L": 10, "M": 11, "N": 12, "P": 13, "Q": 14, "R": 15, "S": 16, "T": 17, "V": 18, "W": 19, "Y": 20, #"M(ox)": 21, } #letterDict_s = {integer: char for char, integer in letterDict.items()} def add_mod(mod=None): i=max(letterDict.values())+1 for m in mod: if str(m) not in letterDict: letterDict[str(m)] = i print("New aa: %s -> %d" % (str(m),i)) i = i + 1 def load_aa(file): print("Load aa coding data from file %s" % (file)) dat = pd.read_table(file, sep="\t", header=0, low_memory=False) letterDict.clear() for i, row in dat.iterrows(): letterDict[row['aa']] = row['i'] def save_aa(file): print("Save aa coding data to file %s" % (file)) with open(file,"w") as f: f.write("aa\ti\n") for aa in letterDict.keys(): f.write(aa+"\t"+str(letterDict[aa])+"\n") def peptideEncode(sequence, max_length=50): ''' Encode peptide :param sequences: A list of peptides :return: ''' array = np.zeros([max_length], dtype=int) #print(sequence) #print(letterDict) for i in range(len(sequence)): #print(sequence[i]) array[i] = letterDict[sequence[i]] return array ## This is only used to process training data def data_processing(input_data: str, test_file=None, mod=None, max_x_length = 50, min_rt=0, max_rt=120, unit="s", out_dir="./", aa_file=None): res = dict() if aa_file is not None: ## read aa information from file load_aa(aa_file) res['aa'] = aa_file else: if mod is not None: add_mod(mod) aa2file = out_dir + "/aa.tsv" save_aa(aa2file) res['aa'] = aa2file ## siteData = pd.read_table(input_data, sep="\t", header=0, low_memory=False) ## x is peptide sequence and y is rt if "x" not in siteData.columns: siteData.columns = ['x','y'] ## convert second to minute if unit.startswith("s"): siteData['y'] = siteData['y']/60.0 ## get max rt if max_rt < siteData['y'].max(): max_rt = siteData['y'].max() + 1.0 ## get min rt if min_rt > siteData['y'].min(): min_rt = siteData['y'].min() - 1.0 # aaMap = getAAcodingMap() n_aa_types = len(letterDict) print("AA types: %d" % (n_aa_types)) ## all aa in data all_aa = set() ## get the max length of input sequences longest_pep_training_data = 0 for pep in siteData["x"]: if max_x_length < len(pep): max_x_length = len(pep) if longest_pep_training_data < len(pep): longest_pep_training_data = len(pep) ## for aa in pep: all_aa.add(aa) print("Longest peptide in training data: %d\n" % (longest_pep_training_data)) ## test data test_data = None longest_pep_test_data = 0 if test_file is not None: print("Use test file %s" % (test_file)) test_data = pd.read_table(test_file, sep="\t", header=0, low_memory=False) if "x" not in test_data.columns: test_data.columns = ['x', 'y'] if unit.startswith("s"): test_data['y'] = test_data['y'] / 60.0 if max_rt < test_data['y'].max(): max_rt = test_data['y'].max() + 1.0 if min_rt > test_data['y'].min(): min_rt = test_data['y'].min() - 1.0 for pep in test_data["x"]: if max_x_length < len(pep): max_x_length = len(pep) if longest_pep_test_data < len(pep): longest_pep_test_data = len(pep) for aa in pep: all_aa.add(aa) print("Longest peptide in test data: %d\n" % (longest_pep_test_data)) print(sorted(all_aa)) siteData = siteData.sample(siteData.shape[0], replace=False, random_state=2018) #train_data = np.zeros((siteData.shape[0], max_x_length, n_aa_types)) train_data = np.zeros((siteData.shape[0], max_x_length)) k = 0 for i, row in siteData.iterrows(): peptide = row['x'] # train_data[k] = encodePeptideOneHot(peptide, max_length=max_x_length) train_data[k] = peptideEncode(peptide, max_length=max_x_length) k = k + 1 #train_data = train_data.reshape(train_data.shape[0], train_data.shape[1], train_data.shape[2]) X_test = np.empty(1) Y_test = np.empty(1) print("RT range: %d - %d\n" % (min_rt,max_rt)) if test_data is None: X_train, X_test, Y_train, Y_test = train_test_split(train_data, #to_categorical(pos_neg_all_data['y'], num_classes=2), minMaxScale(siteData['y'],min_rt,max_rt), test_size=0.1, random_state=100) else: X_train = train_data #Y_train = to_categorical(pos_neg_all_data['y'], num_classes=2) Y_train = siteData['y'] Y_train = minMaxScale(Y_train, min_rt, max_rt) if len(Y_train.shape) >= 2: Y_train = Y_train.reshape(Y_train.shape[1]) #X_test = np.zeros((test_data.shape[0], max_x_length, n_aa_types)) X_test = np.zeros((test_data.shape[0], max_x_length)) k = 0 for i, row in test_data.iterrows(): peptide = row['x'] X_test[k] = peptideEncode(peptide, max_length=max_x_length) k = k + 1 Y_test = minMaxScale(test_data['y'],min_rt,max_rt) X_train = X_train.astype('float32') X_test = X_test.astype('float32') print("X_train shape:") print(X_train.shape) print("X_test shape:") print(X_test.shape) print("Modeling start ...") res['X_train'] = X_train res['Y_train'] = Y_train res['X_test'] = X_test res['Y_test'] = Y_test res['min_rt'] = min_rt res['max_rt'] = max_rt res['max_x_length'] = max_x_length #return [X_train, Y_train, X_test, Y_test, min_rt, max_rt] return res def processing_prediction_data(model_file: str, input_data: str): ''' :param model_file: model file in json format :param input_data: prediction file :return: A numpy matrix for prediction ''' with open(model_file, "r") as read_file: model_list = json.load(read_file) model_folder = os.path.dirname(model_file) aa_file = model_folder + "/" + os.path.basename(model_list['aa']) load_aa(aa_file) ## siteData = pd.read_csv(input_data, sep="\t", header=0, low_memory=False) n_aa_types = len(letterDict) print("AA types: %d" % (n_aa_types)) ## all aa in data all_aa = set() ## get the max length of input sequences max_x_length = model_list['max_x_length'] longest_pep_len = 0 for pep in siteData["x"]: #if max_x_length < len(pep): # max_x_length = len(pep) if longest_pep_len < len(pep): longest_pep_len = len(pep) ## for aa in pep: all_aa.add(aa) print("Longest peptide in input data: %d\n" % (longest_pep_len)) print(sorted(all_aa)) # siteData = siteData.sample(siteData.shape[0], replace=False, random_state=2018) pred_data = np.zeros((siteData.shape[0], max_x_length)) k = 0 for i, row in siteData.iterrows(): peptide = row['x'] # train_data[k] = encodePeptideOneHot(peptide, max_length=max_x_length) pred_data[k] = peptideEncode(peptide, max_length=max_x_length) k = k + 1 pred_data = pred_data.astype('float32') return pred_data def minMaxScale(x, min=0,max=120): new_x = 1.0*(x-min)/(max-min) return new_x def minMaxScoreRev(x,min=0,max=120): old_x = x * (max - min) + min return old_x def encodePeptideOneHot(peptide: str, max_length=None): # changed add one column for '1' AACategoryLen = len(letterDict) peptide_length = len(peptide) use_peptide = peptide if max_length is not None: if peptide_length < max_length: use_peptide = peptide + "X" * (max_length - peptide_length) en_vector = np.zeros((len(use_peptide), AACategoryLen)) i = 0 for AA in use_peptide: if AA in letterDict.keys(): try: en_vector[i][letterDict[AA]] = 1 except: print("peptide: %s, i => aa: %d, %s, %d" % (use_peptide,i, AA, letterDict[AA])) exit(1) else: en_vector[i] = np.full(AACategoryLen,1/AACategoryLen) i = i + 1 return en_vector
[ "numpy.full", "h5py.File", "json.load", "os.path.basename", "pandas.read_csv", "numpy.empty", "os.path.dirname", "numpy.zeros", "matplotlib.use", "pandas.read_table" ]
[((131, 152), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (145, 152), False, 'import matplotlib\n'), ((1315, 1372), 'pandas.read_table', 'pd.read_table', (['file'], {'sep': '"""\t"""', 'header': '(0)', 'low_memory': '(False)'}), "(file, sep='\\t', header=0, low_memory=False)\n", (1328, 1372), True, 'import pandas as pd\n'), ((1838, 1871), 'numpy.zeros', 'np.zeros', (['[max_length]'], {'dtype': 'int'}), '([max_length], dtype=int)\n', (1846, 1871), True, 'import numpy as np\n'), ((2567, 2630), 'pandas.read_table', 'pd.read_table', (['input_data'], {'sep': '"""\t"""', 'header': '(0)', 'low_memory': '(False)'}), "(input_data, sep='\\t', header=0, low_memory=False)\n", (2580, 2630), True, 'import pandas as pd\n'), ((4761, 4804), 'numpy.zeros', 'np.zeros', (['(siteData.shape[0], max_x_length)'], {}), '((siteData.shape[0], max_x_length))\n', (4769, 4804), True, 'import numpy as np\n'), ((5166, 5177), 'numpy.empty', 'np.empty', (['(1)'], {}), '(1)\n', (5174, 5177), True, 'import numpy as np\n'), ((5191, 5202), 'numpy.empty', 'np.empty', (['(1)'], {}), '(1)\n', (5199, 5202), True, 'import numpy as np\n'), ((7162, 7189), 'os.path.dirname', 'os.path.dirname', (['model_file'], {}), '(model_file)\n', (7177, 7189), False, 'import os\n'), ((7304, 7365), 'pandas.read_csv', 'pd.read_csv', (['input_data'], {'sep': '"""\t"""', 'header': '(0)', 'low_memory': '(False)'}), "(input_data, sep='\\t', header=0, low_memory=False)\n", (7315, 7365), True, 'import pandas as pd\n'), ((8044, 8087), 'numpy.zeros', 'np.zeros', (['(siteData.shape[0], max_x_length)'], {}), '((siteData.shape[0], max_x_length))\n', (8052, 8087), True, 'import numpy as np\n'), ((352, 372), 'h5py.File', 'h5py.File', (['path', '"""w"""'], {}), "(path, 'w')\n", (361, 372), False, 'import h5py\n'), ((556, 576), 'h5py.File', 'h5py.File', (['path', '"""r"""'], {}), "(path, 'r')\n", (565, 576), False, 'import h5py\n'), ((3791, 3853), 'pandas.read_table', 'pd.read_table', (['test_file'], {'sep': '"""\t"""', 'header': '(0)', 'low_memory': '(False)'}), "(test_file, sep='\\t', header=0, low_memory=False)\n", (3804, 3853), True, 'import pandas as pd\n'), ((6047, 6091), 'numpy.zeros', 'np.zeros', (['(test_data.shape[0], max_x_length)'], {}), '((test_data.shape[0], max_x_length))\n', (6055, 6091), True, 'import numpy as np\n'), ((7121, 7141), 'json.load', 'json.load', (['read_file'], {}), '(read_file)\n', (7130, 7141), False, 'import json\n'), ((7225, 7259), 'os.path.basename', 'os.path.basename', (["model_list['aa']"], {}), "(model_list['aa'])\n", (7241, 7259), False, 'import os\n'), ((9293, 9334), 'numpy.full', 'np.full', (['AACategoryLen', '(1 / AACategoryLen)'], {}), '(AACategoryLen, 1 / AACategoryLen)\n', (9300, 9334), True, 'import numpy as np\n')]
# Essentials import pandas as pd import numpy as np # Plots import matplotlib.pyplot as plt from tqdm import tqdm # Models from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier, VotingClassifier import xgboost as xgb # Misc from rdkit import Chem from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold from sklearn.feature_selection import SelectKBest, f_classif from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, \ roc_auc_score, precision_recall_curve, average_precision_score from imblearn.pipeline import make_pipeline from imblearn.over_sampling import SMOTENC from collections import Counter import re, requests # Functions import create_fingerprints as cf import create_descriptors as cd def create_original_df(usedf=False, file=None, write_s=False, write_off=False): # Create dataframe from csv if not usedf: df = pd.read_csv("./datasets/sider.csv") else: df = file.copy() # Extract SMILES column df_molecules = pd.DataFrame(df["smiles"]) # Converting to molecules df_molecules["mols"] = df_molecules["smiles"].apply(Chem.MolFromSmiles) # Droping mols and smiles df_y = df.drop("smiles", axis=1) # Write to csv if write_s: df_molecules.to_csv("./dataframes/df_molecules.csv") df_y.to_csv("./dataframes/df_y.csv") if write_off: df_molecules.to_csv("./dataframes/df_off_mols.csv") df_y.to_csv("./dataframes/df_off_y.csv") return df_y, df_molecules def createfingerprints(df_mols, length): # Morgan Fingerprint (ECFP4) ecfp_df = cf.create_ecfp4_fingerprint(df_mols, length, False) # MACCS keys (always 167) maccs_df = cf.create_maccs_fingerprint(df_mols, False) # ATOM PAIRS atom_pairs_df = cf.create_atompairs_fingerprint(df_mols, length, False) # Topological torsion tt_df = cf.create_topological_torsion_fingerprint(df_mols, length, False) return ecfp_df, maccs_df, atom_pairs_df, tt_df def createdescriptors(df_molecules): # Descriptors df_mols_desc = cd.calc_descriptors(df_molecules, False) return df_mols_desc def test_fingerprint_size(df_mols, df_y, model, colname="Hepatobiliary disorders", num_sizes_to_test=20, min_size=100, max_size=2048, cv=10, makeplots=False, write=False): # Fingerprint length type and selection # Scoring metrics to use scoring_metrics = ("f1_micro", "f1_macro", "f1", "roc_auc", "recall", "precision", "average_precision") sizes = np.linspace(min_size, max_size, num_sizes_to_test, dtype=int) # Create results dataframes for each metric results_f1 = np.zeros([4, len(sizes)]) results_rocauc = np.zeros([4, len(sizes)]) results_precision = np.zeros([4, len(sizes)]) results_recall = np.zeros([4, len(sizes)]) results_average_precision = np.zeros([4, len(sizes)]) results_f1_micro = np.zeros([4, len(sizes)]) results_f1_macro = np.zeros([4, len(sizes)]) # Get test sizes c = 0 # Size testing using SVC with scale gamma (1 / (n_features * X.var())) for s in tqdm(sizes): # Create fingerprint with size S fingerprints = createfingerprints(df_mols, int(s)) r = 0 for fp in fingerprints: X = fp.copy() # Using "Hepatobiliary disorders" as an results example since its balanced y = df_y[colname].copy() # 10-fold cross validation cv_scores = cross_validate(model, X, y, cv=cv, scoring=scoring_metrics, return_train_score=False, n_jobs=-1) for k, v in cv_scores.items(): if k == "test_roc_auc": results_rocauc[r, c] = v.mean() if k == "test_precision": results_precision[r, c] = v.mean() if k == "test_recall": results_recall[r, c] = v.mean() if k == "test_average_precision": results_average_precision[r, c] = v.mean() if k == "test_f1": results_f1[r, c] = v.mean() if k == "test_f1_micro": results_f1_micro[r, c] = v.mean() if k == "test_f1_macro": results_f1_macro[r, c] = v.mean() r += 1 c += 1 all_results = (results_rocauc, results_precision, results_recall, results_average_precision, results_f1, results_f1_micro, results_f1_macro) # Create dataframe for results df_results_rocauc_size_SVC = pd.DataFrame(results_rocauc, columns=sizes) df_results_precision_size_SVC = pd.DataFrame(results_precision, columns=sizes) df_results_recall_size_SVC = pd.DataFrame(results_recall, columns=sizes) df_results_av_prec_size_SVC = pd.DataFrame(results_average_precision, columns=sizes) df_results_f1_size_SVC = pd.DataFrame(results_f1, columns=sizes) df_results_f1_micro_size_SVC = pd.DataFrame(results_f1_micro, columns=sizes) df_results_f1_macro_size_SVC = pd.DataFrame(results_f1_macro, columns=sizes) all_df_results = ( df_results_rocauc_size_SVC, df_results_precision_size_SVC, df_results_recall_size_SVC, df_results_av_prec_size_SVC, df_results_f1_size_SVC, df_results_f1_micro_size_SVC, df_results_f1_macro_size_SVC) # Save to file if write: df_results_rocauc_size_SVC.to_csv("./results/df_results_rocauc_size_SVC.csv") df_results_precision_size_SVC.to_csv("./results/df_results_precision_size_SVC.csv") df_results_recall_size_SVC.to_csv("./results/df_results_recall_size_SVC.csv") df_results_av_prec_size_SVC.to_csv("./results/df_results_av_prec_size_SVC.csv") df_results_f1_size_SVC.to_csv("./results/df_results_f1_size_SVC.csv") df_results_f1_micro_size_SVC.to_csv("./results/df_results_f1_micro_size_SVC.csv") df_results_f1_macro_size_SVC.to_csv("./results/df_results_f1_macro_size_SVC.csv") if makeplots: fp_names = ["ECFP-4", "MACCS", "Atom Pairs", "Topological Torsion"] m = 0 for d in all_results: fig = plt.figure(figsize=(10, 10)) for i in range(len(fingerprints)): plt.plot(sizes, d[i, :], "-") plt.title(f"SVC, {scoring_metrics[m]} vs fingerprint length", fontsize=25) plt.ylabel(f"{scoring_metrics[m]}", fontsize=20) plt.xlabel("Fingerprint Length", fontsize=20) plt.legend(fp_names, fontsize=15) plt.ylim([0, 1]) plt.show() m += 1 return all_df_results def select_best_descriptors_multi(df_desc, y_all, out_names=[], score_func=f_classif, k=1): # Select k highest scoring feature from X to every y and return new df with only the selected ones if not out_names: print("Column names necessary") return None selected = [] for n in tqdm(out_names): skb = SelectKBest(score_func=score_func, k=k).fit(df_desc, y_all[n]) n_sel_bol = skb.get_support() sel = df_desc.loc[:, n_sel_bol].columns.to_list() for s in sel: if s not in selected: selected.append(s) return selected def select_best_descriptors(X, y, score_func=f_classif, k=2): # Select k highest scoring feature from X to y with a score function, f_classif by default skb = SelectKBest(score_func=score_func, k=k).fit(X, y) n_sel_bol = skb.get_support() sel = X.loc[:, n_sel_bol].columns.to_list() assert sel return sel def create_dataframes_dic(df_desc_base_train, df_desc_base_test, X_train_fp, X_test_fp, y_train, out_names, score_func=f_classif, k=3): # Create 3 dictionaries, one with the train dataframes, one with the test dataframes and one with the selected # features for each label # Initialize dictonaries train_series_dic = {name: None for name in out_names} test_series_dic = {name: None for name in out_names} selected_name = {name: None for name in out_names} # For each of the tasks build the train and test dataframe with the selected descriptors for name in tqdm(out_names): # Select best descriptors for the task sel_col = select_best_descriptors(df_desc_base_train, y_train[name], score_func=score_func, k=k) selected_name[name] = sel_col # Keep track of selected columns df_desc_train = df_desc_base_train.loc[:, sel_col].copy() # Get train dataframe with only selected columns df_desc_test = df_desc_base_test.loc[:, sel_col].copy() # Get test dataframe with only selected columns X_train = pd.concat([X_train_fp, df_desc_train], axis=1) X_test = pd.concat([X_test_fp, df_desc_test], axis=1) # Add to the dictionary train_series_dic[name] = X_train test_series_dic[name] = X_test # Return the dictionaries return train_series_dic, test_series_dic, selected_name def balance_dataset(X_train_dic, y_train_dic, out_names, random_state=0, n_jobs=-1, verbose=False): # Initialize the dictionaries and boolean array for categorical features train_series_dic_bal = {name: None for name in out_names} y_dic_bal = {name: None for name in out_names} cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # For each classficiation label for label in tqdm(out_names): X_imb = X_train_dic[label] y_imb = y_train_dic[label] X_bal, y_bal = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs).fit_resample( X_imb, y_imb) train_series_dic_bal[label] = X_bal y_dic_bal[label] = y_bal # Print new counts if verbose: for label in out_names: print(f"For {label}") print(sorted(Counter(y_train_dic[label]).items())) print(sorted(Counter(y_dic_bal[label]).items())) # Return the new dictionaries return train_series_dic_bal, y_dic_bal def grid_search(X_train, y_train, model, params_to_test, X_test=None, y_test=None, balancing=False, n_splits=5, scoring="f1", n_jobs=-1, verbose=False, random_state=None): # Define grid search if balancing: # Save index of categorical features cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # Prepatre SMOTENC smotenc = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs) # Make a pipeline with the balancing and the estimator, balacing is only called when fitting pipeline = make_pipeline(smotenc, model) # Determine stratified k folds kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) # Call cross validate grid_search = GridSearchCV(pipeline, params_to_test, cv=kf, n_jobs=n_jobs, verbose=verbose, scoring=scoring) else: kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) grid_search = GridSearchCV(model, params_to_test, cv=kf, n_jobs=n_jobs, verbose=verbose, scoring=scoring) # Fit X and y to test parameters grid_search.fit(X_train, y_train) means = grid_search.cv_results_["mean_test_score"] stds = grid_search.cv_results_["std_test_score"] if verbose: # Print scores print() print("Score for development set:") for mean, std, params in zip(means, stds, grid_search.cv_results_["params"]): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 1.96, params)) print() # Print best parameters print() print("Best parameters set found:") print(grid_search.best_params_) print() if X_test and y_test: # Detailed Classification report print() print("Detailed classification report:") print("The model is trained on the full development set.") print("The scores are computed on the full evaluation set.") print() y_true, y_pred = y_test, grid_search.predict(X_test) print(classification_report(y_true, y_pred)) print() print("Confusion Matrix as") print(""" TN FP FN TP """) print(confusion_matrix(y_true, y_pred)) # Save best estimator best_estimator = grid_search.best_estimator_ best_params = grid_search.best_params_ # And return it return best_params, best_estimator def multi_label_grid_search(X_train_dic, y_train, out_names, model, params_to_test, balancing=False, X_test=None, y_test=None, n_splits=5, scoring="f1", n_jobs=-1, verbose=False, random_state=None): # Creates a dictionary with the best params in regards to chosen metric for each label # Creates the dictionary best_params_by_label = {label: None for label in out_names} # If X_test and y_test is given so that generalization evalutation can happen if X_test and y_test: for label in tqdm(out_names): print() print(f"Scores for {label}") best_params, _ = grid_search(X_train_dic[label], y_train[label], model, params_to_test[label], X_test[label], y_test[label], n_splits=n_splits, scoring=scoring, verbose=verbose, n_jobs=n_jobs, balancing=balancing, random_state=random_state) best_params_by_label[label] = best_params else: for label in tqdm(out_names): print() print(f"Scores for {label}") best_params, _ = grid_search(X_train_dic[label], y_train[label], model, params_to_test[label], n_splits=n_splits, scoring=scoring, verbose=verbose, n_jobs=n_jobs, balancing=balancing, random_state=random_state) best_params_by_label[label] = best_params return best_params_by_label def random_search(X_train, y_train, model, params_to_test, X_test=None, y_test=None, balancing=False, n_iter=100, n_splits=5, scoring="f1", n_jobs=-1, verbose=False, random_state=None): # Define random search if balancing: # Save index of categorical features cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # Prepatre SMOTENC smotenc = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs) # Make a pipeline with the balancing and the estimator, balacing is only called when fitting pipeline = make_pipeline(smotenc, model) # Determine stratified k folds kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) # Call cross validate rs = RandomizedSearchCV(pipeline, params_to_test, n_iter=n_iter, cv=kf, n_jobs=n_jobs, verbose=verbose, scoring=scoring) else: kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) rs = RandomizedSearchCV(model, params_to_test, n_iter=n_iter, cv=kf, n_jobs=n_jobs, verbose=verbose, scoring=scoring) # Fit parameters rs.fit(np.asarray(X_train), np.asarray(y_train)) means = rs.cv_results_["mean_test_score"] stds = rs.cv_results_["std_test_score"] # Print scores if verbose: print() print("Score for development set:") for mean, std, params in zip(means, stds, rs.cv_results_["params"]): print("%0.3f (+/-%0.03f) for %r" % (mean, std * 1.96, params)) print() # Print best parameters print() print("Best parameters set found:") print(rs.best_params_) print() if X_test and y_test: # Detailed Classification report print() print("Detailed classification report:") print("The model is trained on the full development set.") print("The scores are computed on the full evaluation set.") print() y_true, y_pred = y_test, rs.predict(X_test) print(classification_report(y_true, y_pred)) print() """ print("Confusion matrix as:") print( TN FP FN TP ) print(confusion_matrix(y_true, y_pred)) print() """ # Save best estimator best_estimator = rs.best_estimator_ best_params = rs.best_params_ # And return it return best_params, best_estimator def multi_label_random_search(X_train_dic, y_train, out_names, model, params_to_test, balancing=False, X_test=None, y_test=None, n_iter=100, n_splits=5, scoring="f1", n_jobs=-1, verbose=False, random_state=None): # Creates a dictionary with the best params in regards to chosen metric for each label # Creates the dictionary best_params_by_label = {label: None for label in out_names} # If X_test and y_test is given so that generalization evalutation can happen if X_test and y_test: for label in tqdm(out_names): print() print(f"Scores for {label}") best_params, _ = random_search(X_train_dic[label], y_train[label], model, params_to_test[label], X_test[label], y_test[label], n_iter=n_iter, n_splits=n_splits, scoring=scoring, verbose=verbose, n_jobs=n_jobs, random_state=random_state, balancing=balancing) best_params_by_label[label] = best_params else: for label in tqdm(out_names): print() print(f"Scores for {label}") best_params, _ = random_search(X_train_dic[label], y_train[label], model, params_to_test[label], n_iter=n_iter, n_splits=n_splits, scoring=scoring, verbose=verbose, n_jobs=n_jobs, random_state=random_state, balancing=balancing) best_params_by_label[label] = best_params return best_params_by_label def score_report(estimator, X_test, y_test, verbose=False, plot=False, name=None): # Predicting value y_true, y_pred = y_test, estimator.predict(X_test) y_score = estimator.predict_proba(X_test) y_score = y_score[:, 1] # Individual metrics f1_micr_score = f1_score(y_true, y_pred, average="micro") f1_macro_score = f1_score(y_true, y_pred, average="macro") f1_s_score = f1_score(y_true, y_pred, average="binary") auc = roc_auc_score(y_true, y_pred) rec = recall_score(y_true, y_pred, average="binary") prec = precision_score(y_true, y_pred, average="binary") average_precision = average_precision_score(y_true, y_score) # Detailed Classification report if verbose: print() print("The scores are computed on the full evaluation set") print("These are not used to train or optimize the model") print() print("Detailed classification report:") print(classification_report(y_true, y_pred)) print() print("Confusion matrix as:") print(""" TN FP FN TP """) print(confusion_matrix(y_true, y_pred)) print() print("Individual metrics:") print(f"F1 Micro score: {f1_micr_score:.3f}") print(f"F1 Macro score: {f1_macro_score:.3f}") print(f"F1 Binary score: {f1_s_score:.3f}") print(f"AUROC score: {auc:.3f}") print(f"Recall score: {rec:.3f}") print(f"Precision score: {prec:.3f}") print(f"Average precision-recall score: {average_precision:.3f}") print() if plot: precision, recall, _ = precision_recall_curve(y_true, y_score) # step_kwargs = ({'step': 'post'} # if 'step' in signature(plt.fill_between).parameters # else {}) plt.step(recall, precision, color="r", alpha=0.2, where="post") plt.fill_between(recall, precision, step="post", alpha=0.2, color="#F59B00") plt.xlabel("Recall") plt.ylabel("Precision") plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title(f'{name} \n Precision-Recall curve: AP={average_precision:0.2f}') plt.savefig(f"./results/{name} Precision-Recall curve.png") plt.clf() return {"f1_micr_score": f1_micr_score, "auc_score": auc, "rec_score": rec, "prec_score": prec, "f1_macro_score": f1_macro_score, "f1_s_score": f1_s_score, "prec_rec_score": average_precision} def cv_report(estimator, X_train, y_train, balancing=False, n_splits=5, scoring_metrics=("f1_micro", "f1_macro", "f1", "roc_auc", "recall", "precision", "average_precision"), random_state=None, n_jobs=-1, verbose=False): if balancing: # Save index of categorical features cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # Prepare SMOTENC smotenc = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs) # Make a pipeline with the balancing and the estimator, balacing is only called when fitting pipeline = make_pipeline(smotenc, estimator) # Determine stratified k folds kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) # Call cross validate scores = cross_validate(pipeline, np.asarray(X_train), np.asarray(y_train), scoring=scoring_metrics, cv=kf, n_jobs=n_jobs, verbose=verbose, return_train_score=False) else: # Normal cross validation kf = StratifiedKFold(n_splits=n_splits, random_state=random_state) scores = cross_validate(estimator, np.asarray(X_train), np.asarray(y_train), scoring=scoring_metrics, cv=kf, n_jobs=n_jobs, verbose=verbose, return_train_score=False) # Means f1_s = np.mean(scores["test_f1_micro"]) f1_ms = np.mean(scores["test_f1_macro"]) f1_bs = np.mean(scores["test_f1"]) auc_s = np.mean(scores["test_roc_auc"]) rec_s = np.mean(scores["test_recall"]) prec_s = np.mean(scores["test_precision"]) avp_s = np.mean(scores["test_average_precision"]) # STD f1_std = np.std(scores["test_f1_micro"]) f1_mstd = np.std(scores["test_f1_macro"]) f1_bstd = np.std(scores["test_f1"]) auc_std = np.std(scores["test_roc_auc"]) rec_std = np.std(scores["test_recall"]) prec_std = np.std(scores["test_precision"]) avp_std = np.std(scores["test_average_precision"]) if verbose: print() print("Individual metrics") print(f"F1 Micro Score: Mean: {f1_s:.3f} (Std: {f1_std:.3f})") print(f"F1 Macro Score: Mean: {f1_ms:.3f} (Std: {f1_mstd:.3f})") print(f"F1 Binary Score: Mean: {f1_bs:.3f} (Std: {f1_bstd:.3f})") print(f"AUROC score: Mean: {auc_s:.3f} (Std: {auc_std:.3f})") print(f"Recall score: Mean: {rec_s:.3f} (Std: {rec_std:.3f})") print(f"Precision score: Mean: {prec_s:.3f} (Std: {prec_std:.3f})") print(f"Average Precision score: Mean: {avp_s:.3f} (Std: {avp_std:.3f})") print() return {"f1_micr_score": f1_s, "f1_micr_std": f1_std, "auc_score": auc_s, "auc_std": auc_std, "rec_score": rec_s, "rec_std": rec_std, "prec_score": prec_s, "prec_std": prec_std, "f1_macro_score": f1_ms, "f1_macro_std": f1_mstd, "f1_score": f1_bs, "f1_std": f1_bstd, "avp_score": avp_s, "avp_std": avp_std} def cv_multi_report(X_train_dic, y_train, out_names, model=None, balancing=False, modelname=None, spec_params=None, random_state=None, n_splits=5, n_jobs=-1, verbose=False): # Creates a scores report dataframe for each classification label with cv # Initizalize the dataframe report = pd.DataFrame( columns=["F1 Binary", "F1 Micro", "F1 Macro", "ROC_AUC", "Recall", "Precision", "Average Precision"], index=out_names) scoring_metrics = ("f1_micro", "f1_macro", "f1", "roc_auc", "recall", "precision", "average_precision") # For each label for name in tqdm(out_names): if verbose: print() print(f"Scores for {name}") # Calculate the score for the current label using the respective dataframe if spec_params: # Define the specific parameters for each model for each label if modelname[name] == "SVC": model_temp = SVC(random_state=random_state, probability=True) model_temp.set_params(C=spec_params[name]["svc__C"], gamma=spec_params[name]["svc__gamma"], kernel=spec_params[name]["svc__kernel"]) elif modelname[name] == "RF": model_temp = RandomForestClassifier(n_estimators=100, random_state=random_state) model_temp.set_params(bootstrap=spec_params[name]["randomforestclassifier__bootstrap"], max_depth=spec_params[name]["randomforestclassifier__max_depth"], max_features=spec_params[name]["randomforestclassifier__max_features"], min_samples_leaf=spec_params[name]["randomforestclassifier__min_samples_leaf"], min_samples_split=spec_params[name]["randomforestclassifier__min_samples_split"], n_estimators=spec_params[name]["randomforestclassifier__n_estimators"]) elif modelname[name] == "XGB": model_temp = xgb.XGBClassifier(objective="binary:logistic", random_state=random_state) model_temp.set_params(colsample_bytree=spec_params[name]["xgbclassifier__colsample_bytree"], eta=spec_params[name]["xgbclassifier__eta"], gamma=spec_params[name]["xgbclassifier__gamma"], max_depth=spec_params[name]["xgbclassifier__max_depth"], min_child_weight=spec_params[name]["xgbclassifier__min_child_weight"], subsample=spec_params[name]["xgbclassifier__subsample"]) elif modelname[name] == "VotingClassifier": # Spec params must be the list of the dictionaries with the params in order (SVC - RF - XGB) model_svc = SVC(random_state=random_state, probability=True) model_rf = RandomForestClassifier(n_estimators=100, random_state=random_state) model_xgb = xgb.XGBClassifier(objective="binary:logistic", random_state=random_state) model_svc.set_params(C=spec_params[0][name]["svc__C"], gamma=spec_params[0][name]["svc__gamma"], kernel=spec_params[0][name]["svc__kernel"]) model_rf.set_params(bootstrap=spec_params[1][name]["randomforestclassifier__bootstrap"], max_depth=spec_params[1][name]["randomforestclassifier__max_depth"], max_features=spec_params[1][name]["randomforestclassifier__max_features"], min_samples_leaf=spec_params[1][name]["randomforestclassifier__min_samples_leaf"], min_samples_split=spec_params[1][name]["randomforestclassifier__min_samples_split"], n_estimators=spec_params[1][name]["randomforestclassifier__n_estimators"]) model_xgb.set_params(colsample_bytree=spec_params[2][name]["xgbclassifier__colsample_bytree"], eta=spec_params[2][name]["xgbclassifier__eta"], gamma=spec_params[2][name]["xgbclassifier__gamma"], max_depth=spec_params[2][name]["xgbclassifier__max_depth"], min_child_weight=spec_params[2][name]["xgbclassifier__min_child_weight"], subsample=spec_params[2][name]["xgbclassifier__subsample"]) model_temp = VotingClassifier(estimators=[("svc", model_svc), ("rf", model_rf), ("xgb", model_xgb)], voting="soft", n_jobs=n_jobs) else: print("Please specify used model (SVC, RF, XGB)") return None scores = cv_report(model_temp, X_train_dic[name], y_train[name], balancing=balancing, n_splits=n_splits, scoring_metrics=scoring_metrics, n_jobs=n_jobs, verbose=verbose, random_state=random_state) else: scores = cv_report(model, X_train_dic[name], y_train[name], balancing=balancing, n_splits=n_splits, scoring_metrics=scoring_metrics, n_jobs=n_jobs, verbose=verbose, random_state=random_state) report.loc[name, "F1 Micro"] = round(float(scores["f1_micr_score"]), 3) report.loc[name, "F1 Macro"] = round(float(scores["f1_macro_score"]), 3) report.loc[name, "F1 Binary"] = round(float(scores["f1_score"]), 3) report.loc[name, "ROC_AUC"] = round(float(scores["auc_score"]), 3) report.loc[name, "Recall"] = round(float(scores["rec_score"]), 3) report.loc[name, "Precision"] = round(float(scores["prec_score"]), 3) report.loc[name, "Average Precision"] = round(float(scores["avp_score"]), 3) report = report.apply(pd.to_numeric) return report def test_score_multi_report(X_train_dic, y_train, X_test, y_test, out_names, model=None, modelname=None, spec_params=None, balancing=False, random_state=None, plot=False, verbose=False, n_jobs=-1): # Creates a scores report dataframe for each classification label with cv # Initizalize the dataframe report = pd.DataFrame(columns=["F1 Binary", "F1 Micro", "F1 Macro", "ROC_AUC", "Recall", "Precision"], index=out_names) # For each label for name in tqdm(out_names): if verbose: print() print(f"Scores for {name}") # Calculate the score for the current label using the respective dataframe if spec_params: # Define the specific parameters for each model for each label if modelname[name] == "SVC": model_temp = SVC(random_state=random_state, probability=True) model_temp.set_params(C=spec_params[name]["svc__C"], gamma=spec_params[name]["svc__gamma"], kernel=spec_params[name]["svc__kernel"]) elif modelname[name] == "RF": model_temp = RandomForestClassifier(n_estimators=100, random_state=random_state) model_temp.set_params(bootstrap=spec_params[name]["randomforestclassifier__bootstrap"], max_depth=spec_params[name]["randomforestclassifier__max_depth"], max_features=spec_params[name]["randomforestclassifier__max_features"], min_samples_leaf=spec_params[name]["randomforestclassifier__min_samples_leaf"], min_samples_split=spec_params[name]["randomforestclassifier__min_samples_split"], n_estimators=spec_params[name]["randomforestclassifier__n_estimators"]) elif modelname[name] == "XGB": model_temp = xgb.XGBClassifier(objective="binary:logistic", random_state=random_state) model_temp.set_params(colsample_bytree=spec_params[name]["xgbclassifier__colsample_bytree"], eta=spec_params[name]["xgbclassifier__eta"], gamma=spec_params[name]["xgbclassifier__gamma"], max_depth=spec_params[name]["xgbclassifier__max_depth"], min_child_weight=spec_params[name]["xgbclassifier__min_child_weight"], subsample=spec_params[name]["xgbclassifier__subsample"]) else: print("Please specify used model (SVC, RF, XGB)") return None if balancing: # Save index of categorical features cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # Prepatre SMOTENC smotenc = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs) # Make a pipeline with the balancing and the estimator, balacing is only called when fitting pipeline = make_pipeline(smotenc, model_temp) # Fit and test pipeline.fit(np.asarray(X_train_dic[name]), np.asarray(y_train[name])) scores = score_report(pipeline, np.asarray(X_test[name]), np.asarray(y_test[name]), plot=plot, verbose=verbose, name=name) else: model_temp.fit(np.asarray(X_train_dic[name]), np.asarray(y_train[name])) scores = score_report(model_temp, np.asarray(X_test[name]), np.asarray(y_test[name]), plot=plot, verbose=verbose, name=name) else: if balancing: # Save index of categorical features cat_shape = np.full((1128,), True, dtype=bool) cat_shape[-3:] = False # Prepatre SMOTENC smotenc = SMOTENC(categorical_features=cat_shape, random_state=random_state, n_jobs=n_jobs) # Make a pipeline with the balancing and the estimator, balacing is only called when fitting pipeline = make_pipeline(smotenc, model) # Fit and test pipeline.fit(np.asarray(X_train_dic[name]), np.asarray(y_train[name])) scores = score_report(pipeline, np.asarray(X_test[name]), np.asarray(y_test[name]), plot=plot, verbose=verbose, name=name) else: model.fit(np.asarray(X_train_dic[name]), np.asarray(y_train[name])) scores = score_report(model, np.asarray(X_test[name]), np.asarray(y_test[name]), plot=plot, verbose=verbose, name=name) report.loc[name, "F1 Micro"] = round(float(scores["f1_micr_score"]), 3) report.loc[name, "F1 Macro"] = round(float(scores["f1_macro_score"]), 3) report.loc[name, "F1 Binary"] = round(float(scores["f1_s_score"]), 3) report.loc[name, "ROC_AUC"] = round(float(scores["auc_score"]), 3) report.loc[name, "Recall"] = round(float(scores["rec_score"]), 3) report.loc[name, "Precision"] = round(float(scores["prec_score"]), 3) report.loc[name, "Average Prec-Rec"] = round(float(scores["prec_rec_score"]), 3) # prec_rec_score report = report.apply(pd.to_numeric) return report def get_smile_from_cid(cid): # Trim CID ct = re.sub("^CID[0]*", "", cid) # Getting smile res = requests.get(f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{ct}/property/CanonicalSMILES/txt") # Checking for Error 400 try: res.raise_for_status() except Exception as e: print(f"Problem retrieving smile for {cid}: {e}") # If everything is ok, get smile text res_t = res.text.strip("\n") # Return smile return res_t def create_offside_df(out_names, write=False): oss = pd.read_csv("./datasets/offsides_socs.csv") oss_df = oss[["stitch_id", "SOC"]].copy() stitchs = oss_df.stitch_id.unique() sti_to_smil = {stitch: get_smile_from_cid(stitch) for stitch in tqdm(stitchs)} d = {"stitch_id": stitchs} mod_off = pd.DataFrame(data=d) mod_off["smiles"] = mod_off.stitch_id.apply(lambda x: sti_to_smil[x]) for name in out_names: mod_off[name] = 0 for index, row in tqdm(oss_df.iterrows()): if row["SOC"] in out_names: mod_off.loc[mod_off["stitch_id"] == row["stitch_id"], row["SOC"]] = 1 mod_off.drop("stitch_id", inplace=True, axis=1) if write: mod_off.to_csv("./datasets/offside_socs_modified.csv", index=False) return mod_off
[ "matplotlib.pyplot.title", "sklearn.model_selection.GridSearchCV", "matplotlib.pyplot.clf", "pandas.read_csv", "sklearn.model_selection.cross_validate", "create_fingerprints.create_topological_torsion_fingerprint", "sklearn.metrics.classification_report", "matplotlib.pyplot.step", "sklearn.metrics.f...
[((1099, 1125), 'pandas.DataFrame', 'pd.DataFrame', (["df['smiles']"], {}), "(df['smiles'])\n", (1111, 1125), True, 'import pandas as pd\n'), ((1692, 1743), 'create_fingerprints.create_ecfp4_fingerprint', 'cf.create_ecfp4_fingerprint', (['df_mols', 'length', '(False)'], {}), '(df_mols, length, False)\n', (1719, 1743), True, 'import create_fingerprints as cf\n'), ((1790, 1833), 'create_fingerprints.create_maccs_fingerprint', 'cf.create_maccs_fingerprint', (['df_mols', '(False)'], {}), '(df_mols, False)\n', (1817, 1833), True, 'import create_fingerprints as cf\n'), ((1872, 1927), 'create_fingerprints.create_atompairs_fingerprint', 'cf.create_atompairs_fingerprint', (['df_mols', 'length', '(False)'], {}), '(df_mols, length, False)\n', (1903, 1927), True, 'import create_fingerprints as cf\n'), ((1967, 2032), 'create_fingerprints.create_topological_torsion_fingerprint', 'cf.create_topological_torsion_fingerprint', (['df_mols', 'length', '(False)'], {}), '(df_mols, length, False)\n', (2008, 2032), True, 'import create_fingerprints as cf\n'), ((2161, 2201), 'create_descriptors.calc_descriptors', 'cd.calc_descriptors', (['df_molecules', '(False)'], {}), '(df_molecules, False)\n', (2180, 2201), True, 'import create_descriptors as cd\n'), ((2620, 2681), 'numpy.linspace', 'np.linspace', (['min_size', 'max_size', 'num_sizes_to_test'], {'dtype': 'int'}), '(min_size, max_size, num_sizes_to_test, dtype=int)\n', (2631, 2681), True, 'import numpy as np\n'), ((3194, 3205), 'tqdm.tqdm', 'tqdm', (['sizes'], {}), '(sizes)\n', (3198, 3205), False, 'from tqdm import tqdm\n'), ((4641, 4684), 'pandas.DataFrame', 'pd.DataFrame', (['results_rocauc'], {'columns': 'sizes'}), '(results_rocauc, columns=sizes)\n', (4653, 4684), True, 'import pandas as pd\n'), ((4721, 4767), 'pandas.DataFrame', 'pd.DataFrame', (['results_precision'], {'columns': 'sizes'}), '(results_precision, columns=sizes)\n', (4733, 4767), True, 'import pandas as pd\n'), ((4801, 4844), 'pandas.DataFrame', 'pd.DataFrame', (['results_recall'], {'columns': 'sizes'}), '(results_recall, columns=sizes)\n', (4813, 4844), True, 'import pandas as pd\n'), ((4879, 4933), 'pandas.DataFrame', 'pd.DataFrame', (['results_average_precision'], {'columns': 'sizes'}), '(results_average_precision, columns=sizes)\n', (4891, 4933), True, 'import pandas as pd\n'), ((4963, 5002), 'pandas.DataFrame', 'pd.DataFrame', (['results_f1'], {'columns': 'sizes'}), '(results_f1, columns=sizes)\n', (4975, 5002), True, 'import pandas as pd\n'), ((5038, 5083), 'pandas.DataFrame', 'pd.DataFrame', (['results_f1_micro'], {'columns': 'sizes'}), '(results_f1_micro, columns=sizes)\n', (5050, 5083), True, 'import pandas as pd\n'), ((5119, 5164), 'pandas.DataFrame', 'pd.DataFrame', (['results_f1_macro'], {'columns': 'sizes'}), '(results_f1_macro, columns=sizes)\n', (5131, 5164), True, 'import pandas as pd\n'), ((6988, 7003), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (6992, 7003), False, 'from tqdm import tqdm\n'), ((8239, 8254), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (8243, 8254), False, 'from tqdm import tqdm\n'), ((9347, 9381), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (9354, 9381), True, 'import numpy as np\n'), ((9463, 9478), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (9467, 9478), False, 'from tqdm import tqdm\n'), ((18648, 18689), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred'], {'average': '"""micro"""'}), "(y_true, y_pred, average='micro')\n", (18656, 18689), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18711, 18752), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred'], {'average': '"""macro"""'}), "(y_true, y_pred, average='macro')\n", (18719, 18752), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18770, 18812), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (18778, 18812), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18823, 18852), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (18836, 18852), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18863, 18909), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (18875, 18909), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18921, 18970), 'sklearn.metrics.precision_score', 'precision_score', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (18936, 18970), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((18995, 19035), 'sklearn.metrics.average_precision_score', 'average_precision_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (19018, 19035), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((22257, 22289), 'numpy.mean', 'np.mean', (["scores['test_f1_micro']"], {}), "(scores['test_f1_micro'])\n", (22264, 22289), True, 'import numpy as np\n'), ((22302, 22334), 'numpy.mean', 'np.mean', (["scores['test_f1_macro']"], {}), "(scores['test_f1_macro'])\n", (22309, 22334), True, 'import numpy as np\n'), ((22347, 22373), 'numpy.mean', 'np.mean', (["scores['test_f1']"], {}), "(scores['test_f1'])\n", (22354, 22373), True, 'import numpy as np\n'), ((22386, 22417), 'numpy.mean', 'np.mean', (["scores['test_roc_auc']"], {}), "(scores['test_roc_auc'])\n", (22393, 22417), True, 'import numpy as np\n'), ((22430, 22460), 'numpy.mean', 'np.mean', (["scores['test_recall']"], {}), "(scores['test_recall'])\n", (22437, 22460), True, 'import numpy as np\n'), ((22474, 22507), 'numpy.mean', 'np.mean', (["scores['test_precision']"], {}), "(scores['test_precision'])\n", (22481, 22507), True, 'import numpy as np\n'), ((22520, 22561), 'numpy.mean', 'np.mean', (["scores['test_average_precision']"], {}), "(scores['test_average_precision'])\n", (22527, 22561), True, 'import numpy as np\n'), ((22586, 22617), 'numpy.std', 'np.std', (["scores['test_f1_micro']"], {}), "(scores['test_f1_micro'])\n", (22592, 22617), True, 'import numpy as np\n'), ((22632, 22663), 'numpy.std', 'np.std', (["scores['test_f1_macro']"], {}), "(scores['test_f1_macro'])\n", (22638, 22663), True, 'import numpy as np\n'), ((22678, 22703), 'numpy.std', 'np.std', (["scores['test_f1']"], {}), "(scores['test_f1'])\n", (22684, 22703), True, 'import numpy as np\n'), ((22718, 22748), 'numpy.std', 'np.std', (["scores['test_roc_auc']"], {}), "(scores['test_roc_auc'])\n", (22724, 22748), True, 'import numpy as np\n'), ((22763, 22792), 'numpy.std', 'np.std', (["scores['test_recall']"], {}), "(scores['test_recall'])\n", (22769, 22792), True, 'import numpy as np\n'), ((22808, 22840), 'numpy.std', 'np.std', (["scores['test_precision']"], {}), "(scores['test_precision'])\n", (22814, 22840), True, 'import numpy as np\n'), ((22855, 22895), 'numpy.std', 'np.std', (["scores['test_average_precision']"], {}), "(scores['test_average_precision'])\n", (22861, 22895), True, 'import numpy as np\n'), ((24152, 24287), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['F1 Binary', 'F1 Micro', 'F1 Macro', 'ROC_AUC', 'Recall', 'Precision',\n 'Average Precision']", 'index': 'out_names'}), "(columns=['F1 Binary', 'F1 Micro', 'F1 Macro', 'ROC_AUC',\n 'Recall', 'Precision', 'Average Precision'], index=out_names)\n", (24164, 24287), True, 'import pandas as pd\n'), ((24447, 24462), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (24451, 24462), False, 'from tqdm import tqdm\n'), ((30349, 30463), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['F1 Binary', 'F1 Micro', 'F1 Macro', 'ROC_AUC', 'Recall', 'Precision']", 'index': 'out_names'}), "(columns=['F1 Binary', 'F1 Micro', 'F1 Macro', 'ROC_AUC',\n 'Recall', 'Precision'], index=out_names)\n", (30361, 30463), True, 'import pandas as pd\n'), ((30524, 30539), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (30528, 30539), False, 'from tqdm import tqdm\n'), ((35639, 35666), 're.sub', 're.sub', (['"""^CID[0]*"""', '""""""', 'cid'], {}), "('^CID[0]*', '', cid)\n", (35645, 35666), False, 'import re, requests\n'), ((35698, 35813), 'requests.get', 'requests.get', (['f"""https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{ct}/property/CanonicalSMILES/txt"""'], {}), "(\n f'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{ct}/property/CanonicalSMILES/txt'\n )\n", (35710, 35813), False, 'import re, requests\n'), ((36131, 36174), 'pandas.read_csv', 'pd.read_csv', (['"""./datasets/offsides_socs.csv"""'], {}), "('./datasets/offsides_socs.csv')\n", (36142, 36174), True, 'import pandas as pd\n'), ((36391, 36411), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (36403, 36411), True, 'import pandas as pd\n'), ((980, 1015), 'pandas.read_csv', 'pd.read_csv', (['"""./datasets/sider.csv"""'], {}), "('./datasets/sider.csv')\n", (991, 1015), True, 'import pandas as pd\n'), ((8727, 8773), 'pandas.concat', 'pd.concat', (['[X_train_fp, df_desc_train]'], {'axis': '(1)'}), '([X_train_fp, df_desc_train], axis=1)\n', (8736, 8773), True, 'import pandas as pd\n'), ((8791, 8835), 'pandas.concat', 'pd.concat', (['[X_test_fp, df_desc_test]'], {'axis': '(1)'}), '([X_test_fp, df_desc_test], axis=1)\n', (8800, 8835), True, 'import pandas as pd\n'), ((10378, 10412), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (10385, 10412), True, 'import numpy as np\n'), ((10489, 10575), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (10496, 10575), False, 'from imblearn.over_sampling import SMOTENC\n'), ((10691, 10720), 'imblearn.pipeline.make_pipeline', 'make_pipeline', (['smotenc', 'model'], {}), '(smotenc, model)\n', (10704, 10720), False, 'from imblearn.pipeline import make_pipeline\n'), ((10773, 10834), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (10788, 10834), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((10887, 10986), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['pipeline', 'params_to_test'], {'cv': 'kf', 'n_jobs': 'n_jobs', 'verbose': 'verbose', 'scoring': 'scoring'}), '(pipeline, params_to_test, cv=kf, n_jobs=n_jobs, verbose=\n verbose, scoring=scoring)\n', (10899, 10986), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((11006, 11067), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (11021, 11067), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((11090, 11185), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['model', 'params_to_test'], {'cv': 'kf', 'n_jobs': 'n_jobs', 'verbose': 'verbose', 'scoring': 'scoring'}), '(model, params_to_test, cv=kf, n_jobs=n_jobs, verbose=verbose,\n scoring=scoring)\n', (11102, 11185), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((13135, 13150), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (13139, 13150), False, 'from tqdm import tqdm\n'), ((13633, 13648), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (13637, 13648), False, 'from tqdm import tqdm\n'), ((14419, 14453), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (14426, 14453), True, 'import numpy as np\n'), ((14530, 14616), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (14537, 14616), False, 'from imblearn.over_sampling import SMOTENC\n'), ((14732, 14761), 'imblearn.pipeline.make_pipeline', 'make_pipeline', (['smotenc', 'model'], {}), '(smotenc, model)\n', (14745, 14761), False, 'from imblearn.pipeline import make_pipeline\n'), ((14814, 14875), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (14829, 14875), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((14919, 15039), 'sklearn.model_selection.RandomizedSearchCV', 'RandomizedSearchCV', (['pipeline', 'params_to_test'], {'n_iter': 'n_iter', 'cv': 'kf', 'n_jobs': 'n_jobs', 'verbose': 'verbose', 'scoring': 'scoring'}), '(pipeline, params_to_test, n_iter=n_iter, cv=kf, n_jobs=\n n_jobs, verbose=verbose, scoring=scoring)\n', (14937, 15039), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((15091, 15152), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (15106, 15152), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((15166, 15283), 'sklearn.model_selection.RandomizedSearchCV', 'RandomizedSearchCV', (['model', 'params_to_test'], {'n_iter': 'n_iter', 'cv': 'kf', 'n_jobs': 'n_jobs', 'verbose': 'verbose', 'scoring': 'scoring'}), '(model, params_to_test, n_iter=n_iter, cv=kf, n_jobs=\n n_jobs, verbose=verbose, scoring=scoring)\n', (15184, 15283), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((15344, 15363), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (15354, 15363), True, 'import numpy as np\n'), ((15365, 15384), 'numpy.asarray', 'np.asarray', (['y_train'], {}), '(y_train)\n', (15375, 15384), True, 'import numpy as np\n'), ((17312, 17327), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (17316, 17327), False, 'from tqdm import tqdm\n'), ((17874, 17889), 'tqdm.tqdm', 'tqdm', (['out_names'], {}), '(out_names)\n', (17878, 17889), False, 'from tqdm import tqdm\n'), ((20021, 20060), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (20043, 20060), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((20224, 20287), 'matplotlib.pyplot.step', 'plt.step', (['recall', 'precision'], {'color': '"""r"""', 'alpha': '(0.2)', 'where': '"""post"""'}), "(recall, precision, color='r', alpha=0.2, where='post')\n", (20232, 20287), True, 'import matplotlib.pyplot as plt\n'), ((20296, 20372), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['recall', 'precision'], {'step': '"""post"""', 'alpha': '(0.2)', 'color': '"""#F59B00"""'}), "(recall, precision, step='post', alpha=0.2, color='#F59B00')\n", (20312, 20372), True, 'import matplotlib.pyplot as plt\n'), ((20382, 20402), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Recall"""'], {}), "('Recall')\n", (20392, 20402), True, 'import matplotlib.pyplot as plt\n'), ((20411, 20434), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Precision"""'], {}), "('Precision')\n", (20421, 20434), True, 'import matplotlib.pyplot as plt\n'), ((20443, 20464), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.05]'], {}), '([0.0, 1.05])\n', (20451, 20464), True, 'import matplotlib.pyplot as plt\n'), ((20473, 20493), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (20481, 20493), True, 'import matplotlib.pyplot as plt\n'), ((20502, 20580), 'matplotlib.pyplot.title', 'plt.title', (['f"""{name} \n Precision-Recall curve: AP={average_precision:0.2f}"""'], {}), '(f"""{name} \n Precision-Recall curve: AP={average_precision:0.2f}""")\n', (20511, 20580), True, 'import matplotlib.pyplot as plt\n'), ((20587, 20646), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""./results/{name} Precision-Recall curve.png"""'], {}), "(f'./results/{name} Precision-Recall curve.png')\n", (20598, 20646), True, 'import matplotlib.pyplot as plt\n'), ((20655, 20664), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (20662, 20664), True, 'import matplotlib.pyplot as plt\n'), ((21210, 21244), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (21217, 21244), True, 'import numpy as np\n'), ((21320, 21406), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (21327, 21406), False, 'from imblearn.over_sampling import SMOTENC\n'), ((21522, 21555), 'imblearn.pipeline.make_pipeline', 'make_pipeline', (['smotenc', 'estimator'], {}), '(smotenc, estimator)\n', (21535, 21555), False, 'from imblearn.pipeline import make_pipeline\n'), ((21608, 21669), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (21623, 21669), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((21964, 22025), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'n_splits', 'random_state': 'random_state'}), '(n_splits=n_splits, random_state=random_state)\n', (21979, 22025), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((3566, 3666), 'sklearn.model_selection.cross_validate', 'cross_validate', (['model', 'X', 'y'], {'cv': 'cv', 'scoring': 'scoring_metrics', 'return_train_score': '(False)', 'n_jobs': '(-1)'}), '(model, X, y, cv=cv, scoring=scoring_metrics,\n return_train_score=False, n_jobs=-1)\n', (3580, 3666), False, 'from sklearn.model_selection import GridSearchCV, cross_validate, RandomizedSearchCV, StratifiedKFold\n'), ((6206, 6234), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10)'}), '(figsize=(10, 10))\n', (6216, 6234), True, 'import matplotlib.pyplot as plt\n'), ((6340, 6414), 'matplotlib.pyplot.title', 'plt.title', (['f"""SVC, {scoring_metrics[m]} vs fingerprint length"""'], {'fontsize': '(25)'}), "(f'SVC, {scoring_metrics[m]} vs fingerprint length', fontsize=25)\n", (6349, 6414), True, 'import matplotlib.pyplot as plt\n'), ((6427, 6475), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""{scoring_metrics[m]}"""'], {'fontsize': '(20)'}), "(f'{scoring_metrics[m]}', fontsize=20)\n", (6437, 6475), True, 'import matplotlib.pyplot as plt\n'), ((6488, 6533), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Fingerprint Length"""'], {'fontsize': '(20)'}), "('Fingerprint Length', fontsize=20)\n", (6498, 6533), True, 'import matplotlib.pyplot as plt\n'), ((6546, 6579), 'matplotlib.pyplot.legend', 'plt.legend', (['fp_names'], {'fontsize': '(15)'}), '(fp_names, fontsize=15)\n', (6556, 6579), True, 'import matplotlib.pyplot as plt\n'), ((6592, 6608), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (6600, 6608), True, 'import matplotlib.pyplot as plt\n'), ((6621, 6631), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6629, 6631), True, 'import matplotlib.pyplot as plt\n'), ((7458, 7497), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'score_func': 'score_func', 'k': 'k'}), '(score_func=score_func, k=k)\n', (7469, 7497), False, 'from sklearn.feature_selection import SelectKBest, f_classif\n'), ((19320, 19357), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (19341, 19357), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((19508, 19540), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (19524, 19540), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((21742, 21761), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (21752, 21761), True, 'import numpy as np\n'), ((21763, 21782), 'numpy.asarray', 'np.asarray', (['y_train'], {}), '(y_train)\n', (21773, 21782), True, 'import numpy as np\n'), ((22069, 22088), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (22079, 22088), True, 'import numpy as np\n'), ((22090, 22109), 'numpy.asarray', 'np.asarray', (['y_train'], {}), '(y_train)\n', (22100, 22109), True, 'import numpy as np\n'), ((36330, 36343), 'tqdm.tqdm', 'tqdm', (['stitchs'], {}), '(stitchs)\n', (36334, 36343), False, 'from tqdm import tqdm\n'), ((6298, 6327), 'matplotlib.pyplot.plot', 'plt.plot', (['sizes', 'd[i, :]', '"""-"""'], {}), "(sizes, d[i, :], '-')\n", (6306, 6327), True, 'import matplotlib.pyplot as plt\n'), ((7019, 7058), 'sklearn.feature_selection.SelectKBest', 'SelectKBest', ([], {'score_func': 'score_func', 'k': 'k'}), '(score_func=score_func, k=k)\n', (7030, 7058), False, 'from sklearn.feature_selection import SelectKBest, f_classif\n'), ((9573, 9659), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (9580, 9659), False, 'from imblearn.over_sampling import SMOTENC\n'), ((12187, 12224), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (12208, 12224), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((12380, 12412), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (12396, 12412), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((16268, 16305), 'sklearn.metrics.classification_report', 'classification_report', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (16289, 16305), False, 'from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve, average_precision_score\n'), ((24796, 24844), 'sklearn.svm.SVC', 'SVC', ([], {'random_state': 'random_state', 'probability': '(True)'}), '(random_state=random_state, probability=True)\n', (24799, 24844), False, 'from sklearn.svm import SVC\n'), ((30873, 30921), 'sklearn.svm.SVC', 'SVC', ([], {'random_state': 'random_state', 'probability': '(True)'}), '(random_state=random_state, probability=True)\n', (30876, 30921), False, 'from sklearn.svm import SVC\n'), ((32896, 32930), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (32903, 32930), True, 'import numpy as np\n'), ((33031, 33117), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (33038, 33117), False, 'from imblearn.over_sampling import SMOTENC\n'), ((33249, 33283), 'imblearn.pipeline.make_pipeline', 'make_pipeline', (['smotenc', 'model_temp'], {}), '(smotenc, model_temp)\n', (33262, 33283), False, 'from imblearn.pipeline import make_pipeline\n'), ((33988, 34022), 'numpy.full', 'np.full', (['(1128,)', '(True)'], {'dtype': 'bool'}), '((1128,), True, dtype=bool)\n', (33995, 34022), True, 'import numpy as np\n'), ((34123, 34209), 'imblearn.over_sampling.SMOTENC', 'SMOTENC', ([], {'categorical_features': 'cat_shape', 'random_state': 'random_state', 'n_jobs': 'n_jobs'}), '(categorical_features=cat_shape, random_state=random_state, n_jobs=\n n_jobs)\n', (34130, 34209), False, 'from imblearn.over_sampling import SMOTENC\n'), ((34342, 34371), 'imblearn.pipeline.make_pipeline', 'make_pipeline', (['smotenc', 'model'], {}), '(smotenc, model)\n', (34355, 34371), False, 'from imblearn.pipeline import make_pipeline\n'), ((25141, 25208), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'random_state': 'random_state'}), '(n_estimators=100, random_state=random_state)\n', (25163, 25208), False, 'from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n'), ((31218, 31285), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'random_state': 'random_state'}), '(n_estimators=100, random_state=random_state)\n', (31240, 31285), False, 'from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n'), ((33344, 33373), 'numpy.asarray', 'np.asarray', (['X_train_dic[name]'], {}), '(X_train_dic[name])\n', (33354, 33373), True, 'import numpy as np\n'), ((33375, 33400), 'numpy.asarray', 'np.asarray', (['y_train[name]'], {}), '(y_train[name])\n', (33385, 33400), True, 'import numpy as np\n'), ((33450, 33474), 'numpy.asarray', 'np.asarray', (['X_test[name]'], {}), '(X_test[name])\n', (33460, 33474), True, 'import numpy as np\n'), ((33476, 33500), 'numpy.asarray', 'np.asarray', (['y_test[name]'], {}), '(y_test[name])\n', (33486, 33500), True, 'import numpy as np\n'), ((33629, 33658), 'numpy.asarray', 'np.asarray', (['X_train_dic[name]'], {}), '(X_train_dic[name])\n', (33639, 33658), True, 'import numpy as np\n'), ((33660, 33685), 'numpy.asarray', 'np.asarray', (['y_train[name]'], {}), '(y_train[name])\n', (33670, 33685), True, 'import numpy as np\n'), ((33737, 33761), 'numpy.asarray', 'np.asarray', (['X_test[name]'], {}), '(X_test[name])\n', (33747, 33761), True, 'import numpy as np\n'), ((33763, 33787), 'numpy.asarray', 'np.asarray', (['y_test[name]'], {}), '(y_test[name])\n', (33773, 33787), True, 'import numpy as np\n'), ((34432, 34461), 'numpy.asarray', 'np.asarray', (['X_train_dic[name]'], {}), '(X_train_dic[name])\n', (34442, 34461), True, 'import numpy as np\n'), ((34463, 34488), 'numpy.asarray', 'np.asarray', (['y_train[name]'], {}), '(y_train[name])\n', (34473, 34488), True, 'import numpy as np\n'), ((34538, 34562), 'numpy.asarray', 'np.asarray', (['X_test[name]'], {}), '(X_test[name])\n', (34548, 34562), True, 'import numpy as np\n'), ((34564, 34588), 'numpy.asarray', 'np.asarray', (['y_test[name]'], {}), '(y_test[name])\n', (34574, 34588), True, 'import numpy as np\n'), ((34712, 34741), 'numpy.asarray', 'np.asarray', (['X_train_dic[name]'], {}), '(X_train_dic[name])\n', (34722, 34741), True, 'import numpy as np\n'), ((34743, 34768), 'numpy.asarray', 'np.asarray', (['y_train[name]'], {}), '(y_train[name])\n', (34753, 34768), True, 'import numpy as np\n'), ((34815, 34839), 'numpy.asarray', 'np.asarray', (['X_test[name]'], {}), '(X_test[name])\n', (34825, 34839), True, 'import numpy as np\n'), ((34841, 34865), 'numpy.asarray', 'np.asarray', (['y_test[name]'], {}), '(y_test[name])\n', (34851, 34865), True, 'import numpy as np\n'), ((25947, 26020), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {'objective': '"""binary:logistic"""', 'random_state': 'random_state'}), "(objective='binary:logistic', random_state=random_state)\n", (25964, 26020), True, 'import xgboost as xgb\n'), ((32024, 32097), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {'objective': '"""binary:logistic"""', 'random_state': 'random_state'}), "(objective='binary:logistic', random_state=random_state)\n", (32041, 32097), True, 'import xgboost as xgb\n'), ((9903, 9930), 'collections.Counter', 'Counter', (['y_train_dic[label]'], {}), '(y_train_dic[label])\n', (9910, 9930), False, 'from collections import Counter\n'), ((9966, 9991), 'collections.Counter', 'Counter', (['y_dic_bal[label]'], {}), '(y_dic_bal[label])\n', (9973, 9991), False, 'from collections import Counter\n'), ((26792, 26840), 'sklearn.svm.SVC', 'SVC', ([], {'random_state': 'random_state', 'probability': '(True)'}), '(random_state=random_state, probability=True)\n', (26795, 26840), False, 'from sklearn.svm import SVC\n'), ((26868, 26935), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(100)', 'random_state': 'random_state'}), '(n_estimators=100, random_state=random_state)\n', (26890, 26935), False, 'from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n'), ((26964, 27037), 'xgboost.XGBClassifier', 'xgb.XGBClassifier', ([], {'objective': '"""binary:logistic"""', 'random_state': 'random_state'}), "(objective='binary:logistic', random_state=random_state)\n", (26981, 27037), True, 'import xgboost as xgb\n'), ((28562, 28683), 'sklearn.ensemble.VotingClassifier', 'VotingClassifier', ([], {'estimators': "[('svc', model_svc), ('rf', model_rf), ('xgb', model_xgb)]", 'voting': '"""soft"""', 'n_jobs': 'n_jobs'}), "(estimators=[('svc', model_svc), ('rf', model_rf), ('xgb',\n model_xgb)], voting='soft', n_jobs=n_jobs)\n", (28578, 28683), False, 'from sklearn.ensemble import RandomForestClassifier, VotingClassifier\n')]
import json import base64 import collections import numpy as np from copy import deepcopy from ..arc import arc_center from ..entities import Line, Arc, Bezier from ...constants import log, tol from ...constants import res_path as res from ... import util from ... import grouping from ... import resources from ... import exceptions from ...util import jsonify from ...transformations import transform_points, planar_matrix try: # pip install svg.path from svg.path import parse_path except BaseException as E: # will re-raise the import exception when # someone tries to call `parse_path` parse_path = exceptions.closure(E) try: from lxml import etree except BaseException as E: # will re-raise the import exception when # someone actually tries to use the module etree = exceptions.ExceptionModule(E) # store any additional properties using a trimesh namespace _ns_name = 'trimesh' _ns_url = 'https://github.com/mikedh/trimesh' _ns = '{{{}}}'.format(_ns_url) def svg_to_path(file_obj, file_type=None): """ Load an SVG file into a Path2D object. Parameters ----------- file_obj : open file object Contains SVG data file_type: None Not used Returns ----------- loaded : dict With kwargs for Path2D constructor """ def element_transform(e, max_depth=10): """ Find a transformation matrix for an XML element. Parameters -------------- e : lxml.etree.Element Element to search upwards from. max_depth : int Maximum depth to search for transforms. """ matrices = [] current = e for i in range(max_depth): if 'transform' in current.attrib: matrices.extend(transform_to_matrices( current.attrib['transform'])) current = current.getparent() if current is None: break if len(matrices) == 0: return np.eye(3) elif len(matrices) == 1: return matrices[0] else: return util.multi_dot(matrices[::-1]) # first parse the XML tree = etree.fromstring(file_obj.read()) # store paths and transforms as # (path string, 3x3 matrix) paths = [] for element in tree.iter('{*}path'): # store every path element attributes and transform paths.append((element.attrib, element_transform(element))) try: # see if the SVG should be reproduced as a scene force = tree.attrib[_ns + 'class'] except BaseException: force = None result = _svg_path_convert(paths=paths, force=force) try: # get overall metadata from JSON string if it exists result['metadata'] = _decode( tree.attrib[_ns + 'metadata']) except KeyError: # not in the trimesh ns pass except BaseException: # no metadata stored with trimesh ns log.warning('failed metadata', exc_info=True) # if the result is a scene try to get the metadata # for each subgeometry here if 'geometry' in result: try: # get per-geometry metadata if available bag = _decode( tree.attrib[_ns + 'metadata_geometry']) for name, meta in bag.items(): if name in result['geometry']: # assign this metadata to the geometry result['geometry'][name]['metadata'] = meta except KeyError: # no stored geometry metadata so ignore pass except BaseException: # failed to load existing metadata log.warning('failed metadata', exc_info=True) return result def transform_to_matrices(transform): """ Convert an SVG transform string to an array of matrices. i.e. "rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)" Parameters ----------- transform : str Contains transformation information in SVG form Returns ----------- matrices : (n, 3, 3) float Multiple transformation matrices from input transform string """ # split the transform string in to components of: # (operation, args) i.e. (translate, '-1.0, 2.0') components = [ [j.strip() for j in i.strip().split('(') if len(j) > 0] for i in transform.lower().split(')') if len(i) > 0] # store each matrix without dotting matrices = [] for line in components: if len(line) == 0: continue elif len(line) != 2: raise ValueError('should always have two components!') key, args = line # convert string args to array of floats # support either comma or space delimiter values = np.array([float(i) for i in args.replace(',', ' ').split()]) if key == 'translate': # convert translation to a (3, 3) homogeneous matrix matrices.append(np.eye(3)) matrices[-1][:2, 2] = values elif key == 'matrix': # [a b c d e f] -> # [[a c e], # [b d f], # [0 0 1]] matrices.append(np.vstack(( values.reshape((3, 2)).T, [0, 0, 1]))) elif key == 'rotate': # SVG rotations are in degrees angle = np.degrees(values[0]) # if there are three values rotate around point if len(values) == 3: point = values[1:] else: point = None matrices.append(planar_matrix(theta=angle, point=point)) elif key == 'scale': # supports (x_scale, y_scale) or (scale) mat = np.eye(3) mat[:2, :2] *= values matrices.append(mat) else: log.warning('unknown SVG transform: {}'.format(key)) return matrices def _svg_path_convert(paths, force=None): """ Convert an SVG path string into a Path2D object Parameters ------------- paths: list of tuples Containing (path string, (3, 3) matrix, metadata) Returns ------------- drawing : dict Kwargs for Path2D constructor """ def complex_to_float(values): return np.array([[i.real, i.imag] for i in values], dtype=np.float64) def load_multi(multi): # load a previously parsed multiline return (Line(points=np.arange(len(multi.points)) + counts[name]), multi.points) def load_arc(svg_arc): # load an SVG arc into a trimesh arc points = complex_to_float([svg_arc.start, svg_arc.point(0.5), svg_arc.end]) return Arc(points=np.arange(3) + counts[name]), points def load_quadratic(svg_quadratic): # load a quadratic bezier spline points = complex_to_float([svg_quadratic.start, svg_quadratic.control, svg_quadratic.end]) return Bezier(points=np.arange(3) + counts[name]), points def load_cubic(svg_cubic): # load a cubic bezier spline points = complex_to_float([svg_cubic.start, svg_cubic.control1, svg_cubic.control2, svg_cubic.end]) return Bezier(np.arange(4) + counts[name]), points class MultiLine(object): # An object to hold one or multiple Line entities. def __init__(self, lines): if tol.strict: # in unit tests make sure we only have lines assert all(type(L).__name__ in ('Line', 'Close') for L in lines) # get the starting point of every line points = [L.start for L in lines] # append the endpoint points.append(lines[-1].end) # convert to (n, 2) float points self.points = np.array([[i.real, i.imag] for i in points], dtype=np.float64) # load functions for each entity loaders = {'Arc': load_arc, 'MultiLine': load_multi, 'CubicBezier': load_cubic, 'QuadraticBezier': load_quadratic} entities = collections.defaultdict(list) vertices = collections.defaultdict(list) counts = collections.defaultdict(lambda: 0) for attrib, matrix in paths: # the path string is stored under `d` path_string = attrib.get('d', '') if len(path_string) == 0: log.warning('empty path string!') continue # get the name of the geometry if trimesh specified it # note that the get will by default return `None` name = _decode(attrib.get(_ns + 'name')) # get parsed entities from svg.path raw = np.array(list(parse_path(path_string))) # if there is no path string exit if len(raw) == 0: continue # check to see if each entity is "line-like" is_line = np.array([type(i).__name__ in ('Line', 'Close') for i in raw]) # find groups of consecutive lines so we can combine them blocks = grouping.blocks( is_line, min_len=1, only_nonzero=False) if tol.strict: # in unit tests make sure we didn't lose any entities assert np.allclose(np.hstack(blocks), np.arange(len(raw))) # Combine consecutive lines into a single MultiLine parsed = [] for b in blocks: if type(raw[b[0]]).__name__ in ('Line', 'Close'): # if entity consists of lines add a multiline parsed.append(MultiLine(raw[b])) else: # otherwise just add the entities parsed.extend(raw[b]) try: # try to retrieve any trimesh attributes as metadata entity_meta = { k.lstrip(_ns): _decode(v) for k, v in attrib.items() if k[1:].startswith(_ns_url)} except BaseException: entity_meta = {} # loop through parsed entity objects for svg_entity in parsed: # keyed by entity class name type_name = type(svg_entity).__name__ if type_name in loaders: # get new entities and vertices e, v = loaders[type_name](svg_entity) e.metadata.update(entity_meta) # append them to the result entities[name].append(e) # transform the vertices by the matrix and append vertices[name].append(transform_points(v, matrix)) counts[name] += len(v) geoms = {name: {'vertices': np.vstack(v), 'entities': entities[name]} for name, v in vertices.items()} if len(geoms) > 1 or force == 'Scene': kwargs = {'geometry': geoms} else: # return a Path2D kwargs = next(iter(geoms.values())) return kwargs def _entities_to_str(entities, vertices, name=None, only_layers=None): """ Convert the entities of a path to path strings. Parameters ------------ entities : (n,) list Entity objects vertices : (m, 2) float Vertices entities reference name : any Trimesh namespace name to assign to entity only_layers : set Only export these layers if passed """ points = vertices.copy() def circle_to_svgpath(center, radius, reverse): c = 'M {x},{y} a {r},{r},0,1,0,{d},0 a {r},{r},0,1,{rev},-{d},0 Z' fmt = '{{:{}}}'.format(res.export) return c.format(x=fmt.format(center[0] - radius), y=fmt.format(center[1]), r=fmt.format(radius), d=fmt.format(2.0 * radius), rev=int(bool(reverse))) def svg_arc(arc, reverse=False): """ arc string: (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ large-arc-flag: greater than 180 degrees sweep flag: direction (cw/ccw) """ arc_idx = arc.points[::((reverse * -2) + 1)] vertices = points[arc_idx] vertex_start, vertex_mid, vertex_end = vertices center_info = arc_center( vertices, return_normal=False, return_angle=True) C, R, angle = (center_info['center'], center_info['radius'], center_info['span']) if arc.closed: return circle_to_svgpath(C, R, reverse) large_flag = str(int(angle > np.pi)) sweep_flag = str(int(np.cross( vertex_mid - vertex_start, vertex_end - vertex_start) > 0.0)) return (move_to(arc_idx[0]) + 'A {R},{R} 0 {}, {} {},{}'.format( large_flag, sweep_flag, vertex_end[0], vertex_end[1], R=R)) def move_to(vertex_id): x_ex = format(points[vertex_id][0], res.export) y_ex = format(points[vertex_id][1], res.export) move_str = 'M ' + x_ex + ',' + y_ex return move_str def svg_discrete(entity, reverse=False): """ Use an entities discrete representation to export a curve as a polyline """ discrete = entity.discrete(points) # if entity contains no geometry return if len(discrete) == 0: return '' # are we reversing the entity if reverse: discrete = discrete[::-1] # the format string for the SVG path result = ('M {:0.5f},{:0.5f} ' + ( ' L {:0.5f},{:0.5f}' * (len(discrete) - 1))).format( *discrete.reshape(-1)) return result # tuples of (metadata, path string) pairs = [] for entity in entities: if only_layers is not None and entity.layer not in only_layers: continue # the class name of the entity etype = entity.__class__.__name__ if etype == 'Arc': # export the exact version of the entity path_string = svg_arc(entity) else: # just export the polyline version of the entity path_string = svg_discrete(entity) meta = deepcopy(entity.metadata) if name is not None: meta['name'] = name pairs.append((meta, path_string)) return pairs def export_svg(drawing, return_path=False, only_layers=None, **kwargs): """ Export a Path2D object into an SVG file. Parameters ----------- drawing : Path2D Source geometry return_path : bool If True return only path string not wrapped in XML Returns ----------- as_svg : str XML formatted SVG, or path string """ # collect custom attributes for the overall export attribs = {'class': type(drawing).__name__} if util.is_instance_named(drawing, 'Scene'): pairs = [] geom_meta = {} for name, geom in drawing.geometry.items(): if not util.is_instance_named(geom, 'Path2D'): continue geom_meta[name] = geom.metadata # a pair of (metadata, path string) pairs.extend(_entities_to_str( entities=geom.entities, vertices=geom.vertices, name=name, only_layers=only_layers)) if len(geom_meta) > 0: # encode the whole metadata bundle here to avoid # polluting the file with a ton of loose attribs attribs['metadata_geometry'] = _encode(geom_meta) elif util.is_instance_named(drawing, 'Path2D'): pairs = _entities_to_str( entities=drawing.entities, vertices=drawing.vertices, only_layers=only_layers) else: raise ValueError('drawing must be Scene or Path2D object!') # return path string without XML wrapping if return_path: return ' '.join(v[1] for v in pairs) # fetch the export template for the base SVG file template_svg = resources.get('templates/base.svg') elements = [] for meta, path_string in pairs: # create a simple path element elements.append('<path d="{d}" {attr}/>'.format( d=path_string, attr=_format_attrib(meta))) # format as XML if 'stroke_width' in kwargs: stroke_width = float(kwargs['stroke_width']) else: # set stroke to something OK looking stroke_width = drawing.extents.max() / 800.0 try: # store metadata in XML as JSON -_- attribs['metadata'] = _encode(drawing.metadata) except BaseException: # log failed metadata encoding log.warning('failed to encode', exc_info=True) subs = {'elements': '\n'.join(elements), 'min_x': drawing.bounds[0][0], 'min_y': drawing.bounds[0][1], 'width': drawing.extents[0], 'height': drawing.extents[1], 'stroke_width': stroke_width, 'attribs': _format_attrib(attribs)} return template_svg.format(**subs) def _format_attrib(attrib): """ Format attribs into the trimesh namespace. Parameters ----------- attrib : dict Bag of keys and values. """ bag = {k: _encode(v) for k, v in attrib.items()} return '\n'.join('{ns}:{key}="{value}"'.format( ns=_ns_name, key=k, value=v) for k, v in bag.items() if len(k) > 0 and v is not None and len(v) > 0) def _encode(stuff): """ Wangle things into a string. Parameters ----------- stuff : dict, str Thing to pack Returns ------------ encoded : str Packaged into url-safe b64 string """ if util.is_string(stuff) and '"' not in stuff: return stuff pack = base64.urlsafe_b64encode(jsonify( stuff, separators=(',', ':')).encode('utf-8')) result = 'base64,' + util.decode_text(pack) if tol.strict: # make sure we haven't broken the things _deep_same(stuff, _decode(result)) return result def _deep_same(original, other): """ Do a recursive comparison of two items to check our encoding scheme in unit tests. Parameters ----------- original : str, bytes, list, dict Original item other : str, bytes, list, dict Item that should be identical Raises ------------ AssertionError If items are not the same. """ # ndarrays will be converted to lists # but otherwise types should be identical if isinstance(original, np.ndarray): assert isinstance(other, (list, np.ndarray)) elif util.is_string(original): # handle python 2+3 unicode vs str assert util.is_string(other) else: # otherwise they should be the same type assert isinstance(original, type(other)) if isinstance(original, (str, bytes)): # string and bytes should just be identical assert original == other return elif isinstance(original, (float, int, np.ndarray)): # for numeric classes use numpy magic comparison # which includes an epsilon for floating point assert np.allclose(original, other) return elif isinstance(original, list): # lengths should match assert len(original) == len(other) # every element should be identical for a, b in zip(original, other): _deep_same(a, b) return # we should have special-cased everything else by here assert isinstance(original, dict) # all keys should match assert set(original.keys()) == set(other.keys()) # do a recursive comparison of the values for k in original.keys(): _deep_same(original[k], other[k]) def _decode(bag): """ Decode a base64 bag of stuff. Parameters ------------ bag : str Starts with `base64,` Returns ------------- loaded : dict Loaded bag of stuff """ if bag is None: return text = util.decode_text(bag) if text.startswith('base64,'): return json.loads(base64.urlsafe_b64decode( text[7:].encode('utf-8')).decode('utf-8')) return text
[ "copy.deepcopy", "numpy.degrees", "numpy.allclose", "numpy.cross", "numpy.hstack", "collections.defaultdict", "numpy.array", "numpy.arange", "svg.path.parse_path", "numpy.eye", "numpy.vstack" ]
[((8515, 8544), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (8538, 8544), False, 'import collections\n'), ((8560, 8589), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (8583, 8589), False, 'import collections\n'), ((8603, 8638), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : 0)'], {}), '(lambda : 0)\n', (8626, 8638), False, 'import collections\n'), ((6389, 6451), 'numpy.array', 'np.array', (['[[i.real, i.imag] for i in values]'], {'dtype': 'np.float64'}), '([[i.real, i.imag] for i in values], dtype=np.float64)\n', (6397, 6451), True, 'import numpy as np\n'), ((14728, 14753), 'copy.deepcopy', 'deepcopy', (['entity.metadata'], {}), '(entity.metadata)\n', (14736, 14753), False, 'from copy import deepcopy\n'), ((2012, 2021), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (2018, 2021), True, 'import numpy as np\n'), ((8163, 8225), 'numpy.array', 'np.array', (['[[i.real, i.imag] for i in points]'], {'dtype': 'np.float64'}), '([[i.real, i.imag] for i in points], dtype=np.float64)\n', (8171, 8225), True, 'import numpy as np\n'), ((11081, 11093), 'numpy.vstack', 'np.vstack', (['v'], {}), '(v)\n', (11090, 11093), True, 'import numpy as np\n'), ((19744, 19772), 'numpy.allclose', 'np.allclose', (['original', 'other'], {}), '(original, other)\n', (19755, 19772), True, 'import numpy as np\n'), ((5068, 5077), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (5074, 5077), True, 'import numpy as np\n'), ((9104, 9127), 'svg.path.parse_path', 'parse_path', (['path_string'], {}), '(path_string)\n', (9114, 9127), False, 'from svg.path import parse_path\n'), ((9682, 9699), 'numpy.hstack', 'np.hstack', (['blocks'], {}), '(blocks)\n', (9691, 9699), True, 'import numpy as np\n'), ((5441, 5462), 'numpy.degrees', 'np.degrees', (['values[0]'], {}), '(values[0])\n', (5451, 5462), True, 'import numpy as np\n'), ((7563, 7575), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (7572, 7575), True, 'import numpy as np\n'), ((13044, 13106), 'numpy.cross', 'np.cross', (['(vertex_mid - vertex_start)', '(vertex_end - vertex_start)'], {}), '(vertex_mid - vertex_start, vertex_end - vertex_start)\n', (13052, 13106), True, 'import numpy as np\n'), ((5849, 5858), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (5855, 5858), True, 'import numpy as np\n'), ((6906, 6918), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (6915, 6918), True, 'import numpy as np\n'), ((7222, 7234), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (7231, 7234), True, 'import numpy as np\n')]
import unittest import shutil import numpy as np from magnificat import cadence class TestLSSTCadence(unittest.TestCase): """Tests for LSSTCadence class """ @classmethod def setUpClass(cls): cls.out_dir = 'obs_testing' def test_get_pointings(self): """Test input and output shapes of get_pointings """ cadence_obj = cadence.LSSTCadence(self.out_dir) ra, dec = cadence_obj.get_pointings(100) np.testing.assert_equal(len(ra), 100) np.testing.assert_equal(len(dec), 100) def test_seeding(self): """Test seeding """ # Run 0 cadence_obj = cadence.LSSTCadence(self.out_dir) ra0, dec0 = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra0, dec0) cadence_obj.bin_by_day() n_pointings_0 = cadence_obj.n_pointings obs_mask_0 = cadence_obj.get_observed_mask() # Run 1 cadence_obj = cadence.LSSTCadence(self.out_dir) ra1, dec1 = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra1, dec1) cadence_obj.bin_by_day() n_pointings_1 = cadence_obj.n_pointings obs_mask_1 = cadence_obj.get_observed_mask() np.testing.assert_array_equal(ra0, ra1) np.testing.assert_array_equal(dec0, dec1) np.testing.assert_array_equal(n_pointings_0, n_pointings_1) np.testing.assert_array_equal(obs_mask_0, obs_mask_1) def test_get_obs_info(self): """Test queried visits of get_obs_info """ cadence_obj = cadence.LSSTCadence(self.out_dir) ra, dec = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra, dec, skip_ddf=True) # Final n_pointings should be <= requested 100 # if there were DDF pointings assert cadence_obj.n_pointings <= 100 for p in range(cadence_obj.n_pointings): # Number of visits should be < 1500 if DDF was skipped mjd = cadence_obj.get_mjd_single_pointing(p, rounded=False) assert len(mjd) < 1500 def test_get_mjd_single_pointing(self): """Test `get_mjd_single_pointing` """ cadence_obj = cadence.LSSTCadence(self.out_dir) ra, dec = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra, dec, skip_ddf=True) mjd = cadence_obj.get_mjd_single_pointing(0, rounded=True) assert mjd.dtype is np.dtype(np.int64) assert np.min(mjd) >= 0 assert np.max(mjd) <= 3649 def test_get_mask_single_pointing(self): """Test `get_mask_single_pointing` """ cadence_obj = cadence.LSSTCadence(self.out_dir) ra, dec = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra, dec, skip_ddf=True) mjd = cadence_obj.get_mjd_single_pointing(0, rounded=True) T = len(mjd) mask = cadence_obj.get_mask_single_pointing(0) np.testing.assert_equal(mask.shape, [T, 6]) assert mask.dtype is np.dtype(bool) def test_bin_by_day(self): """Test `bin_by_day` """ cadence_obj = cadence.LSSTCadence(self.out_dir) ra, dec = cadence_obj.get_pointings(100) cadence_obj.get_obs_info(ra, dec, skip_ddf=True) cadence_obj.bin_by_day() obs_mask = cadence_obj.get_observed_mask() assert obs_mask.dtype is np.dtype(bool) trimmed_mjd = cadence_obj.get_trimmed_mjd() trimmed_T = len(trimmed_mjd) assert trimmed_T == sum(obs_mask) trimmed_mask = cadence_obj.get_trimmed_mask(0) np.testing.assert_equal(trimmed_mask.shape, [trimmed_T, 6]) assert trimmed_mask.dtype is np.dtype(bool) @classmethod def tearDownClass(cls): shutil.rmtree(cls.out_dir) if __name__ == '__main__': unittest.main()
[ "unittest.main", "magnificat.cadence.LSSTCadence", "numpy.testing.assert_array_equal", "numpy.dtype", "numpy.min", "numpy.max", "numpy.testing.assert_equal", "shutil.rmtree" ]
[((3796, 3811), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3809, 3811), False, 'import unittest\n'), ((372, 405), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (391, 405), False, 'from magnificat import cadence\n'), ((651, 684), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (670, 684), False, 'from magnificat import cadence\n'), ((953, 986), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (972, 986), False, 'from magnificat import cadence\n'), ((1224, 1263), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['ra0', 'ra1'], {}), '(ra0, ra1)\n', (1253, 1263), True, 'import numpy as np\n'), ((1272, 1313), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['dec0', 'dec1'], {}), '(dec0, dec1)\n', (1301, 1313), True, 'import numpy as np\n'), ((1322, 1381), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['n_pointings_0', 'n_pointings_1'], {}), '(n_pointings_0, n_pointings_1)\n', (1351, 1381), True, 'import numpy as np\n'), ((1390, 1443), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['obs_mask_0', 'obs_mask_1'], {}), '(obs_mask_0, obs_mask_1)\n', (1419, 1443), True, 'import numpy as np\n'), ((1560, 1593), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (1579, 1593), False, 'from magnificat import cadence\n'), ((2184, 2217), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (2203, 2217), False, 'from magnificat import cadence\n'), ((2629, 2662), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (2648, 2662), False, 'from magnificat import cadence\n'), ((2920, 2963), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['mask.shape', '[T, 6]'], {}), '(mask.shape, [T, 6])\n', (2943, 2963), True, 'import numpy as np\n'), ((3104, 3137), 'magnificat.cadence.LSSTCadence', 'cadence.LSSTCadence', (['self.out_dir'], {}), '(self.out_dir)\n', (3123, 3137), False, 'from magnificat import cadence\n'), ((3570, 3629), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['trimmed_mask.shape', '[trimmed_T, 6]'], {}), '(trimmed_mask.shape, [trimmed_T, 6])\n', (3593, 3629), True, 'import numpy as np\n'), ((3736, 3762), 'shutil.rmtree', 'shutil.rmtree', (['cls.out_dir'], {}), '(cls.out_dir)\n', (3749, 3762), False, 'import shutil\n'), ((2419, 2437), 'numpy.dtype', 'np.dtype', (['np.int64'], {}), '(np.int64)\n', (2427, 2437), True, 'import numpy as np\n'), ((2453, 2464), 'numpy.min', 'np.min', (['mjd'], {}), '(mjd)\n', (2459, 2464), True, 'import numpy as np\n'), ((2485, 2496), 'numpy.max', 'np.max', (['mjd'], {}), '(mjd)\n', (2491, 2496), True, 'import numpy as np\n'), ((2993, 3007), 'numpy.dtype', 'np.dtype', (['bool'], {}), '(bool)\n', (3001, 3007), True, 'import numpy as np\n'), ((3361, 3375), 'numpy.dtype', 'np.dtype', (['bool'], {}), '(bool)\n', (3369, 3375), True, 'import numpy as np\n'), ((3667, 3681), 'numpy.dtype', 'np.dtype', (['bool'], {}), '(bool)\n', (3675, 3681), True, 'import numpy as np\n')]
import numpy as np import sklearn import sklearn.metrics class Evaluator(object): def __init__(self, metric='auc'): if metric == 'auc': self.metric = auc_score elif metric == 'acc': self.metric = acc_score def calculate(self, y_true, y_pred): return self.metric(y_true, y_pred) def auc_score(y_true, y_pred, positive_label=1): if hasattr(sklearn.metrics, 'roc_auc_score'): return sklearn.metrics.roc_auc_score(y_true, y_pred) fp_rate, tp_rate, thresholds = sklearn.metrics.roc_curve( y_true, y_pred, pos_label=positive_label) return sklearn.metrics.auc(fp_rate, tp_rate) def acc_score(y_true, y_pred, positive_label=1): if hasattr(sklearn.metrics, 'accuracy_score'): return sklearn.metrics.accuracy_score(y_true, y_pred) return float(np.sum(y_true == y_pred)) / y_true.shape[0]
[ "numpy.sum", "sklearn.metrics.roc_curve", "sklearn.metrics.accuracy_score", "sklearn.metrics.roc_auc_score", "sklearn.metrics.auc" ]
[((537, 604), 'sklearn.metrics.roc_curve', 'sklearn.metrics.roc_curve', (['y_true', 'y_pred'], {'pos_label': 'positive_label'}), '(y_true, y_pred, pos_label=positive_label)\n', (562, 604), False, 'import sklearn\n'), ((625, 662), 'sklearn.metrics.auc', 'sklearn.metrics.auc', (['fp_rate', 'tp_rate'], {}), '(fp_rate, tp_rate)\n', (644, 662), False, 'import sklearn\n'), ((455, 500), 'sklearn.metrics.roc_auc_score', 'sklearn.metrics.roc_auc_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (484, 500), False, 'import sklearn\n'), ((780, 826), 'sklearn.metrics.accuracy_score', 'sklearn.metrics.accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (810, 826), False, 'import sklearn\n'), ((845, 869), 'numpy.sum', 'np.sum', (['(y_true == y_pred)'], {}), '(y_true == y_pred)\n', (851, 869), True, 'import numpy as np\n')]
import multiprocessing as mp import numpy as np import statsmodels.api as sm from sklearn.metrics import roc_auc_score def bootstrap(args, out_q): outdict = {} mean = [] std = [] c68 = [] boot = [] if 'name' not in args: args['name'] = '' if 'n' not in args: args['n'] = 100 if 'kde' not in args: args['kde'] = False if 'mean' not in args: args['mean'] = False if 'std' not in args: args['std'] = False if 'c68' not in args: args['c68'] = False for i in range(args['n']): points = np.random.choice(args['data'], len(args['data']), replace=True) if args['kde']: kde = sm.nonparametric.KDEUnivariate(points) kde.fit() boot.append([kde.evaluate(x) for x in args['x']]) if args['mean']: mean.append(points.mean()) if args['std']: std.append(points.std()) if args['c68']: c68.append(np.percentile(np.abs(points), 68.2)) if args['kde']: outdict[args['name'] + '_kde'] = boot if args['mean']: outdict[args['name'] + '_mean'] = mean if args['std']: outdict[args['name'] + '_std'] = std if args['c68']: outdict[args['name'] + '_c68'] = c68 out_q.put(outdict) def rocauc(args, out_q): outdict = {} boot = [] if 'name' not in args: args['name'] = '' if 'n' not in args: args['n'] = 100 if 'weights' in args: for i in range(args['n']): points = np.random.choice(args['indeces'], len(args['indeces']), replace=True) boot.append(roc_auc_score(args['labels'].loc[points].values, args['preds'].loc[points].values, sample_weight=args['weights'].loc[points].values)) else: for i in range(args['n']): points = np.random.choice(args['indeces'], len(args['indeces']), replace=True) boot.append(roc_auc_score(args['labels'].loc[points].values, args['preds'].loc[points].values)) outdict[args['name']] = boot out_q.put(outdict) def mpRun(args, target=bootstrap): procs = [] out_q = mp.Queue() for i in range(len(args)): p = mp.Process(target=target, args=(args[i], out_q)) procs.append(p) p.start() resultdict = {} for i in range(len(args)): resultdict.update(out_q.get()) for p in procs: p.join() return resultdict
[ "statsmodels.api.nonparametric.KDEUnivariate", "numpy.abs", "sklearn.metrics.roc_auc_score", "multiprocessing.Queue", "multiprocessing.Process" ]
[((2188, 2198), 'multiprocessing.Queue', 'mp.Queue', ([], {}), '()\n', (2196, 2198), True, 'import multiprocessing as mp\n'), ((2242, 2290), 'multiprocessing.Process', 'mp.Process', ([], {'target': 'target', 'args': '(args[i], out_q)'}), '(target=target, args=(args[i], out_q))\n', (2252, 2290), True, 'import multiprocessing as mp\n'), ((660, 698), 'statsmodels.api.nonparametric.KDEUnivariate', 'sm.nonparametric.KDEUnivariate', (['points'], {}), '(points)\n', (690, 698), True, 'import statsmodels.api as sm\n'), ((1575, 1712), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["args['labels'].loc[points].values", "args['preds'].loc[points].values"], {'sample_weight': "args['weights'].loc[points].values"}), "(args['labels'].loc[points].values, args['preds'].loc[points].\n values, sample_weight=args['weights'].loc[points].values)\n", (1588, 1712), False, 'from sklearn.metrics import roc_auc_score\n'), ((1946, 2033), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["args['labels'].loc[points].values", "args['preds'].loc[points].values"], {}), "(args['labels'].loc[points].values, args['preds'].loc[points].\n values)\n", (1959, 2033), False, 'from sklearn.metrics import roc_auc_score\n'), ((969, 983), 'numpy.abs', 'np.abs', (['points'], {}), '(points)\n', (975, 983), True, 'import numpy as np\n')]
#!/usr/bin/env python #coding=utf-8 import numpy as np from eap import cell from neuron import h from nose import with_setup def configure_cell(): h('vinit=-65') h('create cable') h('create soma') h('connect soma(1), cable(0)') h('access cable') h('nseg = 10') h('L = 10') h('forall insert extracellular') h('define_shape()') configure_cell() def add_synapse(): h('objref synapse') h('cable synapse = new AlphaSynapse(0.1)') h('synapse.onset=0') h('synapse.tau=1') h('synapse.e=-100') h('synapse.gmax=0.00001') def reset_cell(): h('objref synapse') h('access cable') h.t = 0 def total_current(coord, I): return (I[:,:]*(coord['diam']*coord['L']*h.PI)[None,:]).sum(1) @with_setup(add_synapse, reset_cell) def test_current_balance_synapse_in_segment(): h('synapse.loc(0.1)') h('soma {insert pas}') cell.initialize(dt=0.025) t, I = cell.integrate(1) coord = cell.get_seg_coords() assert (np.abs(total_current(coord, I))<1e-6).all() @with_setup(add_synapse, reset_cell) def test_current_balance_synapse_at_section_end(): h('synapse.loc(0)') cell.initialize(dt=0.025) t, I = cell.integrate(1) coord = cell.get_seg_coords() assert (np.abs(total_current(coord, I))<1e-6).all() def test_location_coord(): x, y, z = cell.get_locs_coord(h.cable, 0.15) assert x == 1.5 assert y == 0 assert z == 0 @with_setup(add_synapse, reset_cell) def test_point_process_coord(): h('synapse.loc(0.15)') h('access soma') x, y, z = cell.get_pp_coord(h.synapse) assert x == 1.5 assert y == 0 assert z == 0 @with_setup(add_synapse, reset_cell) def test_get_point_processes(): h('synapse.loc(0.15)') h('access soma') pps = cell.get_point_processes() assert len(pps)==1 assert pps[0][0].same(h.synapse) assert pps[0][1] == 1.5 def test_axial_currents(): h('soma {insert pas}') isim = h.IClamp(1, sec=h.cable) isim.delay = 0 isim.dur = 1 isim.amp = 2 #nA h.cable.Ra = 0.1 cell.initialize(0.1) t, imem_density, iax_density = cell.integrate(0.2, i_axial=True) coord = cell.get_seg_coords() iax = iax_density*coord['diam'][None,:]**2*1e-8/4.*h.PI #mA assert np.abs(iax[-1,1]*1e6 - isim.amp)<0.1*isim.amp
[ "eap.cell.integrate", "eap.cell.get_seg_coords", "numpy.abs", "eap.cell.get_point_processes", "eap.cell.get_locs_coord", "neuron.h", "eap.cell.get_pp_coord", "neuron.h.IClamp", "nose.with_setup", "eap.cell.initialize" ]
[((750, 785), 'nose.with_setup', 'with_setup', (['add_synapse', 'reset_cell'], {}), '(add_synapse, reset_cell)\n', (760, 785), False, 'from nose import with_setup\n'), ((1037, 1072), 'nose.with_setup', 'with_setup', (['add_synapse', 'reset_cell'], {}), '(add_synapse, reset_cell)\n', (1047, 1072), False, 'from nose import with_setup\n'), ((1434, 1469), 'nose.with_setup', 'with_setup', (['add_synapse', 'reset_cell'], {}), '(add_synapse, reset_cell)\n', (1444, 1469), False, 'from nose import with_setup\n'), ((1651, 1686), 'nose.with_setup', 'with_setup', (['add_synapse', 'reset_cell'], {}), '(add_synapse, reset_cell)\n', (1661, 1686), False, 'from nose import with_setup\n'), ((153, 167), 'neuron.h', 'h', (['"""vinit=-65"""'], {}), "('vinit=-65')\n", (154, 167), False, 'from neuron import h\n'), ((172, 189), 'neuron.h', 'h', (['"""create cable"""'], {}), "('create cable')\n", (173, 189), False, 'from neuron import h\n'), ((194, 210), 'neuron.h', 'h', (['"""create soma"""'], {}), "('create soma')\n", (195, 210), False, 'from neuron import h\n'), ((215, 245), 'neuron.h', 'h', (['"""connect soma(1), cable(0)"""'], {}), "('connect soma(1), cable(0)')\n", (216, 245), False, 'from neuron import h\n'), ((250, 267), 'neuron.h', 'h', (['"""access cable"""'], {}), "('access cable')\n", (251, 267), False, 'from neuron import h\n'), ((272, 286), 'neuron.h', 'h', (['"""nseg = 10"""'], {}), "('nseg = 10')\n", (273, 286), False, 'from neuron import h\n'), ((291, 302), 'neuron.h', 'h', (['"""L = 10"""'], {}), "('L = 10')\n", (292, 302), False, 'from neuron import h\n'), ((307, 339), 'neuron.h', 'h', (['"""forall insert extracellular"""'], {}), "('forall insert extracellular')\n", (308, 339), False, 'from neuron import h\n'), ((344, 363), 'neuron.h', 'h', (['"""define_shape()"""'], {}), "('define_shape()')\n", (345, 363), False, 'from neuron import h\n'), ((406, 425), 'neuron.h', 'h', (['"""objref synapse"""'], {}), "('objref synapse')\n", (407, 425), False, 'from neuron import h\n'), ((430, 472), 'neuron.h', 'h', (['"""cable synapse = new AlphaSynapse(0.1)"""'], {}), "('cable synapse = new AlphaSynapse(0.1)')\n", (431, 472), False, 'from neuron import h\n'), ((477, 497), 'neuron.h', 'h', (['"""synapse.onset=0"""'], {}), "('synapse.onset=0')\n", (478, 497), False, 'from neuron import h\n'), ((502, 520), 'neuron.h', 'h', (['"""synapse.tau=1"""'], {}), "('synapse.tau=1')\n", (503, 520), False, 'from neuron import h\n'), ((525, 544), 'neuron.h', 'h', (['"""synapse.e=-100"""'], {}), "('synapse.e=-100')\n", (526, 544), False, 'from neuron import h\n'), ((549, 574), 'neuron.h', 'h', (['"""synapse.gmax=0.00001"""'], {}), "('synapse.gmax=0.00001')\n", (550, 574), False, 'from neuron import h\n'), ((598, 617), 'neuron.h', 'h', (['"""objref synapse"""'], {}), "('objref synapse')\n", (599, 617), False, 'from neuron import h\n'), ((622, 639), 'neuron.h', 'h', (['"""access cable"""'], {}), "('access cable')\n", (623, 639), False, 'from neuron import h\n'), ((837, 858), 'neuron.h', 'h', (['"""synapse.loc(0.1)"""'], {}), "('synapse.loc(0.1)')\n", (838, 858), False, 'from neuron import h\n'), ((863, 885), 'neuron.h', 'h', (['"""soma {insert pas}"""'], {}), "('soma {insert pas}')\n", (864, 885), False, 'from neuron import h\n'), ((890, 915), 'eap.cell.initialize', 'cell.initialize', ([], {'dt': '(0.025)'}), '(dt=0.025)\n', (905, 915), False, 'from eap import cell\n'), ((927, 944), 'eap.cell.integrate', 'cell.integrate', (['(1)'], {}), '(1)\n', (941, 944), False, 'from eap import cell\n'), ((957, 978), 'eap.cell.get_seg_coords', 'cell.get_seg_coords', ([], {}), '()\n', (976, 978), False, 'from eap import cell\n'), ((1129, 1148), 'neuron.h', 'h', (['"""synapse.loc(0)"""'], {}), "('synapse.loc(0)')\n", (1130, 1148), False, 'from neuron import h\n'), ((1153, 1178), 'eap.cell.initialize', 'cell.initialize', ([], {'dt': '(0.025)'}), '(dt=0.025)\n', (1168, 1178), False, 'from eap import cell\n'), ((1190, 1207), 'eap.cell.integrate', 'cell.integrate', (['(1)'], {}), '(1)\n', (1204, 1207), False, 'from eap import cell\n'), ((1220, 1241), 'eap.cell.get_seg_coords', 'cell.get_seg_coords', ([], {}), '()\n', (1239, 1241), False, 'from eap import cell\n'), ((1341, 1375), 'eap.cell.get_locs_coord', 'cell.get_locs_coord', (['h.cable', '(0.15)'], {}), '(h.cable, 0.15)\n', (1360, 1375), False, 'from eap import cell\n'), ((1506, 1528), 'neuron.h', 'h', (['"""synapse.loc(0.15)"""'], {}), "('synapse.loc(0.15)')\n", (1507, 1528), False, 'from neuron import h\n'), ((1533, 1549), 'neuron.h', 'h', (['"""access soma"""'], {}), "('access soma')\n", (1534, 1549), False, 'from neuron import h\n'), ((1564, 1592), 'eap.cell.get_pp_coord', 'cell.get_pp_coord', (['h.synapse'], {}), '(h.synapse)\n', (1581, 1592), False, 'from eap import cell\n'), ((1723, 1745), 'neuron.h', 'h', (['"""synapse.loc(0.15)"""'], {}), "('synapse.loc(0.15)')\n", (1724, 1745), False, 'from neuron import h\n'), ((1750, 1766), 'neuron.h', 'h', (['"""access soma"""'], {}), "('access soma')\n", (1751, 1766), False, 'from neuron import h\n'), ((1777, 1803), 'eap.cell.get_point_processes', 'cell.get_point_processes', ([], {}), '()\n', (1801, 1803), False, 'from eap import cell\n'), ((1924, 1946), 'neuron.h', 'h', (['"""soma {insert pas}"""'], {}), "('soma {insert pas}')\n", (1925, 1946), False, 'from neuron import h\n'), ((1958, 1982), 'neuron.h.IClamp', 'h.IClamp', (['(1)'], {'sec': 'h.cable'}), '(1, sec=h.cable)\n', (1966, 1982), False, 'from neuron import h\n'), ((2065, 2085), 'eap.cell.initialize', 'cell.initialize', (['(0.1)'], {}), '(0.1)\n', (2080, 2085), False, 'from eap import cell\n'), ((2121, 2154), 'eap.cell.integrate', 'cell.integrate', (['(0.2)'], {'i_axial': '(True)'}), '(0.2, i_axial=True)\n', (2135, 2154), False, 'from eap import cell\n'), ((2167, 2188), 'eap.cell.get_seg_coords', 'cell.get_seg_coords', ([], {}), '()\n', (2186, 2188), False, 'from eap import cell\n'), ((2269, 2310), 'numpy.abs', 'np.abs', (['(iax[-1, 1] * 1000000.0 - isim.amp)'], {}), '(iax[-1, 1] * 1000000.0 - isim.amp)\n', (2275, 2310), True, 'import numpy as np\n')]
#!/usr/bin/python3 -B # Copyright 2015-2019 <NAME>, <EMAIL>. 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. '''%prog [options] Interactively display and update values from an embedded device. ''' import binascii import io import numpy import optparse import os import re import serial import socket import struct import sys import time import matplotlib matplotlib.use('Qt4Agg') matplotlib.rcParams['backend.qt4'] = 'PySide' from matplotlib.backends import backend_qt4agg from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas os.environ['QT_API'] = 'pyside' from qtconsole.qt import QtCore, QtGui from PySide import QtUiTools from qtconsole.history_console_widget import HistoryConsoleWidget from bazel_tools.tools.python.runfiles import runfiles import mjlib.telemetry.reader as reader LEFT_LEGEND_LOC = 3 RIGHT_LEGEND_LOC = 2 DEFAULT_RATE = 100 MAX_HISTORY_SIZE = 100 def readline(stream): result = b'' while True: c = stream.read(1) if len(c) == 0: return result result += c if c == b'\n': return result def dehexify(data): result = b'' for i in range(0, len(data), 2): result += bytes([int(data[i:i+2], 16)]) return result def read_varuint(data, offset): '''Return (varuint, next_offset)''' result = 0 shift = 0 for i in range(5): if offset >= len(data): return None, offset this_byte, = struct.unpack('<B', data[offset:offset+1]) result |= (this_byte & 0x7f) << shift shift += 7 offset += 1 if (this_byte & 0x80) == 0: return result, offset assert False class NetworkPort: def __init__(self, port): self._port = port def write(self, data): self._port.send(data) def read(self, size): try: return self._port.recv(size) except socket.timeout: return b'' @property def timeout(self): return self._port.gettimeout() @timeout.setter def timeout(self, value): self._port.settimeout(value) class BufferedSerial: def __init__(self, port): self.port = port self._write_buffer = b'' def queue(self, data): self._write_buffer += data def poll(self): if len(self._write_buffer): self.write(b'') def write(self, data): to_write = self._write_buffer + data self._write_buffer = b'' self.port.write(to_write) def read(self, size): return self.port.read(size) def set_timeout(self, value): self.port.timeout = value def get_timeout(self): return self.port.timeout timeout = property(get_timeout, set_timeout) class StreamBase: def __init__(self, stream, destination_id, max_receive_bytes): self._stream = stream self._destination_id = destination_id self._max_receive_bytes = max_receive_bytes self._read_buffer = b'' self._write_buffer = b'' def read(self, max_bytes): to_return, self._read_buffer = self._read_buffer[0:max_bytes], self._read_buffer[max_bytes:] return to_return def write(self, data): self._write_buffer += data def flush(self): if len(self._write_buffer): self.poll() class FdcanUsbStream(StreamBase): def __init__(self, *args, **kwargs): super(FdcanUsbStream, self).__init__(*args, **kwargs) def poll(self): wait_for_response = len(self._write_buffer) == 0 to_write = min(len(self._write_buffer), 100) payload = struct.pack( '<BBB', 0x42 if wait_for_response else 0x40, 1, self._max_receive_bytes if wait_for_response else to_write) this_write, self._write_buffer = self._write_buffer[0:to_write], self._write_buffer[to_write:] payload += this_write assert len(payload) < 127 self._stream.queue( 'can send {:x} {}\n'.format( (0x8000 if wait_for_response else 0x0) | self._destination_id, ''.join(['{:02x}'.format(x) for x in payload])) .encode('latin1')) try: self._stream.poll() self._stream.timeout = 0.10 while True: maybe_response = readline(self._stream) if maybe_response == b'': return if maybe_response.startswith(b"OK"): if not wait_for_response: # This is all we need here. return continue if maybe_response.startswith(b"rcv "): break finally: self._stream.timeout = 0.0 fields = maybe_response.decode('latin1').strip().split(' ') address = int(fields[1], 16) dest = address & 0xff source = (address >> 8) & 0xff if dest != 0x00: return if source != self._destination_id: return payload = dehexify(fields[2]) sbo = 0 subframe_id, sbo = read_varuint(payload, sbo) channel, sbo = read_varuint(payload, sbo) server_len, sbo = read_varuint(payload, sbo) if subframe_id is None or channel is None or server_len is None: return if subframe_id != 0x41: return if channel != 1: return payload_rest = payload[sbo:] to_add = payload_rest[0:server_len] self._read_buffer += to_add class MultiplexStream(StreamBase): def __init__(self, *args, **kwargs): super(FdcanUsbStream, self).__init__(*args, **kwargs) def poll(self): # We only ask for a response if we're not writing immediately. # That way we can get multiple writes out nearly # simultaneously. wait_for_response = len(self._write_buffer) == 0 header = struct.pack('<HBB', 0xab54, 0x80 if wait_for_response else 0x00, self._destination_id) to_write = min(len(self._write_buffer), 100) payload = struct.pack( '<BBB', 0x42 if wait_for_response else 0x40, 1, self._max_receive_bytes if wait_for_response else to_write) this_write, self._write_buffer = self._write_buffer[0:to_write], self._write_buffer[to_write:] payload += this_write # So we don't need varuint assert len(payload) < 127 frame = header + struct.pack('<B', len(payload)) + payload crc = binascii.crc_hqx(frame, 0xffff) frame += struct.pack('<H', crc) self._stream.queue(frame) if not wait_for_response: return try: self._stream.poll() self._stream.timeout = 0.02 result_frame_start = self._stream.read(7) if len(result_frame_start) < 7: return header, source, dest = struct.unpack( '<HBB', result_frame_start[:4]) if header != 0xab54: # TODO: resynchronize print("Resynchronizing! hdr={:x}".format(header), flush=True) self._stream.read(8192) return payload_len, payload_offset = read_varuint(result_frame_start, 4) if payload_len is None: print("No payload!", flush=True) # We don't yet have enough return result_frame_remainder = self._stream.read( 6 + (payload_offset - 4) + payload_len - len(result_frame_start)) finally: self._stream.timeout = 0.0 result_frame = result_frame_start + result_frame_remainder if dest != 0x00: return if source != self._destination_id: return payload = result_frame[payload_offset:-2] if len(payload) < 3: return sbo = 0 subframe_id, sbo = read_varuint(payload, sbo) channel, sbo = read_varuint(payload, sbo) server_len, sbo = read_varuint(payload, sbo) if subframe_id is None or channel is None or server_len is None: return if subframe_id != 0x41: return if channel != 1: return payload_rest = payload[sbo:] if server_len != len(payload_rest): return self._read_buffer += payload_rest # TODO jpieper: Factor these out of tplot.py def _get_data(value, name): fields = name.split('.') for field in fields: if isinstance(value, list): value = value[int(field)] else: value = getattr(value, field) return value def _set_tree_widget_data(item, struct, getter=lambda x, y: getattr(x, y), required_size=0): if item.childCount() < required_size: for i in range(item.childCount(), required_size): subitem = QtGui.QTreeWidgetItem(item) subitem.setText(0, str(i)) for i in range(item.childCount()): child = item.child(i) name = child.text(0) field = getter(struct, name) if isinstance(field, tuple) and child.childCount() > 0: _set_tree_widget_data(child, field) elif isinstance(field, list): _set_tree_widget_data(child, field, getter=lambda x, y: x[int(y)], required_size=len(field)) else: child.setText(1, repr(field)) class RecordSignal(object): def __init__(self): self._index = 0 self._callbacks = {} def connect(self, handler): result = self._index self._index += 1 self._callbacks[result] = handler class Connection(object): def __init__(self, parent, index): self.parent = parent self.index = index def remove(self): del self.parent._callbacks[self.index] return Connection(self, result) def update(self, value): for handler in self._callbacks.values(): handler(value) return len(self._callbacks) != 0 class PlotItem(object): def __init__(self, axis, plot_widget, name, signal): self.axis = axis self.plot_widget = plot_widget self.name = name self.line = None self.xdata = [] self.ydata = [] self.connection = signal.connect(self._handle_update) def _make_line(self): line = matplotlib.lines.Line2D([], []) line.set_label(self.name) line.set_color(self.plot_widget.COLORS[self.plot_widget.next_color]) self.plot_widget.next_color = ( self.plot_widget.next_color + 1) % len(self.plot_widget.COLORS) self.axis.add_line(line) self.axis.legend(loc=self.axis.legend_loc) self.line = line def remove(self): self.line.remove() self.connection.remove() # NOTE jpieper: matplotlib gives us no better way to remove a # legend. if len(self.axis.lines) == 0: self.axis.legend_ = None else: self.axis.legend(loc=self.axis.legend_loc) self.plot_widget.canvas.draw() def _handle_update(self, value): if self.plot_widget.paused: return if self.line is None: self._make_line() now = time.time() self.xdata.append(now) self.ydata.append(value) # Remove elements from the beginning until there is at most # one before the window. oldest_time = now - self.plot_widget.history_s oldest_index = None for i in range(len(self.xdata)): if self.xdata[i] >= oldest_time: oldest_index = i - 1 break if oldest_index and oldest_index > 1: self.xdata = self.xdata[oldest_index:] self.ydata = self.ydata[oldest_index:] self.line.set_data(self.xdata, self.ydata) self.axis.relim() self.axis.autoscale() self.plot_widget.data_update() class PlotWidget(QtGui.QWidget): COLORS = 'rbgcmyk' def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.history_s = 20.0 self.next_color = 0 self.paused = False self.last_draw_time = 0.0 self.figure = matplotlib.figure.Figure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect('key_press_event', self.handle_key_press) self.canvas.mpl_connect('key_release_event', self.handle_key_release) self.left_axis = self.figure.add_subplot(111) self.left_axis.grid() self.left_axis.fmt_xdata = lambda x: '%.3f' % x self.left_axis.legend_loc = LEFT_LEGEND_LOC self.right_axis = None def draw(): # NOTE jpieper: For some reason, on the first repaint # event, the height is negative, which throws spurious # errors. Paper over that here. l, b, w, h = self.figure.bbox.bounds if h < 0: return FigureCanvas.draw(self.canvas) self.canvas.repaint() self.canvas.draw = draw self.toolbar = backend_qt4agg.NavigationToolbar2QT(self.canvas, self) self.pause_action = QtGui.QAction(u'Pause', self) self.pause_action.setCheckable(True) self.pause_action.toggled.connect(self._handle_pause) self.toolbar.addAction(self.pause_action) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.toolbar, 0) layout.addWidget(self.canvas, 1) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus) def _handle_pause(self, value): self.paused = value def add_plot(self, name, signal, axis_number): axis = self.left_axis if axis_number == 1: if self.right_axis is None: self.right_axis = self.left_axis.twinx() self.right_axis.legend_loc = RIGHT_LEGEND_LOC axis = self.right_axis item = PlotItem(axis, self, name, signal) return item def remove_plot(self, item): item.remove() def data_update(self): now = time.time() elapsed = now - self.last_draw_time if elapsed > 0.1: self.last_draw_time = now self.canvas.draw() def _get_axes_keys(self): result = [] result.append(('1', self.left_axis)) if self.right_axis: result.append(('2', self.right_axis)) return result def handle_key_press(self, event): if event.key not in ['1', '2']: return for key, axis in self._get_axes_keys(): if key == event.key: axis.set_navigate(True) else: axis.set_navigate(False) def handle_key_release(self, event): if event.key not in ['1', '2']: return for key, axis in self._get_axes_keys(): axis.set_navigate(True) class SizedTreeWidget(QtGui.QTreeWidget): def __init__(self, parent=None): QtGui.QTreeWidget.__init__(self, parent) self.setColumnCount(2) self.headerItem().setText(0, 'Name') self.headerItem().setText(1, 'Value') def sizeHint(self): return QtCore.QSize(350, 500) class TviewConsoleWidget(HistoryConsoleWidget): line_input = QtCore.Signal(str) def __init__(self, *args, **kw): super(TviewConsoleWidget, self).__init__(*args, **kw) self._prompt = '>>> ' self.clear() # The bionic version of ConsoleWidget seems to get the cursor # position screwed up after a clear. Let's just fix it up # here. self._append_before_prompt_cursor.setPosition(0) def sizeHint(self): return QtCore.QSize(600, 200) def add_text(self, data): assert data.endswith('\n') or data.endswith('\r') self._append_plain_text(data, before_prompt=True) self._control.moveCursor(QtGui.QTextCursor.End) def _handle_timeout(self): self._append_plain_text('%s\r\n' % time.time(), before_prompt=True) self._control.moveCursor(QtGui.QTextCursor.End) def _is_complete(self, source, interactive): return True, False def _execute(self, source, hidden): self.line_input.emit(source) self._show_prompt(self._prompt) return True class Record: def __init__(self, archive): self.archive = archive self.tree_item = None self.signals = {} self.history = [] def get_signal(self, name): if name not in self.signals: self.signals[name] = RecordSignal() return self.signals[name] def update(self, struct): count = 0 self.history.append(struct) if len(self.history) > MAX_HISTORY_SIZE: self.history = self.history[1:] for key, signal in self.signals.items(): if key.startswith('__STDDEV_'): remaining = key.split('__STDDEV_')[1] values = [_get_data(x, remaining) for x in self.history] value = numpy.std(values) elif key.startswith('__MEAN_'): remaining = key.split('__MEAN_')[1] values = [_get_data(x, remaining) for x in self.history] value = numpy.mean(values) else: value = _get_data(struct, key) if signal.update(value): count += 1 return count != 0 class NoEditDelegate(QtGui.QStyledItemDelegate): def __init__(self, parent=None): QtGui.QStyledItemDelegate.__init__(self, parent=parent) def createEditor(self, parent, option, index): return None def _get_item_name(item): name = item.text(0) while item.parent() and item.parent().parent(): name = item.parent().text(0) + '.' + name item = item.parent() return name def _get_item_root(item): while item.parent().parent(): item = item.parent() return item.text(0) class Device: STATE_LINE = 0 STATE_CONFIG = 1 STATE_TELEMETRY = 2 STATE_SCHEMA = 3 STATE_DATA = 4 def __init__(self, number, stream, console, prefix, config_tree_item, data_tree_item): self.number = number self._stream = stream self._console = console self._prefix = prefix self._config_tree_item = config_tree_item self._data_tree_item = data_tree_item self._buffer = b'' self._serial_state = self.STATE_LINE self._telemetry_records = {} self._schema_name = None self._config_tree_items = {} self._config_callback = None self._start_time = None def start(self): # Stop the spew. self._stream.write('\r\n'.encode('latin1')) self._stream.write('tel stop\r\n'.encode('latin1')) # We want to wait a little bit, discard everything we have # received, and then initialize the device. self._start_time = time.time() def _setup_device(self, callback): # When we start, get a listing of all configuration options # and all available telemetry channels. def after_config(): self.update_telemetry(callback) self.update_config(after_config) def poll(self): self._stream.poll() if self._start_time is not None: now = time.time() if now - self._start_time < 0.2: return # Discard any junk that may be there. self._stream.read(8192) self._start_time = None self._setup_device(None) data = self._stream.read(8192) self._buffer += data while True: old_len = len(self._buffer) self._handle_serial_data() if len(self._buffer) == old_len: break self._stream.flush() def write(self, data): self._stream.write(data) def config_item_changed(self, name, value): if self._serial_state == self.STATE_CONFIG: return self.write_line('conf set %s %s\r\n' % (name, value)) def _handle_serial_data(self): if self._serial_state == self.STATE_LINE: self._handle_serial_line() elif self._serial_state == self.STATE_CONFIG: self._handle_config() elif self._serial_state == self.STATE_TELEMETRY: self._handle_telemetry() elif self._serial_state == self.STATE_SCHEMA: self._handle_schema() elif self._serial_state == self.STATE_DATA: self._handle_data() else: assert False def _handle_serial_line(self): line = self._get_serial_line() if line is None: return line = line.decode('latin1') display = True if line == '': display = False if line.startswith('schema '): self._serial_state = self.STATE_SCHEMA self._schema_name = line.split(' ', 1)[1].strip() elif line.startswith('emit '): self._serial_state = self.STATE_DATA self._schema_name = line.split(' ', 1)[1].strip() display = False if display: self._console.add_text(self._prefix + line + '\n') def _get_serial_line(self): # Consume any newlines at the start of our buffer. pos = 0 while pos < len(self._buffer) and self._buffer[pos] in b'\r\n': pos += 1 self._buffer = self._buffer[pos:] # Look for a trailing newline end = 0 while end < len(self._buffer) and self._buffer[end] not in b'\r\n': end += 1 if end >= len(self._buffer): return line, self._buffer = self._buffer[:end], self._buffer[end+1:] return line def update_config(self, callback): # Clear out our config tree. self._config_tree_item.takeChildren() self._config_tree_items = {} self._config_callback = callback self.write_line('conf enumerate\r\n') # TODO jpieper: In the current protocol this is racy, as there # is no header on the config enumeration. I should probably # add one. self._serial_state = self.STATE_CONFIG def _handle_config(self): line = self._get_serial_line() if not line: return line = line.decode('latin1') self._console.add_text(self._prefix + line + '\n') if line.startswith('OK'): # We're done with config now. self._serial_state = self.STATE_LINE cbk, self._config_callback = self._config_callback, None if cbk: cbk() else: # Add it into our tree view. key, value = line.split(' ', 1) name, rest = key.split('.', 1) if name not in self._config_tree_items: item = QtGui.QTreeWidgetItem(self._config_tree_item) item.setText(0, name) self._config_tree_items[name] = item def add_config(item, key, value): if key == '': item.setText(1, value) item.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) return fields = key.split('.', 1) this_field = fields[0] next_key = '' if len(fields) > 1: next_key = fields[1] child = None # See if we already have an appropriate child. for i in range(item.childCount()): if item.child(i).text(0) == this_field: child = item.child(i) break if child is None: child = QtGui.QTreeWidgetItem(item) child.setText(0, this_field) add_config(child, next_key, value) add_config(self._config_tree_items[name], rest, value) # TODO(jpieper) # self.ui.configTreeWidget.resizeColumnToContents(0) def update_telemetry(self, callback): self._data_tree_item.takeChildren() self._telemetry_records = {} self._telemetry_callback = callback self.write_line('tel list\r\n') self._serial_state = self.STATE_TELEMETRY def write_line(self, line): self._console.add_text(self._prefix + line) self._stream.write(line.encode('latin1')) def _handle_telemetry(self): line = self._get_serial_line() if not line: return line = line.decode('latin1') self._console.add_text(self._prefix + line + '\n') if line.startswith('OK'): # Now we need to start getting schemas. self._serial_state = self.STATE_LINE self._update_schema() else: name = line.strip() self._telemetry_records[name] = None def _update_schema(self): # Find a channel we don't have a schema for and request it. for name in self._telemetry_records.keys(): if self._telemetry_records[name] is None: self.write_line('tel schema %s\r\n' % name) self._serial_state = self.STATE_LINE return self._serial_state = self.STATE_LINE # Guess we are done. Update our tree view. # TODO(jpieper) # self.ui.telemetryTreeWidget.resizeColumnToContents(0) cbk, self._telemetry_callback = self._telemetry_callback, None if cbk: cbk() def _handle_schema(self): schema = self._handle_sized_block() if not schema: return name, self._schema_name = self._schema_name, None if name in self._telemetry_records: if self._telemetry_records[name]: return archive = reader.Type.from_binary(io.BytesIO(schema), name=name) record = Record(archive) self._telemetry_records[name] = record record.tree_item = self._add_schema_to_tree(name, archive, record) self._console.add_text(self._prefix + '<schema name=%s>\n' % name) # Now look to see if there are any more we should request. self._update_schema() def _handle_data(self): data = self._handle_sized_block() if not data: return name, self._schema_name = self._schema_name, None if name not in self._telemetry_records: return record = self._telemetry_records[name] if record: struct = record.archive.read(reader.Stream(io.BytesIO(data))) record.update(struct) _set_tree_widget_data(record.tree_item, struct) self._serial_state = self.STATE_LINE def _handle_sized_block(self): # Wait until we have the complete schema in the buffer. It # will start with the final newline from the first line. if len(self._buffer) < 5: return size = struct.unpack('<I', self._buffer[1:5])[0] if size > 2 ** 24: # Whoops, probably bogus. print('Invalid schema size, skipping whatever we were doing.') self._serial_state = self.STATE_LINE return if len(self._buffer) < 5 + size: return block = self._buffer[5:5+size] self._buffer = self._buffer[5+size:] return block class Schema: def __init__(self, name, parent, record): self._name = name self._parent = parent self.record = record def expand(self): self._parent.write_line('tel fmt %s 0\r\n' % self._name) self._parent.write_line('tel rate %s %d\r\n' % (self._name, DEFAULT_RATE)) def collapse(self): self._parent.write_line('tel rate %s 0\r\n' % self._name) def _add_schema_to_tree(self, name, schema_data, record): item = QtGui.QTreeWidgetItem(self._data_tree_item) item.setText(0, name) schema = Device.Schema(name, self, record) item.setData(0, QtCore.Qt.UserRole, schema) def add_item(parent, element): if isinstance(element, reader.ObjectType): for field in element.fields: name = field.name item = QtGui.QTreeWidgetItem(parent) item.setText(0, name) add_item(item, field.type_class) add_item(item, schema_data) return item class TviewMainWindow(): def __init__(self, options, parent=None): self.options = options self.port = None self.devices = [] self.default_rate = 100 self._serial_timer = QtCore.QTimer() self._serial_timer.timeout.connect(self._poll_serial) self._serial_timer.start(10) r = runfiles.Create() uifilename = r.Rlocation( "com_github_mjbots_moteus/moteus/tool/tview_main_window.ui") loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(uifilename) uifile.open(QtCore.QFile.ReadOnly) self.ui = loader.load(uifile, parent) uifile.close() self.ui.configTreeWidget = SizedTreeWidget() self.ui.configDock.setWidget(self.ui.configTreeWidget) self.ui.telemetryTreeWidget = SizedTreeWidget() self.ui.telemetryDock.setWidget(self.ui.telemetryTreeWidget) self.ui.telemetryTreeWidget.itemExpanded.connect( self._handle_tree_expanded) self.ui.telemetryTreeWidget.itemCollapsed.connect( self._handle_tree_collapsed) self.ui.telemetryTreeWidget.setContextMenuPolicy( QtCore.Qt.CustomContextMenu) self.ui.telemetryTreeWidget.customContextMenuRequested.connect( self._handle_telemetry_context_menu) self.ui.configTreeWidget.setItemDelegateForColumn( 0, NoEditDelegate(self.ui)) self.ui.configTreeWidget.itemExpanded.connect( self._handle_config_expanded) self.ui.configTreeWidget.itemChanged.connect( self._handle_config_item_changed) self.ui.plotItemRemoveButton.clicked.connect( self._handle_plot_item_remove) self.console = TviewConsoleWidget() self.console.ansi_codes = False self.console.line_input.connect(self._handle_user_input) self.ui.consoleDock.setWidget(self.console) self.ui.tabifyDockWidget(self.ui.configDock, self.ui.telemetryDock) layout = QtGui.QVBoxLayout(self.ui.plotHolderWidget) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.ui.plotHolderWidget.setLayout(layout) self.ui.plotWidget = PlotWidget(self.ui.plotHolderWidget) layout.addWidget(self.ui.plotWidget) def update_plotwidget(value): self.ui.plotWidget.history_s = value self.ui.historySpin.valueChanged.connect(update_plotwidget) QtCore.QTimer.singleShot(0, self._handle_startup) def show(self): self.ui.show() def _open(self): if self.options.target: target_fields = self.options.target.split(':') try: port = NetworkPort(socket.create_connection( (target_fields[0], int(target_fields[1])), timeout=2.0)) except OSError: print("could not connect to: ", self.options.target) exit(1) self.port = BufferedSerial(port) else: self.port = BufferedSerial(serial.Serial( port=self.options.serial, baudrate=self.options.baudrate, timeout=0.0)) self.devices = [] self.ui.configTreeWidget.clear() self.ui.telemetryTreeWidget.clear() for device_id in [int(x) for x in self.options.devices.split(',')]: if self.options.rs485: stream = MultiplexStream( self.port, device_id, self.options.max_receive_bytes) else: stream = FdcanUsbStream( self.port, device_id, self.options.max_receive_bytes) config_item = QtGui.QTreeWidgetItem() config_item.setText(0, str(device_id)) self.ui.configTreeWidget.addTopLevelItem(config_item) data_item = QtGui.QTreeWidgetItem() data_item.setText(0, str(device_id)) self.ui.telemetryTreeWidget.addTopLevelItem(data_item) device = Device(device_id, stream, self.console, '{}>'.format(device_id), config_item, data_item) config_item.setData(0, QtCore.Qt.UserRole, device) device.start() self.devices.append(device) def _handle_startup(self): self.console._control.setFocus() def _poll_serial(self): if self.port is None: if os.path.exists(self.options.serial) or self.options.target: self._open() else: return else: [x.poll() for x in self.devices] def make_writer(self, devices, line): def write(): for device in devices: device.write((line + '\n').encode('latin1')) return write def _handle_user_input(self, line): device_lines = [x.strip() for x in line.split('&&')] now = time.time() current_delay_ms = 0 for line in device_lines: delay_re = re.search(r"^:(\d+)$", line) device_re = re.search(r"^(A|\d+)>(.*)$", line) if delay_re: current_delay_ms += int(delay_re.group(1)) continue elif device_re: if device_re.group(1) == 'A': device_nums = [x.number for x in self.devices] else: device_nums = [int(device_re.group(1))] line = device_re.group(2) else: device_nums = [self.devices[0].number] devices = [x for x in self.devices if x.number in device_nums] writer = self.make_writer(devices, line) if current_delay_ms > 0: QtCore.QTimer.singleShot(current_delay_ms, writer) else: writer() def _handle_tree_expanded(self, item): self.ui.telemetryTreeWidget.resizeColumnToContents(0) user_data = item.data(0, QtCore.Qt.UserRole) if user_data: user_data.expand() def _handle_tree_collapsed(self, item): user_data = item.data(0, QtCore.Qt.UserRole) if user_data: user_data.collapse() def _handle_telemetry_context_menu(self, pos): item = self.ui.telemetryTreeWidget.itemAt(pos) if item.childCount() > 0: return menu = QtGui.QMenu(self.ui) left_action = menu.addAction('Plot Left') right_action = menu.addAction('Plot Right') left_std_action = menu.addAction('Plot StdDev Left') right_std_action = menu.addAction('Plot StdDev Right') left_mean_action = menu.addAction('Plot Mean Left') right_mean_action = menu.addAction('Plot Mean Right') plot_actions = [ left_action, right_action, left_std_action, right_std_action, left_mean_action, right_mean_action, ] right_actions = [right_action, right_std_action, right_mean_action] std_actions = [left_std_action, right_std_action] mean_actions = [left_mean_action, right_mean_action] menu.addSeparator() copy_name = menu.addAction('Copy Name') copy_value = menu.addAction('Copy Value') requested = menu.exec_(self.ui.telemetryTreeWidget.mapToGlobal(pos)) if requested in plot_actions: top = item while top.parent().parent(): top = top.parent() schema = top.data(0, QtCore.Qt.UserRole) record = schema.record name = _get_item_name(item) root = _get_item_root(item) leaf = name.split('.', 1)[1] axis = 0 if requested in right_actions: axis = 1 if requested in std_actions: leaf = '__STDDEV_' + leaf name = 'stddev ' + name if requested in mean_actions: leaf = '__MEAN_' + leaf name = 'mean ' + name plot_item = self.ui.plotWidget.add_plot( name, record.get_signal(leaf), axis) self.ui.plotItemCombo.addItem(name, plot_item) elif requested == copy_name: QtGui.QApplication.clipboard().setText(item.text(0)) elif requested == copy_value: QtGui.QApplication.clipboard().setText(item.text(1)) else: # The user cancelled. pass def _handle_config_expanded(self, item): self.ui.configTreeWidget.resizeColumnToContents(0) def _handle_config_item_changed(self, item, column): if not item.parent(): return top = item while top.parent(): top = top.parent() device = top.data(0, QtCore.Qt.UserRole) device.config_item_changed(_get_item_name(item), item.text(1)) def _handle_plot_item_remove(self): index = self.ui.plotItemCombo.currentIndex() if index < 0: return item = self.ui.plotItemCombo.itemData(index) self.ui.plotWidget.remove_plot(item) self.ui.plotItemCombo.removeItem(index) def main(): usage, description = __doc__.split('\n\n', 1) parser = optparse.OptionParser(usage=usage, description=description) parser.add_option('--serial', '-s', default='/dev/ttyACM0') parser.add_option('--baudrate', '-b', type='int', default=115200) parser.add_option('--devices', '-d', type='str', default='1') parser.add_option('--target', '-t', default=None) parser.add_option('--rs485', '-c', action='store_true') parser.add_option('--max-receive-bytes', default=127, type=int) options, args = parser.parse_args() assert len(args) == 0 app = QtGui.QApplication(sys.argv) # To work around https://bugreports.qt.io/browse/PYSIDE-88 app.aboutToQuit.connect(lambda: os._exit(0)) tv = TviewMainWindow(options) tv.show() app.exec_() if __name__ == '__main__': main()
[ "matplotlib.backends.backend_qt4agg.NavigationToolbar2QT", "qtconsole.qt.QtGui.QWidget.__init__", "qtconsole.qt.QtGui.QTreeWidget.__init__", "optparse.OptionParser", "matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg", "numpy.mean", "serial.Serial", "qtconsole.qt.QtGui.QMenu", "matplotlib.lines.L...
[((881, 905), 'matplotlib.use', 'matplotlib.use', (['"""Qt4Agg"""'], {}), "('Qt4Agg')\n", (895, 905), False, 'import matplotlib\n'), ((16116, 16134), 'qtconsole.qt.QtCore.Signal', 'QtCore.Signal', (['str'], {}), '(str)\n', (16129, 16134), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((38862, 38921), 'optparse.OptionParser', 'optparse.OptionParser', ([], {'usage': 'usage', 'description': 'description'}), '(usage=usage, description=description)\n', (38883, 38921), False, 'import optparse\n'), ((39383, 39411), 'qtconsole.qt.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (39401, 39411), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((1986, 2030), 'struct.unpack', 'struct.unpack', (['"""<B"""', 'data[offset:offset + 1]'], {}), "('<B', data[offset:offset + 1])\n", (1999, 2030), False, 'import struct\n'), ((4154, 4274), 'struct.pack', 'struct.pack', (['"""<BBB"""', '(66 if wait_for_response else 64)', '(1)', '(self._max_receive_bytes if wait_for_response else to_write)'], {}), "('<BBB', 66 if wait_for_response else 64, 1, self.\n _max_receive_bytes if wait_for_response else to_write)\n", (4165, 4274), False, 'import struct\n'), ((6490, 6576), 'struct.pack', 'struct.pack', (['"""<HBB"""', '(43860)', '(128 if wait_for_response else 0)', 'self._destination_id'], {}), "('<HBB', 43860, 128 if wait_for_response else 0, self.\n _destination_id)\n", (6501, 6576), False, 'import struct\n'), ((6707, 6827), 'struct.pack', 'struct.pack', (['"""<BBB"""', '(66 if wait_for_response else 64)', '(1)', '(self._max_receive_bytes if wait_for_response else to_write)'], {}), "('<BBB', 66 if wait_for_response else 64, 1, self.\n _max_receive_bytes if wait_for_response else to_write)\n", (6718, 6827), False, 'import struct\n'), ((7139, 7169), 'binascii.crc_hqx', 'binascii.crc_hqx', (['frame', '(65535)'], {}), '(frame, 65535)\n', (7155, 7169), False, 'import binascii\n'), ((7188, 7210), 'struct.pack', 'struct.pack', (['"""<H"""', 'crc'], {}), "('<H', crc)\n", (7199, 7210), False, 'import struct\n'), ((11168, 11199), 'matplotlib.lines.Line2D', 'matplotlib.lines.Line2D', (['[]', '[]'], {}), '([], [])\n', (11191, 11199), False, 'import matplotlib\n'), ((12061, 12072), 'time.time', 'time.time', ([], {}), '()\n', (12070, 12072), False, 'import time\n'), ((12869, 12905), 'qtconsole.qt.QtGui.QWidget.__init__', 'QtGui.QWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (12891, 12905), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((13051, 13077), 'matplotlib.figure.Figure', 'matplotlib.figure.Figure', ([], {}), '()\n', (13075, 13077), False, 'import matplotlib\n'), ((13100, 13125), 'matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg', 'FigureCanvas', (['self.figure'], {}), '(self.figure)\n', (13112, 13125), True, 'from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n'), ((13932, 13986), 'matplotlib.backends.backend_qt4agg.NavigationToolbar2QT', 'backend_qt4agg.NavigationToolbar2QT', (['self.canvas', 'self'], {}), '(self.canvas, self)\n', (13967, 13986), False, 'from matplotlib.backends import backend_qt4agg\n'), ((14015, 14044), 'qtconsole.qt.QtGui.QAction', 'QtGui.QAction', (['u"""Pause"""', 'self'], {}), "(u'Pause', self)\n", (14028, 14044), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((14220, 14243), 'qtconsole.qt.QtGui.QVBoxLayout', 'QtGui.QVBoxLayout', (['self'], {}), '(self)\n', (14237, 14243), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((14923, 14934), 'time.time', 'time.time', ([], {}), '()\n', (14932, 14934), False, 'import time\n'), ((15823, 15863), 'qtconsole.qt.QtGui.QTreeWidget.__init__', 'QtGui.QTreeWidget.__init__', (['self', 'parent'], {}), '(self, parent)\n', (15849, 15863), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((16026, 16048), 'qtconsole.qt.QtCore.QSize', 'QtCore.QSize', (['(350)', '(500)'], {}), '(350, 500)\n', (16038, 16048), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((16538, 16560), 'qtconsole.qt.QtCore.QSize', 'QtCore.QSize', (['(600)', '(200)'], {}), '(600, 200)\n', (16550, 16560), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((18394, 18449), 'qtconsole.qt.QtGui.QStyledItemDelegate.__init__', 'QtGui.QStyledItemDelegate.__init__', (['self'], {'parent': 'parent'}), '(self, parent=parent)\n', (18428, 18449), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((19839, 19850), 'time.time', 'time.time', ([], {}), '()\n', (19848, 19850), False, 'import time\n'), ((29030, 29073), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', (['self._data_tree_item'], {}), '(self._data_tree_item)\n', (29051, 29073), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((29814, 29829), 'qtconsole.qt.QtCore.QTimer', 'QtCore.QTimer', ([], {}), '()\n', (29827, 29829), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((29942, 29959), 'bazel_tools.tools.python.runfiles.runfiles.Create', 'runfiles.Create', ([], {}), '()\n', (29957, 29959), False, 'from bazel_tools.tools.python.runfiles import runfiles\n'), ((30084, 30105), 'PySide.QtUiTools.QUiLoader', 'QtUiTools.QUiLoader', ([], {}), '()\n', (30103, 30105), False, 'from PySide import QtUiTools\n'), ((30123, 30147), 'qtconsole.qt.QtCore.QFile', 'QtCore.QFile', (['uifilename'], {}), '(uifilename)\n', (30135, 30147), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((31614, 31657), 'qtconsole.qt.QtGui.QVBoxLayout', 'QtGui.QVBoxLayout', (['self.ui.plotHolderWidget'], {}), '(self.ui.plotHolderWidget)\n', (31631, 31657), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((32060, 32109), 'qtconsole.qt.QtCore.QTimer.singleShot', 'QtCore.QTimer.singleShot', (['(0)', 'self._handle_startup'], {}), '(0, self._handle_startup)\n', (32084, 32109), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((34543, 34554), 'time.time', 'time.time', ([], {}), '()\n', (34552, 34554), False, 'import time\n'), ((35993, 36013), 'qtconsole.qt.QtGui.QMenu', 'QtGui.QMenu', (['self.ui'], {}), '(self.ui)\n', (36004, 36013), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((7544, 7589), 'struct.unpack', 'struct.unpack', (['"""<HBB"""', 'result_frame_start[:4]'], {}), "('<HBB', result_frame_start[:4])\n", (7557, 7589), False, 'import struct\n'), ((9573, 9600), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', (['item'], {}), '(item)\n', (9594, 9600), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((13810, 13840), 'matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg.draw', 'FigureCanvas.draw', (['self.canvas'], {}), '(self.canvas)\n', (13827, 13840), True, 'from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n'), ((20229, 20240), 'time.time', 'time.time', ([], {}), '()\n', (20238, 20240), False, 'import time\n'), ((26932, 26950), 'io.BytesIO', 'io.BytesIO', (['schema'], {}), '(schema)\n', (26942, 26950), False, 'import io\n'), ((28050, 28088), 'struct.unpack', 'struct.unpack', (['"""<I"""', 'self._buffer[1:5]'], {}), "('<I', self._buffer[1:5])\n", (28063, 28088), False, 'import struct\n'), ((33276, 33299), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', ([], {}), '()\n', (33297, 33299), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((33442, 33465), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', ([], {}), '()\n', (33463, 33465), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((34641, 34669), 're.search', 're.search', (['"""^:(\\\\d+)$"""', 'line'], {}), "('^:(\\\\d+)$', line)\n", (34650, 34669), False, 'import re\n'), ((34694, 34728), 're.search', 're.search', (['"""^(A|\\\\d+)>(.*)$"""', 'line'], {}), "('^(A|\\\\d+)>(.*)$', line)\n", (34703, 34728), False, 'import re\n'), ((39512, 39523), 'os._exit', 'os._exit', (['(0)'], {}), '(0)\n', (39520, 39523), False, 'import os\n'), ((16839, 16850), 'time.time', 'time.time', ([], {}), '()\n', (16848, 16850), False, 'import time\n'), ((17913, 17930), 'numpy.std', 'numpy.std', (['values'], {}), '(values)\n', (17922, 17930), False, 'import numpy\n'), ((23806, 23851), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', (['self._config_tree_item'], {}), '(self._config_tree_item)\n', (23827, 23851), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((32641, 32729), 'serial.Serial', 'serial.Serial', ([], {'port': 'self.options.serial', 'baudrate': 'self.options.baudrate', 'timeout': '(0.0)'}), '(port=self.options.serial, baudrate=self.options.baudrate,\n timeout=0.0)\n', (32654, 32729), False, 'import serial\n'), ((34056, 34091), 'os.path.exists', 'os.path.exists', (['self.options.serial'], {}), '(self.options.serial)\n', (34070, 34091), False, 'import os\n'), ((35358, 35408), 'qtconsole.qt.QtCore.QTimer.singleShot', 'QtCore.QTimer.singleShot', (['current_delay_ms', 'writer'], {}), '(current_delay_ms, writer)\n', (35382, 35408), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((18124, 18142), 'numpy.mean', 'numpy.mean', (['values'], {}), '(values)\n', (18134, 18142), False, 'import numpy\n'), ((24805, 24832), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', (['item'], {}), '(item)\n', (24826, 24832), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((27653, 27669), 'io.BytesIO', 'io.BytesIO', (['data'], {}), '(data)\n', (27663, 27669), False, 'import io\n'), ((29414, 29443), 'qtconsole.qt.QtGui.QTreeWidgetItem', 'QtGui.QTreeWidgetItem', (['parent'], {}), '(parent)\n', (29435, 29443), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((37869, 37899), 'qtconsole.qt.QtGui.QApplication.clipboard', 'QtGui.QApplication.clipboard', ([], {}), '()\n', (37897, 37899), False, 'from qtconsole.qt import QtCore, QtGui\n'), ((37972, 38002), 'qtconsole.qt.QtGui.QApplication.clipboard', 'QtGui.QApplication.clipboard', ([], {}), '()\n', (38000, 38002), False, 'from qtconsole.qt import QtCore, QtGui\n')]
"""Internal (private) Utilities Module.""" import logging import math import os from typing import Any, Dict, Generator, List, Optional, Tuple import boto3 # type: ignore import botocore.config # type: ignore import numpy as np # type: ignore import psycopg2 # type: ignore import s3fs # type: ignore logger: logging.Logger = logging.getLogger(__name__) def ensure_session(session: Optional[boto3.Session] = None) -> boto3.Session: """Ensure that a valid boto3.Session will be returned.""" if session is not None: return session return boto3.Session() def client(service_name: str, session: Optional[boto3.Session] = None) -> boto3.client: """Create a valid boto3.client.""" return ensure_session(session=session).client( service_name=service_name, use_ssl=True, config=botocore.config.Config(retries={"max_attempts": 15}) ) def resource(service_name: str, session: Optional[boto3.Session] = None) -> boto3.resource: """Create a valid boto3.resource.""" return ensure_session(session=session).resource( service_name=service_name, use_ssl=True, config=botocore.config.Config(retries={"max_attempts": 15}) ) def parse_path(path: str) -> Tuple[str, str]: """Split a full S3 path in bucket and key strings. 's3://bucket/key' -> ('bucket', 'key') Parameters ---------- path : str S3 path (e.g. s3://bucket/key). Returns ------- Tuple[str, str] Tuple of bucket and key strings Examples -------- >>> from awswrangler._utils import parse_path >>> bucket, key = parse_path('s3://bucket/key') """ parts = path.replace("s3://", "").split("/", 1) bucket: str = parts[0] key: str = "" if len(parts) == 2: key = key if parts[1] is None else parts[1] return bucket, key def ensure_cpu_count(use_threads: bool = True) -> int: """Get the number of cpu cores to be used. Note ---- In case of `use_threads=True` the number of threads that could be spawned will be get from os.cpu_count(). Parameters ---------- use_threads : bool True to enable multi-core utilization, False to disable. Returns ------- int Number of cpu cores to be used. Examples -------- >>> from awswrangler._utils import ensure_cpu_count >>> ensure_cpu_count(use_threads=True) 4 >>> ensure_cpu_count(use_threads=False) 1 """ cpus: int = 1 if use_threads is True: cpu_cnt: Optional[int] = os.cpu_count() if cpu_cnt is not None: cpus = cpu_cnt if cpu_cnt > cpus else cpus return cpus def chunkify(lst: List[Any], num_chunks: int = 1, max_length: Optional[int] = None) -> List[List[Any]]: """Split a list in a List of List (chunks) with even sizes. Parameters ---------- lst: List List of anything to be splitted. num_chunks: int, optional Maximum number of chunks. max_length: int, optional Max length of each chunk. Has priority over num_chunks. Returns ------- List[List[Any]] List of List (chunks) with even sizes. Examples -------- >>> from awswrangler._utils import chunkify >>> chunkify(list(range(13)), num_chunks=3) [[0, 1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] >>> chunkify(list(range(13)), max_length=4) [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] """ n: int = num_chunks if max_length is None else int(math.ceil((float(len(lst)) / float(max_length)))) np_chunks = np.array_split(lst, n) return [arr.tolist() for arr in np_chunks if len(arr) > 0] def get_fs( session: Optional[boto3.Session] = None, s3_additional_kwargs: Optional[Dict[str, str]] = None ) -> s3fs.S3FileSystem: """Build a S3FileSystem from a given boto3 session.""" fs: s3fs.S3FileSystem = s3fs.S3FileSystem( anon=False, use_ssl=True, default_cache_type="none", default_fill_cache=False, default_block_size=134_217_728, # 128 MB (50 * 2**20) config_kwargs={"retries": {"max_attempts": 15}}, session=ensure_session(session=session)._session, # pylint: disable=protected-access s3_additional_kwargs=s3_additional_kwargs, use_listings_cache=False, skip_instance_cache=True, ) fs.invalidate_cache() fs.clear_instance_cache() return fs def empty_generator() -> Generator: """Empty Generator.""" yield from () def ensure_postgresql_casts(): """Ensure that psycopg2 will handle some data types right.""" psycopg2.extensions.register_adapter(bytes, psycopg2.Binary) typecast_bytea = lambda data, cur: None if data is None else bytes(psycopg2.BINARY(data, cur)) # noqa BYTEA = psycopg2.extensions.new_type(psycopg2.BINARY.values, "BYTEA", typecast_bytea) psycopg2.extensions.register_type(BYTEA) def get_directory(path: str) -> str: """Extract directory path.""" return path.rsplit(sep="/", maxsplit=1)[0] + "/"
[ "boto3.Session", "psycopg2.extensions.register_adapter", "psycopg2.extensions.register_type", "os.cpu_count", "psycopg2.extensions.new_type", "numpy.array_split", "psycopg2.BINARY", "logging.getLogger" ]
[((334, 361), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (351, 361), False, 'import logging\n'), ((566, 581), 'boto3.Session', 'boto3.Session', ([], {}), '()\n', (579, 581), False, 'import boto3\n'), ((3565, 3587), 'numpy.array_split', 'np.array_split', (['lst', 'n'], {}), '(lst, n)\n', (3579, 3587), True, 'import numpy as np\n'), ((4600, 4660), 'psycopg2.extensions.register_adapter', 'psycopg2.extensions.register_adapter', (['bytes', 'psycopg2.Binary'], {}), '(bytes, psycopg2.Binary)\n', (4636, 4660), False, 'import psycopg2\n'), ((4780, 4857), 'psycopg2.extensions.new_type', 'psycopg2.extensions.new_type', (['psycopg2.BINARY.values', '"""BYTEA"""', 'typecast_bytea'], {}), "(psycopg2.BINARY.values, 'BYTEA', typecast_bytea)\n", (4808, 4857), False, 'import psycopg2\n'), ((4862, 4902), 'psycopg2.extensions.register_type', 'psycopg2.extensions.register_type', (['BYTEA'], {}), '(BYTEA)\n', (4895, 4902), False, 'import psycopg2\n'), ((2532, 2546), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (2544, 2546), False, 'import os\n'), ((4732, 4758), 'psycopg2.BINARY', 'psycopg2.BINARY', (['data', 'cur'], {}), '(data, cur)\n', (4747, 4758), False, 'import psycopg2\n')]
import pandas as pd import numpy as np import time import os, csv from nsepython import * from datetime import date from dateutil.relativedelta import relativedelta from bfxhfindicators import Stochastic entryTargets = [] params = { 'access_key': 'fce4047d20b3b06c7393ed8093e0574d' } def isDoji(out): wicks = abs(out[1] - out[2]) body = abs(out[0] - out[3]) percentage = 100 / (wicks/body) if (percentage <= 33): return out def stochastic(candles): stochValues = [] iStoch = Stochastic(5, 3, 3) for candle in candles: iStoch.add(candle) stochValues.append(iStoch.v()) return (stochValues) def HEIKIN(O, H, L, C, oldO, oldC): HA_Open = (oldO + oldC)/2 HA_Close = (O + H + L + C)/4 elements = np.array([H, L, HA_Open, HA_Close]) HA_High = elements.max(0) HA_Low = elements.min(0) out = [HA_Open, HA_High, HA_Low, HA_Close] return out def maxMin(fiboRange): rangeMax = max(max(x) if isinstance(x, list) else x for x in fiboRange) rangeMin = min(min(x) if isinstance(x, list) else x for x in fiboRange) return (rangeMax, rangeMin) def fibonacciDown(price_max, price_min): tempList = [] diff = price_max - price_min level0 = price_max level1 = price_max - 0.236 * diff level2 = price_max - 0.382 * diff level3 = price_max - 0.50 * diff level4 = price_max - 0.618 * diff level5 = price_max - 0.786 * diff tempList = [level1, level2, level3, level4, level5, level0] entryTargets.append(tempList) return entryTargets def fibonacciUp(price_max, price_min): tempList = [] diff = price_max - price_min level0 = price_max - 1.0 * diff level1 = price_max - 0.786 * diff level2 = price_max - 0.618 * diff level3 = price_max - 0.50 * diff level4 = price_max - 0.366 * diff level5 = price_max - 0.236 * diff tempList = [level1, level2, level3, level4, level5, level0] entryTargets.append(tempList) return entryTargets def main(): # start = time.time() while(True): os.system(['clear', 'cls'][os.name == 'nt']) j = 0 openPrice = [] highPrice = [] lowPrice = [] closePrice = [] hikenCandle = [] doji = [] swing = [] dateTime = [] allCall = [] dates = [] print("---------------------------------") print("|\tSTOCK MARKET ANALYSIS\t|") print("---------------------------------") print() try: df = pd.read_csv('tcs.csv') # YAHA PE DOWNLOADED CSV FILE (DATA FILE) KA NAAM for data in df.index[::-1]: openPrice.append(df['Open Price'][data]) highPrice.append(df['High Price'][data]) lowPrice.append(df['Low Price'][data]) closePrice.append(df['Close Price'][data]) dates.append(df['Date'][data]) n = len(openPrice) - 2 candle = HEIKIN(openPrice[n], highPrice[n], lowPrice[n], closePrice[n], openPrice[n+1], closePrice[n+1]) hikenCandle.append(candle) for i in range(n-1, -1, -1): candle = HEIKIN(openPrice[i], highPrice[i], lowPrice[i], closePrice[i], hikenCandle[j][0], hikenCandle[j][3]) hikenCandle.append(candle) dateTime.append(dates[i]) j += 1 stochasticHiken = stochastic(hikenCandle) del stochasticHiken[:4] for i in hikenCandle: doji.append(isDoji(i)) del doji[:4] del dateTime[:3] for i in range(1, len(stochasticHiken)): if ((stochasticHiken[i]['k'] < stochasticHiken[i]['d']) and stochasticHiken[i-1]['k'] > stochasticHiken[i-1]['d']) or ((stochasticHiken[i]['k'] > stochasticHiken[i]['d']) and stochasticHiken[i-1]['k'] < stochasticHiken[i-1]['d']): swing.append(i) for i in range(len(stochasticHiken)): if (stochasticHiken[i]['k'] < stochasticHiken[i]['d'] and stochasticHiken[i-1]['k'] > stochasticHiken[i-1]['d']): try: if doji[i]: if i != 0: swingIndex = swing.index(i) if swingIndex != 0: temp = maxMin( hikenCandle[swing[swingIndex-1] + 4: swing[swingIndex] + 4]) testList = fibonacciDown( temp[0], temp[1]) lastCandle = i allCall.append(dateTime[i]) elif doji[i-1] or doji[i+1] or doji[i+2]: if i != 0: swingIndex = swing.index(i) if swingIndex != 0: temp = maxMin( hikenCandle[swing[swingIndex-1] + 4: swing[swingIndex] + 4]) testList = fibonacciDown( temp[0], temp[1]) lastCandle = i allCall.append(dateTime[i]) except (IndexError): pass elif (stochasticHiken[i]['k'] > stochasticHiken[i]['d'] and stochasticHiken[i-1]['k'] < stochasticHiken[i-1]['d']): try: if doji[i]: if i != 0: swingIndex = swing.index(i) if swingIndex > 0: temp = maxMin( hikenCandle[swing[swingIndex-1] + 4: swing[swingIndex] + 4]) testList = fibonacciUp( temp[0], temp[1]) lastCandle = i allCall.append(dateTime[i]) elif doji[i-1] or doji[i+1] or doji[i+2]: if i != 0: swingIndex = swing.index(i) if swingIndex > 0: temp = maxMin( hikenCandle[swing[swingIndex-1] + 4: swing[swingIndex] + 4]) testList = fibonacciUp( temp[0], temp[1]) lastCandle = i allCall.append(dateTime[i]) except (IndexError): pass os.system(['clear', 'cls'][os.name == 'nt']) with open(df['Symbol'][0]+"_REPORT.csv", 'w', newline='') as f: fieldnames = ['Symbol', 'Date', 'Call','Stop_Loss', 'Target_1', 'Target_2', 'Target_3', 'Target_4', 'Trend'] thewriter = csv.DictWriter(f, fieldnames=fieldnames) thewriter.writeheader() for i in range(len(testList)): with open(df['Symbol'][0]+"_REPORT.csv", 'a+', newline='') as f: fieldnames = ['Symbol', 'Date', 'Call', 'Stop_Loss', 'Target_1', 'Target_2', 'Target_3', 'Target_4', 'Trend'] thewriter = csv.DictWriter(f, fieldnames=fieldnames) if testList[i][0] > testList[i][5]: trend = "BUY" else: trend = "SELL" thewriter.writerow( {'Symbol': df['Symbol'][0], 'Date': allCall[i], 'Call': round(testList[i][0],2), 'Stop_Loss': round(testList[i][5],2), 'Target_1': round(testList[i][1],2), 'Target_2': round(testList[i][2],2), 'Target_3': round(testList[i][3],2), 'Target_4': round(testList[i][4],2), 'Trend': trend, }) print("-----------------------------------------") print("|\t", df['Symbol'][0], "- DATE:", allCall[i], "\t|") print("-----------------------------------------") if (testList[i][0] > testList[-1][5]): print("| Buy Above\t|\t", round(testList[i][0], 2), "\t|") else: print("| Sell Below\t|\t", round( testList[i][0], 2), "\t|") print("| Stop Loss\t|\t", round(testList[i][5], 2), "\t|") print("| Target-1 \t|\t", round(testList[i][1], 2), "\t|") print("| Target-2 \t|\t", round(testList[i][2], 2), "\t|") print("| Target-3 \t|\t", round(testList[i][3], 2), "\t|") print("| Target-4 \t|\t", round(testList[i][4], 2), "\t|") print("-----------------------------------------") print() input("Press enter to exit... ") exit() except (KeyError): keyerror = True # end = time.time() # print(f"Runtime of the program is {end - start}") main()
[ "pandas.read_csv", "os.system", "numpy.array", "bfxhfindicators.Stochastic", "csv.DictWriter" ]
[((518, 537), 'bfxhfindicators.Stochastic', 'Stochastic', (['(5)', '(3)', '(3)'], {}), '(5, 3, 3)\n', (528, 537), False, 'from bfxhfindicators import Stochastic\n'), ((772, 807), 'numpy.array', 'np.array', (['[H, L, HA_Open, HA_Close]'], {}), '([H, L, HA_Open, HA_Close])\n', (780, 807), True, 'import numpy as np\n'), ((2076, 2120), 'os.system', 'os.system', (["['clear', 'cls'][os.name == 'nt']"], {}), "(['clear', 'cls'][os.name == 'nt'])\n", (2085, 2120), False, 'import os, csv\n'), ((2545, 2567), 'pandas.read_csv', 'pd.read_csv', (['"""tcs.csv"""'], {}), "('tcs.csv')\n", (2556, 2567), True, 'import pandas as pd\n'), ((6929, 6973), 'os.system', 'os.system', (["['clear', 'cls'][os.name == 'nt']"], {}), "(['clear', 'cls'][os.name == 'nt'])\n", (6938, 6973), False, 'import os, csv\n'), ((7204, 7244), 'csv.DictWriter', 'csv.DictWriter', (['f'], {'fieldnames': 'fieldnames'}), '(f, fieldnames=fieldnames)\n', (7218, 7244), False, 'import os, csv\n'), ((7604, 7644), 'csv.DictWriter', 'csv.DictWriter', (['f'], {'fieldnames': 'fieldnames'}), '(f, fieldnames=fieldnames)\n', (7618, 7644), False, 'import os, csv\n')]
import numpy as np import simtk.openmm as mm from simtk.openmm.app import Simulation from ..unit import * class DrudeTemperatureReporter(object): ''' DrudeTemperatureReporter reports the temperatures of different DOFs in a Drude simulation system. The temperatures for three sets of degrees of freedom are reported -- molecular center of mass, internal atomic and Drude temperature. It's better to set the reportInterval larger than 10000 to avoid performance penalty Parameters ---------- file : string The file to write to reportInterval : int The interval (in time steps) at which to write frames append : bool Whether or not append to existing file ''' def __init__(self, file, reportInterval, append=False): self._reportInterval = reportInterval if append: self._out = open(file, 'a') else: self._out = open(file, 'w') self._hasInitialized = False def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters ---------- simulation : Simulation The Simulation to generate a report for Returns ------- tuple A six element tuple. The first element is the number of steps until the next report. The next four elements specify whether that report will require positions, velocities, forces, and energies respectively. The final element specifies whether positions should be wrapped to lie in a single periodic box. """ steps = self._reportInterval - simulation.currentStep%self._reportInterval return (steps, False, True, False, False) def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ system: mm.System = simulation.system if not self._hasInitialized: self.n_atom = system.getNumParticles() self.molecules: [[int]] = [list(atoms) for atoms in simulation.context.getMolecules()] self.n_mol = len(self.molecules) self.mol_atoms = np.zeros(self.n_atom, dtype=int) # record which molecule the atoms are in self.mass_molecules = np.zeros(self.n_mol) # record the mass of molecules for i, atoms in enumerate(self.molecules): for atom in atoms: self.mol_atoms[atom] = i self.mass_molecules[i] += system.getParticleMass(atom).value_in_unit(unit.dalton) self.dof_com = np.count_nonzero(self.mass_molecules) * 3 self.dof_atom = self.dof_drude = 0 for i in range(self.n_atom): if system.getParticleMass(i) > 0 * unit.dalton: self.dof_atom += 3 self.dof_atom -= (self.dof_com + system.getNumConstraints()) if any(type(f) == mm.CMMotionRemover for f in system.getForces()): self.dof_com -= 3 drude_set = set() self.pair_set = set() force = next(f for f in system.getForces() if type(f) == mm.DrudeForce) self.dof_atom -= 3 * force.getNumParticles() self.dof_drude += 3 * force.getNumParticles() for i in range(force.getNumParticles()): i_drude, i_core = force.getParticleParameters(i)[:2] drude_set.add(i_drude) self.pair_set.add((i_drude, i_core)) self.drude_array = np.array(list(drude_set)) self.atom_array = np.array(list(set(range(self.n_atom)) - drude_set)) self._hasInitialized = True print('#"Step"\t"T_COM"\t"T_Atom"\t"T_Drude"\t"KE_COM"\t"KE_Atom"\t"KE_Drude"', file=self._out) velocities = state.getVelocities(asNumpy=True).value_in_unit(unit.nanometer / unit.picosecond) masses = np.array([system.getParticleMass(i).value_in_unit(unit.dalton) for i in range(self.n_atom)]) vel_mol = np.zeros([self.n_mol, 3]) for i, atoms in enumerate(self.molecules): if self.mass_molecules[i] == 0: continue mv = masses[atoms][:, np.newaxis] * velocities[atoms] vel_mol[i] = np.sum(mv, axis=0) / self.mass_molecules[i] mvv_com = self.mass_molecules * np.sum(vel_mol ** 2, axis=1) ke_com = mvv_com.sum() / 2 * (unit.nanometer / unit.picosecond) ** 2 * unit.dalton t_com = (2 * ke_com / (self.dof_com * unit.MOLAR_GAS_CONSTANT_R)) velocities -= np.array([vel_mol[self.mol_atoms[i]] for i in range(self.n_atom)]) for i_drude, i_core in self.pair_set: v_drude = velocities[i_drude] v_core = velocities[i_core] m_drude = masses[i_drude] m_core = masses[i_core] m_com = m_drude + m_core m_rel = m_drude * m_core / m_com v_com = (m_drude * v_drude + m_core * v_core) / m_com v_rel = v_drude - v_core velocities[i_drude] = v_rel velocities[i_core] = v_com masses[i_drude] = m_rel masses[i_core] = m_com mvv = masses * np.sum(velocities ** 2, axis=1) ke = mvv[self.atom_array].sum() / 2 * (unit.nanometer / unit.picosecond) ** 2 * unit.dalton ke_drude = mvv[self.drude_array].sum() / 2 * (unit.nanometer / unit.picosecond) ** 2 * unit.dalton t = (2 * ke / (self.dof_atom * unit.MOLAR_GAS_CONSTANT_R)) t_drude = (2 * ke_drude / (self.dof_drude * unit.MOLAR_GAS_CONSTANT_R)) print(simulation.currentStep, t_com.value_in_unit(kelvin), t.value_in_unit(kelvin), t_drude.value_in_unit(kelvin), ke_com.value_in_unit(kJ_mol), ke.value_in_unit(kJ_mol), ke_drude.value_in_unit(kJ_mol), sep='\t', file=self._out) if hasattr(self._out, 'flush') and callable(self._out.flush): self._out.flush() def __del__(self): self._out.close()
[ "numpy.count_nonzero", "numpy.zeros", "numpy.sum" ]
[((4217, 4242), 'numpy.zeros', 'np.zeros', (['[self.n_mol, 3]'], {}), '([self.n_mol, 3])\n', (4225, 4242), True, 'import numpy as np\n'), ((2372, 2404), 'numpy.zeros', 'np.zeros', (['self.n_atom'], {'dtype': 'int'}), '(self.n_atom, dtype=int)\n', (2380, 2404), True, 'import numpy as np\n'), ((2481, 2501), 'numpy.zeros', 'np.zeros', (['self.n_mol'], {}), '(self.n_mol)\n', (2489, 2501), True, 'import numpy as np\n'), ((4538, 4566), 'numpy.sum', 'np.sum', (['(vel_mol ** 2)'], {'axis': '(1)'}), '(vel_mol ** 2, axis=1)\n', (4544, 4566), True, 'import numpy as np\n'), ((5382, 5413), 'numpy.sum', 'np.sum', (['(velocities ** 2)'], {'axis': '(1)'}), '(velocities ** 2, axis=1)\n', (5388, 5413), True, 'import numpy as np\n'), ((2798, 2835), 'numpy.count_nonzero', 'np.count_nonzero', (['self.mass_molecules'], {}), '(self.mass_molecules)\n', (2814, 2835), True, 'import numpy as np\n'), ((4454, 4472), 'numpy.sum', 'np.sum', (['mv'], {'axis': '(0)'}), '(mv, axis=0)\n', (4460, 4472), True, 'import numpy as np\n')]
"""Module with utility functions for generating annotations.""" from jicbioimage.transform import mean_intensity_projection from jicbioimage.illustrate import AnnotatedImage from utils import mean_plot_intensity, plot_identifier import numpy as np #def quick_grayscale_ann(image): def get_grayscale_ann(image): """Return AnnotatedImage with field in grayscale.""" grayscale = np.mean(image, axis=2) ann = AnnotatedImage.from_grayscale(grayscale) return ann def color_in_plots(ann, image, plots): """Return AnnotatedImage with plots coloured in.""" for i in plots.identifiers: region = plots.region_by_identifier(i) ann[region] = image[region] return ann def outline_plots(ann, image, plots): """Outline plots with mean intensity colour.""" for i in plots.identifiers: region = plots.region_by_identifier(i) red = mean_plot_intensity(image, region, 0) green = mean_plot_intensity(image, region, 1) blue = mean_plot_intensity(image, region, 2) color = (red, green, blue) ann.mask_region(region.border.dilate(7), color=color) return ann def overlay_text(ann, image, plots, name): """Add text annotation.""" for i in plots.identifiers: region = plots.region_by_identifier(i) red = mean_plot_intensity(image, region, 0) green = mean_plot_intensity(image, region, 1) blue = mean_plot_intensity(image, region, 2) offset = (region.centroid[0] - 120, region.centroid[1]) ann.text_at(plot_identifier(name, i), offset, size=56, center=True) offset = (region.centroid[0] - 60, region.centroid[1]) ann.text_at("R: {:5.1f}".format(red), offset, size=56, center=True) ann.text_at("G: {:5.1f}".format(green), region.centroid, size=56, center=True) offset = (region.centroid[0] + 60, region.centroid[1]) ann.text_at("B: {:5.1f}".format(blue), offset, size=56, center=True) return ann
[ "utils.mean_plot_intensity", "numpy.mean", "utils.plot_identifier", "jicbioimage.illustrate.AnnotatedImage.from_grayscale" ]
[((389, 411), 'numpy.mean', 'np.mean', (['image'], {'axis': '(2)'}), '(image, axis=2)\n', (396, 411), True, 'import numpy as np\n'), ((422, 462), 'jicbioimage.illustrate.AnnotatedImage.from_grayscale', 'AnnotatedImage.from_grayscale', (['grayscale'], {}), '(grayscale)\n', (451, 462), False, 'from jicbioimage.illustrate import AnnotatedImage\n'), ((891, 928), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(0)'], {}), '(image, region, 0)\n', (910, 928), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((945, 982), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(1)'], {}), '(image, region, 1)\n', (964, 982), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((998, 1035), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(2)'], {}), '(image, region, 2)\n', (1017, 1035), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((1319, 1356), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(0)'], {}), '(image, region, 0)\n', (1338, 1356), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((1373, 1410), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(1)'], {}), '(image, region, 1)\n', (1392, 1410), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((1426, 1463), 'utils.mean_plot_intensity', 'mean_plot_intensity', (['image', 'region', '(2)'], {}), '(image, region, 2)\n', (1445, 1463), False, 'from utils import mean_plot_intensity, plot_identifier\n'), ((1549, 1573), 'utils.plot_identifier', 'plot_identifier', (['name', 'i'], {}), '(name, i)\n', (1564, 1573), False, 'from utils import mean_plot_intensity, plot_identifier\n')]
from copy import deepcopy import numpy as np import openmm import pytest from openff.toolkit.topology import Molecule, Topology from openff.toolkit.typing.engines.smirnoff import ForceField from openff.units import unit from openff.utilities.testing import skip_if_missing from openmm import app from openmm import unit as openmm_unit from openff.interchange.components.interchange import Interchange from openff.interchange.drivers import get_openmm_energies from openff.interchange.drivers.openmm import _get_openmm_energies from openff.interchange.drivers.report import EnergyError, EnergyReport from openff.interchange.testing.utils import ( HAS_GROMACS, HAS_LAMMPS, needs_gmx, needs_lmp, ) from openff.interchange.utils import get_test_file_path if HAS_GROMACS: from openff.interchange.drivers.gromacs import ( _get_mdp_file, _run_gmx_energy, get_gromacs_energies, ) if HAS_LAMMPS: from openff.interchange.drivers.lammps import get_lammps_energies kj_mol = unit.kilojoule / unit.mol def test_energy_report(): """Test that multiple failing energies are captured in the EnergyError""" a = EnergyReport( energies={ "a": 1 * kj_mol, "_FLAG": 2 * kj_mol, "KEY_": 1.2 * kj_mol, } ) b = EnergyReport( energies={ "a": -1 * kj_mol, "_FLAG": -2 * kj_mol, "KEY_": -0.1 * kj_mol, } ) custom_tolerances = { "a": 1 * kj_mol, "_FLAG": 1 * kj_mol, "KEY_": 1 * kj_mol, } with pytest.raises(EnergyError, match=r"_FLAG[\s\S]*KEY_"): a.compare(b, custom_tolerances=custom_tolerances) @skip_if_missing("mbuild") @needs_gmx @needs_lmp @pytest.mark.xfail() @pytest.mark.slow() @pytest.mark.parametrize("constrained", [True, False]) @pytest.mark.parametrize("mol_smi", ["C"]) # ["C", "CC"] def test_energies_single_mol(constrained, mol_smi): import mbuild as mb mol = Molecule.from_smiles(mol_smi) mol.generate_conformers(n_conformers=1) mol.name = "FOO" top = mol.to_topology() top.box_vectors = None # [10, 10, 10] * openmm_unit.nanometer if constrained: parsley = ForceField("openff-1.0.0.offxml") else: parsley = ForceField("openff_unconstrained-1.0.0.offxml") off_sys = Interchange.from_smirnoff(parsley, top) off_sys.handlers["Electrostatics"].method = "cutoff" mol.to_file("out.xyz", file_format="xyz") compound: mb.Compound = mb.load("out.xyz") packed_box: mb.Compound = mb.fill_box( compound=compound, n_compounds=1, box=mb.Box(lengths=[10, 10, 10]) ) positions = packed_box.xyz * unit.nanometer off_sys.positions = positions # Compare directly to toolkit's reference implementation omm_energies = get_openmm_energies(off_sys, round_positions=8) omm_reference = parsley.create_openmm_system(top) reference_energies = _get_openmm_energies( omm_sys=omm_reference, box_vectors=off_sys.box, positions=off_sys.positions, round_positions=8, ) omm_energies.compare(reference_energies) mdp = "cutoff_hbonds" if constrained else "auto" # Compare GROMACS writer and OpenMM export gmx_energies = get_gromacs_energies(off_sys, mdp=mdp) custom_tolerances = { "Bond": 2e-5 * openmm_unit.kilojoule_per_mole, "Electrostatics": 2 * openmm_unit.kilojoule_per_mole, "vdW": 2 * openmm_unit.kilojoule_per_mole, "Nonbonded": 2 * openmm_unit.kilojoule_per_mole, "Angle": 1e-4 * openmm_unit.kilojoule_per_mole, } gmx_energies.compare( omm_energies, custom_tolerances=custom_tolerances, ) if not constrained: other_energies = get_openmm_energies( off_sys, round_positions=8, hard_cutoff=True, electrostatics=True, ) lmp_energies = get_lammps_energies(off_sys) custom_tolerances = { "vdW": 5.0 * openmm_unit.kilojoule_per_mole, "Electrostatics": 5.0 * openmm_unit.kilojoule_per_mole, } lmp_energies.compare(other_energies, custom_tolerances=custom_tolerances) @needs_gmx @needs_lmp @pytest.mark.slow() def test_liquid_argon(): argon = Molecule.from_smiles("[#18]") pdbfile = app.PDBFile(get_test_file_path("packed-argon.pdb")) top = Topology.from_openmm(pdbfile.topology, unique_molecules=[argon]) argon_ff = ForceField(get_test_file_path("argon.offxml")) out = Interchange.from_smirnoff(argon_ff, top) out.positions = pdbfile.positions omm_energies = get_openmm_energies(out) gmx_energies = get_gromacs_energies( out, mdp="auto", writer="internal", ) omm_energies.compare( gmx_energies, custom_tolerances={ "vdW": 0.009 * openmm_unit.kilojoule_per_mole, }, ) argon_ff_no_switch = deepcopy(argon_ff) argon_ff_no_switch["vdW"].switch_width *= 0 out_no_switch = Interchange.from_smirnoff(argon_ff_no_switch, top) out_no_switch.positions = pdbfile.positions lmp_energies = get_lammps_energies(out_no_switch) omm_energies.compare( lmp_energies, custom_tolerances={ "vdW": 10.5 * openmm_unit.kilojoule_per_mole, }, ) @needs_gmx @pytest.mark.slow() @pytest.mark.parametrize( "toolkit_file_path", [ "systems/test_systems/1_cyclohexane_1_ethanol.pdb", "systems/test_systems/1_ethanol.pdb", "systems/test_systems/1_ethanol_reordered.pdb", # "systems/test_systems/T4_lysozyme_water_ions.pdb", "systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb", "systems/packmol_boxes/cyclohexane_water.pdb", "systems/packmol_boxes/ethanol_water.pdb", "systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb", ], ) def test_packmol_boxes(toolkit_file_path): # TODO: Isolate a set of systems here instead of using toolkit data # TODO: Fix nonbonded energy differences from openff.toolkit.utils import get_data_file_path pdb_file_path = get_data_file_path(toolkit_file_path) pdbfile = openmm.app.PDBFile(pdb_file_path) unique_molecules = [ Molecule.from_smiles(smi) for smi in [ "CCO", "CCCCO", "C", "CCC", "C1CCCCC1", "O", ] ] omm_topology = pdbfile.topology off_topology = Topology.from_openmm(omm_topology, unique_molecules=unique_molecules) # shim_topology = _OFFBioTop(mdtop=md.Topology.from_openmm(omm_topology)) parsley = ForceField("openff_unconstrained-1.0.0.offxml") off_sys = Interchange.from_smirnoff(parsley, off_topology) off_sys.box = np.asarray( pdbfile.topology.getPeriodicBoxVectors().value_in_unit(openmm_unit.nanometer) ) off_sys.positions = pdbfile.positions sys_from_toolkit = parsley.create_openmm_system(off_topology) omm_energies = get_openmm_energies( off_sys, combine_nonbonded_forces=True, hard_cutoff=True, electrostatics=False ) reference = _get_openmm_energies( sys_from_toolkit, off_sys.box, off_sys.positions, hard_cutoff=True, electrostatics=False, ) try: omm_energies.compare( reference, # custom_tolerances={ # "Electrostatics": 2e-4 * openmm_unit.kilojoule_per_mole, # }, ) except EnergyError as err: if "Torsion" in err.args[0]: from openff.interchange.testing.utils import ( _compare_torsion_forces, _get_force, ) _compare_torsion_forces( _get_force(off_sys.to_openmm(), openmm.PeriodicTorsionForce), _get_force(sys_from_toolkit, openmm.PeriodicTorsionForce), ) # custom_tolerances={"HarmonicBondForce": 1.0} # Compare GROMACS writer and OpenMM export gmx_energies = get_gromacs_energies(off_sys) omm_energies_rounded = get_openmm_energies( off_sys, round_positions=8, hard_cutoff=True, electrostatics=False, ) omm_energies_rounded.compare( other=gmx_energies, custom_tolerances={ "Angle": 1e-2 * openmm_unit.kilojoule_per_mole, "Torsion": 1e-2 * openmm_unit.kilojoule_per_mole, "Electrostatics": 3200 * openmm_unit.kilojoule_per_mole, "vdW": 0.5 * openmm_unit.kilojoule_per_mole, }, ) @needs_lmp @pytest.mark.slow() def test_water_dimer(): tip3p = ForceField(get_test_file_path("tip3p.offxml")) water = Molecule.from_smiles("O") tmp = Topology.from_molecules(2 * [water]) # top = _OFFBioTop(mdtop=md.Topology.from_openmm(tmp.to_openmm())) pdbfile = openmm.app.PDBFile(get_test_file_path("water-dimer.pdb")) positions = pdbfile.positions openff_sys = Interchange.from_smirnoff(tip3p, tmp) openff_sys.positions = positions openff_sys.box = [10, 10, 10] * unit.nanometer omm_energies = get_openmm_energies( openff_sys, hard_cutoff=True, electrostatics=False, combine_nonbonded_forces=True, ) toolkit_energies = _get_openmm_energies( tip3p.create_openmm_system(tmp), openff_sys.box, openff_sys.positions, hard_cutoff=True, electrostatics=False, ) omm_energies.compare(toolkit_energies) # TODO: Fix GROMACS energies by handling SETTLE constraints # gmx_energies, _ = get_gromacs_energies(openff_sys) # compare_gromacs_openmm(omm_energies=omm_energies, gmx_energies=gmx_energies) openff_sys["Electrostatics"].method = "cutoff" omm_energies_cutoff = get_gromacs_energies(openff_sys) lmp_energies = get_lammps_energies(openff_sys) lmp_energies.compare(omm_energies_cutoff) @needs_gmx @skip_if_missing("foyer") @skip_if_missing("mbuild") @pytest.mark.slow() def test_process_rb_torsions(): """Test that the GROMACS driver reports Ryckaert-Bellemans torsions""" import foyer import mbuild as mb oplsaa = foyer.Forcefield(name="oplsaa") ethanol = Molecule.from_smiles("CCO") ethanol.generate_conformers(n_conformers=1) ethanol.generate_unique_atom_names() # Run this OFFMol through MoSDeF infrastructure and OPLS-AA from openff.interchange.components.mbuild import offmol_to_compound my_compound = offmol_to_compound(ethanol) my_compound.box = mb.Box(lengths=[4, 4, 4]) oplsaa = foyer.Forcefield(name="oplsaa") struct = oplsaa.apply(my_compound) struct.save("eth.top", overwrite=True) struct.save("eth.gro", overwrite=True) # Get single-point energies using GROMACS oplsaa_energies = _run_gmx_energy( top_file="eth.top", gro_file="eth.gro", mdp_file=_get_mdp_file("default") ) assert oplsaa_energies.energies["Torsion"].m != 0.0 @needs_gmx def test_gmx_14_energies_exist(): # TODO: Make sure 1-4 energies are accurate, not just existent # Use a molecule with only one 1-4 interaction, and # make it between heavy atoms because H-H 1-4 are weak mol = Molecule.from_smiles("ClC#CCl") mol.name = "HPER" mol.generate_conformers(n_conformers=1) parsley = ForceField("openff-1.0.0.offxml") out = Interchange.from_smirnoff(parsley, mol.to_topology()) out.positions = mol.conformers[0] # Put this molecule in a large box with cut-off electrostatics # to prevent it from interacting with images of itself out.box = [40, 40, 40] out["Electrostatics"].method = "cutoff" gmx_energies = get_gromacs_energies(out) # The only possible non-bonded interactions should be from 1-4 intramolecular interactions assert gmx_energies.energies["vdW"].m != 0.0 assert gmx_energies.energies["Electrostatics"].m != 0.0 # TODO: It would be best to save the 1-4 interactions, split off into vdW and Electrostatics # in the energies. This might be tricky/intractable to do for engines that are not GROMACS @needs_gmx @needs_lmp @pytest.mark.slow() def test_cutoff_electrostatics(): ion_ff = ForceField(get_test_file_path("ions.offxml")) ions = Topology.from_molecules( [ Molecule.from_smiles("[#3]"), Molecule.from_smiles("[#17]"), ] ) # topology = _OFFBioTop(mdtop=md.Topology.from_openmm(ions.to_openmm())) out = Interchange.from_smirnoff(ion_ff, ions) # topology) out.box = [4, 4, 4] * unit.nanometer gmx = [] lmp = [] for d in np.linspace(0.75, 0.95, 5): positions = np.zeros((2, 3)) * unit.nanometer positions[1, 0] = d * unit.nanometer out.positions = positions out["Electrostatics"].method = "cutoff" gmx.append(get_gromacs_energies(out, mdp="auto").energies["Electrostatics"].m) lmp.append( get_lammps_energies(out) .energies["Electrostatics"] .m_as(unit.kilojoule / unit.mol) ) assert np.sum(np.sqrt(np.square(np.asarray(lmp) - np.asarray(gmx)))) < 1e-3 @pytest.mark.parametrize( "smi", [ "C#Cc1ccc(cc1)N", "C=Cc1ccc(cc1)N", "C=Nc1ccc(cc1)N", "CC(=O)Nc1ccc(cc1)N", # "CC(=O)Oc1ccc(cc1)N", "CC(=O)c1ccc(cc1)N", "CC(C)(C)c1ccc(cc1)N", "CN(C)c1ccc(cc1)N", "CNC(=O)c1ccc(cc1)N", # "CNc1ccc(cc1)N", significant energy differences "COC(=O)c1ccc(cc1)N", "COc1ccc(cc1)N", "CS(=O)(=O)Oc1ccc(cc1)N", "CSc1ccc(cc1)N", "C[N+](C)(C)c1ccc(cc1)N", "Cc1ccc(cc1)N", "c1cc(ccc1C#N)N", "c1cc(ccc1C(=O)Cl)N", # "c1cc(ccc1C(=O)N)N", significant energy differences "c1cc(ccc1C(=O)O)N", "c1cc(ccc1C(Br)(Br)Br)N", "c1cc(ccc1C(Cl)(Cl)Cl)N", "c1cc(ccc1C(F)(F)F)N", "c1cc(ccc1C=O)N", "c1cc(ccc1CS(=O)(=O)[O-])N", "c1cc(ccc1N)Br", "c1cc(ccc1N)Cl", "c1cc(ccc1N)F", "c1cc(ccc1N)N", "c1cc(ccc1N)N(=O)=O", "c1cc(ccc1N)N=C=O", "c1cc(ccc1N)N=C=S", # "c1cc(ccc1N)N=[N+]=[N-]", SQM failures "c1cc(ccc1N)NC(=O)N", "c1cc(ccc1N)NO", "c1cc(ccc1N)O", "c1cc(ccc1N)OC#N", # "c1cc(ccc1N)OC(=O)C(F)(F)F", "c1cc(ccc1N)OC(F)(F)F", "c1cc(ccc1N)S", "c1cc(ccc1N)S(=O)(=O)C(F)(F)F", "c1cc(ccc1N)S(=O)(=O)N", "c1cc(ccc1N)SC#N", "c1cc(ccc1N)[N+]#N", "c1cc(ccc1N)[O-]", "c1cc(ccc1N)[S-]", "c1ccc(cc1)Nc2ccc(cc2)N", "c1ccc(cc1)Oc2ccc(cc2)N", "c1ccc(cc1)Sc2ccc(cc2)N", "c1ccc(cc1)c2ccc(cc2)N", ][ :8 ], # TODO: Expand the entire molecule set out into a regression tests ) @needs_gmx @pytest.mark.slow() def test_interpolated_parameters(smi): xml_ff_bo_all_heavy_bonds = """<?xml version='1.0' encoding='ASCII'?> <SMIRNOFF version="0.3" aromaticity_model="OEAroModel_MDL"> <Bonds version="0.3" fractional_bondorder_method="AM1-Wiberg" fractional_bondorder_interpolation="linear"> <Bond smirks="[!#1:1]~[!#1:2]" id="bbo1" k_bondorder1="100.0 * kilocalories_per_mole/angstrom**2" k_bondorder2="1000.0 * kilocalories_per_mole/angstrom**2" length_bondorder1="1.5 * angstrom" length_bondorder2="1.0 * angstrom"/> </Bonds> </SMIRNOFF> """ mol = Molecule.from_smiles(smi) mol.generate_conformers(n_conformers=1) top = mol.to_topology() forcefield = ForceField( "test_forcefields/test_forcefield.offxml", xml_ff_bo_all_heavy_bonds, ) out = Interchange.from_smirnoff(forcefield, top) out.box = [4, 4, 4] * unit.nanometer out.positions = mol.conformers[0] toolkit_system = forcefield.create_openmm_system(top) for key in ["Bond", "Torsion"]: interchange_energy = get_openmm_energies( out, combine_nonbonded_forces=True ).energies[key] toolkit_energy = _get_openmm_energies( toolkit_system, box_vectors=[[4, 0, 0], [0, 4, 0], [0, 0, 4]] * openmm_unit.nanometer, positions=mol.conformers[0], ).energies[key] toolkit_diff = abs(interchange_energy - toolkit_energy).m_as(kj_mol) if toolkit_diff < 1e-6: pass elif toolkit_diff < 1e-2: pytest.xfail( f"Found energy difference of {toolkit_diff} kJ/mol vs. toolkit" ) else: pytest.fail(f"Found energy difference of {toolkit_diff} kJ/mol vs. toolkit") gromacs_energy = get_gromacs_energies(out).energies[key] energy_diff = abs(interchange_energy - gromacs_energy).m_as(kj_mol) if energy_diff < 1e-6: pass elif energy_diff < 1e-2: pytest.xfail( f"Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports" ) else: pytest.fail( f"Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports" )
[ "openff.toolkit.topology.Topology.from_molecules", "pytest.mark.slow", "openff.interchange.drivers.gromacs.get_gromacs_energies", "openff.interchange.components.interchange.Interchange.from_smirnoff", "mbuild.Box", "pytest.xfail", "mbuild.load", "openff.interchange.drivers.report.EnergyReport", "ope...
[((1698, 1723), 'openff.utilities.testing.skip_if_missing', 'skip_if_missing', (['"""mbuild"""'], {}), "('mbuild')\n", (1713, 1723), False, 'from openff.utilities.testing import skip_if_missing\n'), ((1747, 1766), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {}), '()\n', (1764, 1766), False, 'import pytest\n'), ((1768, 1786), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (1784, 1786), False, 'import pytest\n'), ((1788, 1841), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""constrained"""', '[True, False]'], {}), "('constrained', [True, False])\n", (1811, 1841), False, 'import pytest\n'), ((1843, 1884), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mol_smi"""', "['C']"], {}), "('mol_smi', ['C'])\n", (1866, 1884), False, 'import pytest\n'), ((4243, 4261), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (4259, 4261), False, 'import pytest\n'), ((5364, 5382), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (5380, 5382), False, 'import pytest\n'), ((5384, 5809), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""toolkit_file_path"""', "['systems/test_systems/1_cyclohexane_1_ethanol.pdb',\n 'systems/test_systems/1_ethanol.pdb',\n 'systems/test_systems/1_ethanol_reordered.pdb',\n 'systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb',\n 'systems/packmol_boxes/cyclohexane_water.pdb',\n 'systems/packmol_boxes/ethanol_water.pdb',\n 'systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb']"], {}), "('toolkit_file_path', [\n 'systems/test_systems/1_cyclohexane_1_ethanol.pdb',\n 'systems/test_systems/1_ethanol.pdb',\n 'systems/test_systems/1_ethanol_reordered.pdb',\n 'systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb',\n 'systems/packmol_boxes/cyclohexane_water.pdb',\n 'systems/packmol_boxes/ethanol_water.pdb',\n 'systems/packmol_boxes/propane_methane_butanol_0.2_0.3_0.5.pdb'])\n", (5407, 5809), False, 'import pytest\n'), ((8610, 8628), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (8626, 8628), False, 'import pytest\n'), ((9957, 9981), 'openff.utilities.testing.skip_if_missing', 'skip_if_missing', (['"""foyer"""'], {}), "('foyer')\n", (9972, 9981), False, 'from openff.utilities.testing import skip_if_missing\n'), ((9983, 10008), 'openff.utilities.testing.skip_if_missing', 'skip_if_missing', (['"""mbuild"""'], {}), "('mbuild')\n", (9998, 10008), False, 'from openff.utilities.testing import skip_if_missing\n'), ((10010, 10028), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (10026, 10028), False, 'import pytest\n'), ((12148, 12166), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (12164, 12166), False, 'import pytest\n'), ((13162, 14207), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""smi"""', "['C#Cc1ccc(cc1)N', 'C=Cc1ccc(cc1)N', 'C=Nc1ccc(cc1)N', 'CC(=O)Nc1ccc(cc1)N',\n 'CC(=O)c1ccc(cc1)N', 'CC(C)(C)c1ccc(cc1)N', 'CN(C)c1ccc(cc1)N',\n 'CNC(=O)c1ccc(cc1)N', 'COC(=O)c1ccc(cc1)N', 'COc1ccc(cc1)N',\n 'CS(=O)(=O)Oc1ccc(cc1)N', 'CSc1ccc(cc1)N', 'C[N+](C)(C)c1ccc(cc1)N',\n 'Cc1ccc(cc1)N', 'c1cc(ccc1C#N)N', 'c1cc(ccc1C(=O)Cl)N',\n 'c1cc(ccc1C(=O)O)N', 'c1cc(ccc1C(Br)(Br)Br)N', 'c1cc(ccc1C(Cl)(Cl)Cl)N',\n 'c1cc(ccc1C(F)(F)F)N', 'c1cc(ccc1C=O)N', 'c1cc(ccc1CS(=O)(=O)[O-])N',\n 'c1cc(ccc1N)Br', 'c1cc(ccc1N)Cl', 'c1cc(ccc1N)F', 'c1cc(ccc1N)N',\n 'c1cc(ccc1N)N(=O)=O', 'c1cc(ccc1N)N=C=O', 'c1cc(ccc1N)N=C=S',\n 'c1cc(ccc1N)NC(=O)N', 'c1cc(ccc1N)NO', 'c1cc(ccc1N)O',\n 'c1cc(ccc1N)OC#N', 'c1cc(ccc1N)OC(F)(F)F', 'c1cc(ccc1N)S',\n 'c1cc(ccc1N)S(=O)(=O)C(F)(F)F', 'c1cc(ccc1N)S(=O)(=O)N',\n 'c1cc(ccc1N)SC#N', 'c1cc(ccc1N)[N+]#N', 'c1cc(ccc1N)[O-]',\n 'c1cc(ccc1N)[S-]', 'c1ccc(cc1)Nc2ccc(cc2)N', 'c1ccc(cc1)Oc2ccc(cc2)N',\n 'c1ccc(cc1)Sc2ccc(cc2)N', 'c1ccc(cc1)c2ccc(cc2)N'][:8]"], {}), "('smi', ['C#Cc1ccc(cc1)N', 'C=Cc1ccc(cc1)N',\n 'C=Nc1ccc(cc1)N', 'CC(=O)Nc1ccc(cc1)N', 'CC(=O)c1ccc(cc1)N',\n 'CC(C)(C)c1ccc(cc1)N', 'CN(C)c1ccc(cc1)N', 'CNC(=O)c1ccc(cc1)N',\n 'COC(=O)c1ccc(cc1)N', 'COc1ccc(cc1)N', 'CS(=O)(=O)Oc1ccc(cc1)N',\n 'CSc1ccc(cc1)N', 'C[N+](C)(C)c1ccc(cc1)N', 'Cc1ccc(cc1)N',\n 'c1cc(ccc1C#N)N', 'c1cc(ccc1C(=O)Cl)N', 'c1cc(ccc1C(=O)O)N',\n 'c1cc(ccc1C(Br)(Br)Br)N', 'c1cc(ccc1C(Cl)(Cl)Cl)N',\n 'c1cc(ccc1C(F)(F)F)N', 'c1cc(ccc1C=O)N', 'c1cc(ccc1CS(=O)(=O)[O-])N',\n 'c1cc(ccc1N)Br', 'c1cc(ccc1N)Cl', 'c1cc(ccc1N)F', 'c1cc(ccc1N)N',\n 'c1cc(ccc1N)N(=O)=O', 'c1cc(ccc1N)N=C=O', 'c1cc(ccc1N)N=C=S',\n 'c1cc(ccc1N)NC(=O)N', 'c1cc(ccc1N)NO', 'c1cc(ccc1N)O',\n 'c1cc(ccc1N)OC#N', 'c1cc(ccc1N)OC(F)(F)F', 'c1cc(ccc1N)S',\n 'c1cc(ccc1N)S(=O)(=O)C(F)(F)F', 'c1cc(ccc1N)S(=O)(=O)N',\n 'c1cc(ccc1N)SC#N', 'c1cc(ccc1N)[N+]#N', 'c1cc(ccc1N)[O-]',\n 'c1cc(ccc1N)[S-]', 'c1ccc(cc1)Nc2ccc(cc2)N', 'c1ccc(cc1)Oc2ccc(cc2)N',\n 'c1ccc(cc1)Sc2ccc(cc2)N', 'c1ccc(cc1)c2ccc(cc2)N'][:8])\n", (13185, 14207), False, 'import pytest\n'), ((14860, 14878), 'pytest.mark.slow', 'pytest.mark.slow', ([], {}), '()\n', (14876, 14878), False, 'import pytest\n'), ((1158, 1245), 'openff.interchange.drivers.report.EnergyReport', 'EnergyReport', ([], {'energies': "{'a': 1 * kj_mol, '_FLAG': 2 * kj_mol, 'KEY_': 1.2 * kj_mol}"}), "(energies={'a': 1 * kj_mol, '_FLAG': 2 * kj_mol, 'KEY_': 1.2 *\n kj_mol})\n", (1170, 1245), False, 'from openff.interchange.drivers.report import EnergyError, EnergyReport\n'), ((1311, 1401), 'openff.interchange.drivers.report.EnergyReport', 'EnergyReport', ([], {'energies': "{'a': -1 * kj_mol, '_FLAG': -2 * kj_mol, 'KEY_': -0.1 * kj_mol}"}), "(energies={'a': -1 * kj_mol, '_FLAG': -2 * kj_mol, 'KEY_': -0.1 *\n kj_mol})\n", (1323, 1401), False, 'from openff.interchange.drivers.report import EnergyError, EnergyReport\n'), ((1987, 2016), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['mol_smi'], {}), '(mol_smi)\n', (2007, 2016), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((2341, 2380), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['parsley', 'top'], {}), '(parsley, top)\n', (2366, 2380), False, 'from openff.interchange.components.interchange import Interchange\n'), ((2514, 2532), 'mbuild.load', 'mb.load', (['"""out.xyz"""'], {}), "('out.xyz')\n", (2521, 2532), True, 'import mbuild as mb\n'), ((2821, 2868), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['off_sys'], {'round_positions': '(8)'}), '(off_sys, round_positions=8)\n', (2840, 2868), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((2948, 3068), 'openff.interchange.drivers.openmm._get_openmm_energies', '_get_openmm_energies', ([], {'omm_sys': 'omm_reference', 'box_vectors': 'off_sys.box', 'positions': 'off_sys.positions', 'round_positions': '(8)'}), '(omm_sys=omm_reference, box_vectors=off_sys.box,\n positions=off_sys.positions, round_positions=8)\n', (2968, 3068), False, 'from openff.interchange.drivers.openmm import _get_openmm_energies\n'), ((3270, 3308), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['off_sys'], {'mdp': 'mdp'}), '(off_sys, mdp=mdp)\n', (3290, 3308), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((4299, 4328), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""[#18]"""'], {}), "('[#18]')\n", (4319, 4328), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((4406, 4470), 'openff.toolkit.topology.Topology.from_openmm', 'Topology.from_openmm', (['pdbfile.topology'], {'unique_molecules': '[argon]'}), '(pdbfile.topology, unique_molecules=[argon])\n', (4426, 4470), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((4545, 4585), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['argon_ff', 'top'], {}), '(argon_ff, top)\n', (4570, 4585), False, 'from openff.interchange.components.interchange import Interchange\n'), ((4644, 4668), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['out'], {}), '(out)\n', (4663, 4668), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((4689, 4745), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['out'], {'mdp': '"""auto"""', 'writer': '"""internal"""'}), "(out, mdp='auto', writer='internal')\n", (4709, 4745), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((4956, 4974), 'copy.deepcopy', 'deepcopy', (['argon_ff'], {}), '(argon_ff)\n', (4964, 4974), False, 'from copy import deepcopy\n'), ((5044, 5094), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['argon_ff_no_switch', 'top'], {}), '(argon_ff_no_switch, top)\n', (5069, 5094), False, 'from openff.interchange.components.interchange import Interchange\n'), ((5163, 5197), 'openff.interchange.drivers.lammps.get_lammps_energies', 'get_lammps_energies', (['out_no_switch'], {}), '(out_no_switch)\n', (5182, 5197), False, 'from openff.interchange.drivers.lammps import get_lammps_energies\n'), ((6153, 6190), 'openff.toolkit.utils.get_data_file_path', 'get_data_file_path', (['toolkit_file_path'], {}), '(toolkit_file_path)\n', (6171, 6190), False, 'from openff.toolkit.utils import get_data_file_path\n'), ((6205, 6238), 'openmm.app.PDBFile', 'openmm.app.PDBFile', (['pdb_file_path'], {}), '(pdb_file_path)\n', (6223, 6238), False, 'import openmm\n'), ((6508, 6577), 'openff.toolkit.topology.Topology.from_openmm', 'Topology.from_openmm', (['omm_topology'], {'unique_molecules': 'unique_molecules'}), '(omm_topology, unique_molecules=unique_molecules)\n', (6528, 6577), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((6671, 6718), 'openff.toolkit.typing.engines.smirnoff.ForceField', 'ForceField', (['"""openff_unconstrained-1.0.0.offxml"""'], {}), "('openff_unconstrained-1.0.0.offxml')\n", (6681, 6718), False, 'from openff.toolkit.typing.engines.smirnoff import ForceField\n'), ((6734, 6782), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['parsley', 'off_topology'], {}), '(parsley, off_topology)\n', (6759, 6782), False, 'from openff.interchange.components.interchange import Interchange\n'), ((7035, 7139), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['off_sys'], {'combine_nonbonded_forces': '(True)', 'hard_cutoff': '(True)', 'electrostatics': '(False)'}), '(off_sys, combine_nonbonded_forces=True, hard_cutoff=\n True, electrostatics=False)\n', (7054, 7139), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((7165, 7279), 'openff.interchange.drivers.openmm._get_openmm_energies', '_get_openmm_energies', (['sys_from_toolkit', 'off_sys.box', 'off_sys.positions'], {'hard_cutoff': '(True)', 'electrostatics': '(False)'}), '(sys_from_toolkit, off_sys.box, off_sys.positions,\n hard_cutoff=True, electrostatics=False)\n', (7185, 7279), False, 'from openff.interchange.drivers.openmm import _get_openmm_energies\n'), ((8055, 8084), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['off_sys'], {}), '(off_sys)\n', (8075, 8084), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((8113, 8204), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['off_sys'], {'round_positions': '(8)', 'hard_cutoff': '(True)', 'electrostatics': '(False)'}), '(off_sys, round_positions=8, hard_cutoff=True,\n electrostatics=False)\n', (8132, 8204), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((8724, 8749), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""O"""'], {}), "('O')\n", (8744, 8749), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((8760, 8796), 'openff.toolkit.topology.Topology.from_molecules', 'Topology.from_molecules', (['(2 * [water])'], {}), '(2 * [water])\n', (8783, 8796), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((8994, 9031), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['tip3p', 'tmp'], {}), '(tip3p, tmp)\n', (9019, 9031), False, 'from openff.interchange.components.interchange import Interchange\n'), ((9140, 9246), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['openff_sys'], {'hard_cutoff': '(True)', 'electrostatics': '(False)', 'combine_nonbonded_forces': '(True)'}), '(openff_sys, hard_cutoff=True, electrostatics=False,\n combine_nonbonded_forces=True)\n', (9159, 9246), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((9812, 9844), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['openff_sys'], {}), '(openff_sys)\n', (9832, 9844), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((9864, 9895), 'openff.interchange.drivers.lammps.get_lammps_energies', 'get_lammps_energies', (['openff_sys'], {}), '(openff_sys)\n', (9883, 9895), False, 'from openff.interchange.drivers.lammps import get_lammps_energies\n'), ((10192, 10223), 'foyer.Forcefield', 'foyer.Forcefield', ([], {'name': '"""oplsaa"""'}), "(name='oplsaa')\n", (10208, 10223), False, 'import foyer\n'), ((10239, 10266), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""CCO"""'], {}), "('CCO')\n", (10259, 10266), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((10512, 10539), 'openff.interchange.components.mbuild.offmol_to_compound', 'offmol_to_compound', (['ethanol'], {}), '(ethanol)\n', (10530, 10539), False, 'from openff.interchange.components.mbuild import offmol_to_compound\n'), ((10562, 10587), 'mbuild.Box', 'mb.Box', ([], {'lengths': '[4, 4, 4]'}), '(lengths=[4, 4, 4])\n', (10568, 10587), True, 'import mbuild as mb\n'), ((10602, 10633), 'foyer.Forcefield', 'foyer.Forcefield', ([], {'name': '"""oplsaa"""'}), "(name='oplsaa')\n", (10618, 10633), False, 'import foyer\n'), ((11231, 11262), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""ClC#CCl"""'], {}), "('ClC#CCl')\n", (11251, 11262), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((11344, 11377), 'openff.toolkit.typing.engines.smirnoff.ForceField', 'ForceField', (['"""openff-1.0.0.offxml"""'], {}), "('openff-1.0.0.offxml')\n", (11354, 11377), False, 'from openff.toolkit.typing.engines.smirnoff import ForceField\n'), ((11699, 11724), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['out'], {}), '(out)\n', (11719, 11724), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((12494, 12533), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['ion_ff', 'ions'], {}), '(ion_ff, ions)\n', (12519, 12533), False, 'from openff.interchange.components.interchange import Interchange\n'), ((12629, 12655), 'numpy.linspace', 'np.linspace', (['(0.75)', '(0.95)', '(5)'], {}), '(0.75, 0.95, 5)\n', (12640, 12655), True, 'import numpy as np\n'), ((15503, 15528), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['smi'], {}), '(smi)\n', (15523, 15528), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((15620, 15705), 'openff.toolkit.typing.engines.smirnoff.ForceField', 'ForceField', (['"""test_forcefields/test_forcefield.offxml"""', 'xml_ff_bo_all_heavy_bonds'], {}), "('test_forcefields/test_forcefield.offxml', xml_ff_bo_all_heavy_bonds\n )\n", (15630, 15705), False, 'from openff.toolkit.typing.engines.smirnoff import ForceField\n'), ((15735, 15777), 'openff.interchange.components.interchange.Interchange.from_smirnoff', 'Interchange.from_smirnoff', (['forcefield', 'top'], {}), '(forcefield, top)\n', (15760, 15777), False, 'from openff.interchange.components.interchange import Interchange\n'), ((1582, 1636), 'pytest.raises', 'pytest.raises', (['EnergyError'], {'match': '"""_FLAG[\\\\s\\\\S]*KEY_"""'}), "(EnergyError, match='_FLAG[\\\\s\\\\S]*KEY_')\n", (1595, 1636), False, 'import pytest\n'), ((2216, 2249), 'openff.toolkit.typing.engines.smirnoff.ForceField', 'ForceField', (['"""openff-1.0.0.offxml"""'], {}), "('openff-1.0.0.offxml')\n", (2226, 2249), False, 'from openff.toolkit.typing.engines.smirnoff import ForceField\n'), ((2278, 2325), 'openff.toolkit.typing.engines.smirnoff.ForceField', 'ForceField', (['"""openff_unconstrained-1.0.0.offxml"""'], {}), "('openff_unconstrained-1.0.0.offxml')\n", (2288, 2325), False, 'from openff.toolkit.typing.engines.smirnoff import ForceField\n'), ((3773, 3863), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['off_sys'], {'round_positions': '(8)', 'hard_cutoff': '(True)', 'electrostatics': '(True)'}), '(off_sys, round_positions=8, hard_cutoff=True,\n electrostatics=True)\n', (3792, 3863), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((3942, 3970), 'openff.interchange.drivers.lammps.get_lammps_energies', 'get_lammps_energies', (['off_sys'], {}), '(off_sys)\n', (3961, 3970), False, 'from openff.interchange.drivers.lammps import get_lammps_energies\n'), ((4355, 4393), 'openff.interchange.utils.get_test_file_path', 'get_test_file_path', (['"""packed-argon.pdb"""'], {}), "('packed-argon.pdb')\n", (4373, 4393), False, 'from openff.interchange.utils import get_test_file_path\n'), ((4498, 4532), 'openff.interchange.utils.get_test_file_path', 'get_test_file_path', (['"""argon.offxml"""'], {}), "('argon.offxml')\n", (4516, 4532), False, 'from openff.interchange.utils import get_test_file_path\n'), ((6273, 6298), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['smi'], {}), '(smi)\n', (6293, 6298), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((8676, 8710), 'openff.interchange.utils.get_test_file_path', 'get_test_file_path', (['"""tip3p.offxml"""'], {}), "('tip3p.offxml')\n", (8694, 8710), False, 'from openff.interchange.utils import get_test_file_path\n'), ((8902, 8939), 'openff.interchange.utils.get_test_file_path', 'get_test_file_path', (['"""water-dimer.pdb"""'], {}), "('water-dimer.pdb')\n", (8920, 8939), False, 'from openff.interchange.utils import get_test_file_path\n'), ((12225, 12258), 'openff.interchange.utils.get_test_file_path', 'get_test_file_path', (['"""ions.offxml"""'], {}), "('ions.offxml')\n", (12243, 12258), False, 'from openff.interchange.utils import get_test_file_path\n'), ((2622, 2650), 'mbuild.Box', 'mb.Box', ([], {'lengths': '[10, 10, 10]'}), '(lengths=[10, 10, 10])\n', (2628, 2650), True, 'import mbuild as mb\n'), ((10903, 10927), 'openff.interchange.drivers.gromacs._get_mdp_file', '_get_mdp_file', (['"""default"""'], {}), "('default')\n", (10916, 10927), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((12318, 12346), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""[#3]"""'], {}), "('[#3]')\n", (12338, 12346), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((12360, 12389), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['"""[#17]"""'], {}), "('[#17]')\n", (12380, 12389), False, 'from openff.toolkit.topology import Molecule, Topology\n'), ((12677, 12693), 'numpy.zeros', 'np.zeros', (['(2, 3)'], {}), '((2, 3))\n', (12685, 12693), True, 'import numpy as np\n'), ((15982, 16037), 'openff.interchange.drivers.get_openmm_energies', 'get_openmm_energies', (['out'], {'combine_nonbonded_forces': '(True)'}), '(out, combine_nonbonded_forces=True)\n', (16001, 16037), False, 'from openff.interchange.drivers import get_openmm_energies\n'), ((16100, 16240), 'openff.interchange.drivers.openmm._get_openmm_energies', '_get_openmm_energies', (['toolkit_system'], {'box_vectors': '([[4, 0, 0], [0, 4, 0], [0, 0, 4]] * openmm_unit.nanometer)', 'positions': 'mol.conformers[0]'}), '(toolkit_system, box_vectors=[[4, 0, 0], [0, 4, 0], [0,\n 0, 4]] * openmm_unit.nanometer, positions=mol.conformers[0])\n', (16120, 16240), False, 'from openff.interchange.drivers.openmm import _get_openmm_energies\n'), ((16472, 16549), 'pytest.xfail', 'pytest.xfail', (['f"""Found energy difference of {toolkit_diff} kJ/mol vs. toolkit"""'], {}), "(f'Found energy difference of {toolkit_diff} kJ/mol vs. toolkit')\n", (16484, 16549), False, 'import pytest\n'), ((16606, 16682), 'pytest.fail', 'pytest.fail', (['f"""Found energy difference of {toolkit_diff} kJ/mol vs. toolkit"""'], {}), "(f'Found energy difference of {toolkit_diff} kJ/mol vs. toolkit')\n", (16617, 16682), False, 'import pytest\n'), ((16709, 16734), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['out'], {}), '(out)\n', (16729, 16734), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((16919, 17034), 'pytest.xfail', 'pytest.xfail', (['f"""Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports"""'], {}), "(\n f'Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports'\n )\n", (16931, 17034), False, 'import pytest\n'), ((17081, 17195), 'pytest.fail', 'pytest.fail', (['f"""Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports"""'], {}), "(\n f'Found {key} energy difference of {energy_diff} kJ/mol between GROMACS and OpenMM exports'\n )\n", (17092, 17195), False, 'import pytest\n'), ((7863, 7920), 'openff.interchange.testing.utils._get_force', '_get_force', (['sys_from_toolkit', 'openmm.PeriodicTorsionForce'], {}), '(sys_from_toolkit, openmm.PeriodicTorsionForce)\n', (7873, 7920), False, 'from openff.interchange.testing.utils import _compare_torsion_forces, _get_force\n'), ((12858, 12895), 'openff.interchange.drivers.gromacs.get_gromacs_energies', 'get_gromacs_energies', (['out'], {'mdp': '"""auto"""'}), "(out, mdp='auto')\n", (12878, 12895), False, 'from openff.interchange.drivers.gromacs import _get_mdp_file, _run_gmx_energy, get_gromacs_energies\n'), ((13115, 13130), 'numpy.asarray', 'np.asarray', (['lmp'], {}), '(lmp)\n', (13125, 13130), True, 'import numpy as np\n'), ((13133, 13148), 'numpy.asarray', 'np.asarray', (['gmx'], {}), '(gmx)\n', (13143, 13148), True, 'import numpy as np\n'), ((12958, 12982), 'openff.interchange.drivers.lammps.get_lammps_energies', 'get_lammps_energies', (['out'], {}), '(out)\n', (12977, 12982), False, 'from openff.interchange.drivers.lammps import get_lammps_energies\n')]
#T# the following code shows how to draw angle markings with arc marks #T# to draw arc marks, the pyplot module of the matplotlib package is used import matplotlib.pyplot as plt #T# the patches module of the matplotlib package is used to draw shapes import matplotlib.patches as mpatches #T# the numpy package is used to facilitate drawing arcs in polar coordinates import numpy as np #T# create the figure and axes fig1, ax1 = plt.subplots(1, 1) #T# set the projection of the axes to polar projection ax1 = plt.subplot(1, 1, 1, projection = 'polar') #T# set the aspect of the axes ax1.set_aspect('equal') #T# hide the spines and ticks ax1.spines['polar'].set_visible(False) ax1.xaxis.set_visible(False) ax1.yaxis.set_visible(False) #T# create the variables that define the plot p0 = (0, 0) a0 = 0 a1 = np.pi/8 a2 = 2*a1 a3 = a2 + np.pi/2 + .15 a4 = np.pi + .5 #T# plot the figure list_patches1 = [] ray1 = mpatches.FancyArrowPatch(p0, (a0, 1), arrowstyle = '->', mutation_scale = 12) list_patches1.append(ray1) ray2 = mpatches.FancyArrowPatch(p0, (a1, 1), arrowstyle = '->', mutation_scale = 12) list_patches1.append(ray2) ray3 = mpatches.FancyArrowPatch(p0, (a2, 1), arrowstyle = '->', mutation_scale = 12) list_patches1.append(ray3) ray4 = mpatches.FancyArrowPatch(p0, (a3, 1), arrowstyle = '->', mutation_scale = 12) list_patches1.append(ray4) ray5 = mpatches.FancyArrowPatch(p0, (a4, 1), arrowstyle = '->', mutation_scale = 12) list_patches1.append(ray5) plt.scatter(p0[0], p0[1], s = 6, color = 'k') for it1 in list_patches1: ax1.add_patch(it1) plt.polar(np.linspace(a0, a4, 30), 0.200*np.ones((30)), 'k', linewidth = 1) plt.polar(np.linspace(a0, a2, 30), 0.215*np.ones((30)), 'k', linewidth = 1) plt.polar(np.linspace(a3, a4, 30), 0.215*np.ones((30)), 'k', linewidth = 1) plt.polar(np.linspace(a3, a4, 30), 0.230*np.ones((30)), 'k', linewidth = 1) plt.polar([(a0 + a1)/2, (a0 + a1)/2], [.16, .26], 'k', linewidth = 1) plt.polar([(a1 + a2)/2, (a1 + a2)/2], [.16, .26], 'k', linewidth = 1) #T# show the results plt.show()
[ "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.scatter", "matplotlib.patches.FancyArrowPatch", "numpy.ones", "matplotlib.pyplot.polar", "numpy.linspace", "matplotlib.pyplot.subplots" ]
[((432, 450), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (444, 450), True, 'import matplotlib.pyplot as plt\n'), ((513, 553), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(1)', '(1)'], {'projection': '"""polar"""'}), "(1, 1, 1, projection='polar')\n", (524, 553), True, 'import matplotlib.pyplot as plt\n'), ((916, 989), 'matplotlib.patches.FancyArrowPatch', 'mpatches.FancyArrowPatch', (['p0', '(a0, 1)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(12)'}), "(p0, (a0, 1), arrowstyle='->', mutation_scale=12)\n", (940, 989), True, 'import matplotlib.patches as mpatches\n'), ((1028, 1101), 'matplotlib.patches.FancyArrowPatch', 'mpatches.FancyArrowPatch', (['p0', '(a1, 1)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(12)'}), "(p0, (a1, 1), arrowstyle='->', mutation_scale=12)\n", (1052, 1101), True, 'import matplotlib.patches as mpatches\n'), ((1140, 1213), 'matplotlib.patches.FancyArrowPatch', 'mpatches.FancyArrowPatch', (['p0', '(a2, 1)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(12)'}), "(p0, (a2, 1), arrowstyle='->', mutation_scale=12)\n", (1164, 1213), True, 'import matplotlib.patches as mpatches\n'), ((1252, 1325), 'matplotlib.patches.FancyArrowPatch', 'mpatches.FancyArrowPatch', (['p0', '(a3, 1)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(12)'}), "(p0, (a3, 1), arrowstyle='->', mutation_scale=12)\n", (1276, 1325), True, 'import matplotlib.patches as mpatches\n'), ((1364, 1437), 'matplotlib.patches.FancyArrowPatch', 'mpatches.FancyArrowPatch', (['p0', '(a4, 1)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(12)'}), "(p0, (a4, 1), arrowstyle='->', mutation_scale=12)\n", (1388, 1437), True, 'import matplotlib.patches as mpatches\n'), ((1469, 1510), 'matplotlib.pyplot.scatter', 'plt.scatter', (['p0[0]', 'p0[1]'], {'s': '(6)', 'color': '"""k"""'}), "(p0[0], p0[1], s=6, color='k')\n", (1480, 1510), True, 'import matplotlib.pyplot as plt\n'), ((1869, 1942), 'matplotlib.pyplot.polar', 'plt.polar', (['[(a0 + a1) / 2, (a0 + a1) / 2]', '[0.16, 0.26]', '"""k"""'], {'linewidth': '(1)'}), "([(a0 + a1) / 2, (a0 + a1) / 2], [0.16, 0.26], 'k', linewidth=1)\n", (1878, 1942), True, 'import matplotlib.pyplot as plt\n'), ((1939, 2012), 'matplotlib.pyplot.polar', 'plt.polar', (['[(a1 + a2) / 2, (a1 + a2) / 2]', '[0.16, 0.26]', '"""k"""'], {'linewidth': '(1)'}), "([(a1 + a2) / 2, (a1 + a2) / 2], [0.16, 0.26], 'k', linewidth=1)\n", (1948, 2012), True, 'import matplotlib.pyplot as plt\n'), ((2031, 2041), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2039, 2041), True, 'import matplotlib.pyplot as plt\n'), ((1575, 1598), 'numpy.linspace', 'np.linspace', (['a0', 'a4', '(30)'], {}), '(a0, a4, 30)\n', (1586, 1598), True, 'import numpy as np\n'), ((1651, 1674), 'numpy.linspace', 'np.linspace', (['a0', 'a2', '(30)'], {}), '(a0, a2, 30)\n', (1662, 1674), True, 'import numpy as np\n'), ((1727, 1750), 'numpy.linspace', 'np.linspace', (['a3', 'a4', '(30)'], {}), '(a3, a4, 30)\n', (1738, 1750), True, 'import numpy as np\n'), ((1803, 1826), 'numpy.linspace', 'np.linspace', (['a3', 'a4', '(30)'], {}), '(a3, a4, 30)\n', (1814, 1826), True, 'import numpy as np\n'), ((1606, 1617), 'numpy.ones', 'np.ones', (['(30)'], {}), '(30)\n', (1613, 1617), True, 'import numpy as np\n'), ((1682, 1693), 'numpy.ones', 'np.ones', (['(30)'], {}), '(30)\n', (1689, 1693), True, 'import numpy as np\n'), ((1758, 1769), 'numpy.ones', 'np.ones', (['(30)'], {}), '(30)\n', (1765, 1769), True, 'import numpy as np\n'), ((1834, 1845), 'numpy.ones', 'np.ones', (['(30)'], {}), '(30)\n', (1841, 1845), True, 'import numpy as np\n')]
#!/usr/bin/env python """ config_mixed.py: the configuration for mixed state learning task """ import numpy as np from tools.utils import get_zero_state # Learning Scripts # Regularization Parameters lamb = np.float(10) s = np.exp(-1 / (2 * lamb)) - 1 cst1 = s ** 2 / 4 + s + 1 cst2 = s ** 2 / 4 + s / 2 cst3 = s ** 2 / 4 # Learning Scripts initial_eta = 1e-1 epochs = 10 decay = False eta = initial_eta step_size = 1 prob_gen_lr = eta theta_lr = eta psi_lr = eta phi_lr = eta label = 'mixed_state' fidelities = list() losses = list() # System setting// system_size = 2 num_to_mix = 2 zero_state = get_zero_state(system_size) # file settings figure_path = './figure' model_gen_path = './saved_model/{}qubit_model-gen(mixed).mdl'.format(system_size) model_dis_path = './saved_model/{}qubit_model-dis(mixed).mdl'.format(system_size)
[ "numpy.exp", "numpy.float", "tools.utils.get_zero_state" ]
[((216, 228), 'numpy.float', 'np.float', (['(10)'], {}), '(10)\n', (224, 228), True, 'import numpy as np\n'), ((615, 642), 'tools.utils.get_zero_state', 'get_zero_state', (['system_size'], {}), '(system_size)\n', (629, 642), False, 'from tools.utils import get_zero_state\n'), ((233, 256), 'numpy.exp', 'np.exp', (['(-1 / (2 * lamb))'], {}), '(-1 / (2 * lamb))\n', (239, 256), True, 'import numpy as np\n')]
import numpy as np import unittest from utils import * class FermionicOperator: """ A base class for any type of operator. You shouldn't be instantiating this directly. Attributes: type : str The type of operator: 'creation' or 'annihilation'. spin : str Spin of the particle the operator acts on: 'up' or 'down'. site : int < num_sites The index of the site this operator is acting on. We'll calculate which exact qubit it acts on based on site, spin, and num_sites. For systems with spin, we assign two qubits to each site: on site j, the 'up' spin acts on qubit j, and the 'down' spin acts on qubit num_sites + j num_sites : int The number of sites in a system. dim : int The number of qubits used. JW : (2**dim, 2**dim) matrix Jordan-Wigner transformation of operator. The lowest qubit is on the *LEFT* ie |10> = [0, 0, 1, 0]. JW_str : str String representation of Jordan-Wigner encoding. Methods: TODO: """ def __init__(self, _type: str, spin: str, site: int, num_sites: int): """ Parameters: _type : str One of ['creation', 'annihilation']. spin : str One of ['up', 'down']. site : int num_sites : int """ types = ['creation', 'annihilation'] if _type not in types: raise ValueError("_type must be either 'creation' or \ 'annihilation'!") spins = ['up', 'down'] if spin not in spins: raise ValueError("spin must be either 'up' or 'down'!") self.type = _type self.spin = spin self.site = site self.num_sites = num_sites if self.spin == 'up': self.qubit = self.site elif self.spin == 'down': self.qubit = self.num_sites + self.site else: raise ValueError("spin value must be 'up' or 'down'!") self.dim = 2 * num_sites self.JW, self.JW_str = self._gen_JW_mapping() def _gen_JW_mapping(self): """ Generate a Jordan-Wigner representation of a fermionic operator. We let |0> represent no electron in a spin-orbital, and we let |1> represent an electron existing in a spin-orbital. This allows us to define the creation operator as (X-iY)/2 and the annihilation operator as (X+iY)/2. The main problem with this is that the creation and annihilation operators don't anti-commute. To fix this, we prepend the operator with Pauli-Z tensors. Because the Pauli operators anti-commute, this preserves our desired anti-commutation relation. """ res = 1 str_repr = '' # Notice order of tensor product: gate on 0th qubit is "leftmost" for i in range(self.dim): if i < self.qubit: res = NKron(res, Z) str_repr += 'Z' elif i == self.qubit and self.type == 'creation': res = NKron(res, (X - 1j * Y) / 2) str_repr += '-' elif i == self.qubit and self.type == 'annihilation': res = NKron(res, (X + 1j * Y) / 2) str_repr += '+' elif i > self.qubit: res = NKron(res, I) str_repr += 'I' else: raise ValueError("Something's wrong with the JW encoding!") return res, str_repr class CreationOperator(FermionicOperator): """Shortcut for a creation operator.""" def __init__(self, spin: str, site: int, num_sites: int): super(CreationOperator, self).__init__('creation', spin, site, num_sites) class AnnihilationOperator(FermionicOperator): """Shortcut for an annihilation operator.""" def __init__(self, spin: str, site: int, num_sites: int): super(AnnihilationOperator, self).__init__('annihilation', spin, site, num_sites) # TESTS tol = 0.005 class TestCreationOperator(unittest.TestCase): def test_init(self): c_0 = CreationOperator('up', 0, 4) self.assertEqual(c_0.type, 'creation') c_1 = CreationOperator('up', 1, 3) self.assertEqual(c_1.type, 'creation') c_2 = CreationOperator('down', 2, 4) self.assertEqual(c_2.type, 'creation') c_4 = CreationOperator('up', 4, 5) self.assertEqual(c_4.type, 'creation') def test_attributes(self): c_2 = CreationOperator('down', 2, 4) self.assertEqual(c_2.spin, 'down') self.assertEqual(c_2.site, 2) self.assertEqual(c_2.num_sites, 4) self.assertEqual(c_2.dim, 8) self.assertEqual(c_2.JW.shape, (256, 256)) self.assertEqual(c_2.JW_str, 'ZZZZZZ-I') class TestAnnihilationOperator(unittest.TestCase): def test_init(self): a_1 = AnnihilationOperator('down', 3, 6) self.assertEqual(a_1.type, 'annihilation') class TestAntiCommutationRelations(unittest.TestCase): def test_same_site_same_spin_one_dim(self): c_0 = CreationOperator('up', 0, 1) a_0 = AnnihilationOperator('up', 0, 1) anti_comm = NDot(c_0.JW, a_0.JW) + NDot(a_0.JW, c_0.JW) i_4 = np.eye(2**c_0.dim) self.assertTrue(array_eq(anti_comm, i_4, tol)) def test_same_site_diff_spin_one_dim(self): c_0 = CreationOperator('up', 0, 1) a_0 = AnnihilationOperator('down', 0, 1) anti_comm = NDot(c_0.JW, a_0.JW) + NDot(a_0.JW, c_0.JW) z_4 = np.zeros((2**c_0.dim, 2**c_0.dim)) self.assertTrue(array_eq(anti_comm, z_4, tol)) def test_diff_site_same_spin_two_dim(self): c_0 = CreationOperator('down', 0, 2) a_1 = AnnihilationOperator('down', 1, 2) anti_comm = NDot(c_0.JW, a_1.JW) + NDot(a_1.JW, c_0.JW) z_16 = np.zeros((2**c_0.dim, 2**c_0.dim)) self.assertTrue(array_eq(anti_comm, z_16, tol)) def test_diff_site_diff_spin_two_dim(self): c_0 = CreationOperator('up', 0, 2) a_1 = AnnihilationOperator('down', 1, 2) anti_comm = NDot(c_0.JW, a_1.JW) + NDot(a_1.JW, c_0.JW) z_16 = np.zeros((2**c_0.dim, 2**c_0.dim)) self.assertTrue(array_eq(anti_comm, z_16, tol)) # TODO: more complex tests for anti-commutator def test_creation_anti(self): c_0 = CreationOperator('up', 0, 3) c_2 = CreationOperator('down', 2, 3) anti_comm = NDot(c_0.JW, c_2.JW) + NDot(c_2.JW, c_0.JW) z_64 = np.zeros((2**c_0.dim, 2**c_0.dim)) self.assertTrue(array_eq(anti_comm, z_64, tol)) def test_annihilation_anti(self): a_0 = AnnihilationOperator('down', 0, 2) a_1 = AnnihilationOperator('down', 1, 2) anti_comm = NDot(a_0.JW, a_1.JW) + NDot(a_1.JW, a_0.JW) z_16 = np.zeros((2**a_0.dim, 2**a_0.dim)) self.assertTrue(array_eq(anti_comm, z_16, tol)) class TestOnStates(unittest.TestCase): def test_creation_ground(self): c_0 = CreationOperator('up', 0, 1) exc = NDot(c_0.JW, NKron(ket_0, ket_0)) # We apply a CreationOperator on leftmost qubit self.assertTrue(array_eq(exc, NKron(ket_1, ket_0), tol)) c_2 = CreationOperator('up', 2, 3) exc = NDot(c_2.JW, NKron(ket_0, ket_0, ket_0, ket_0, ket_0, ket_0)) self.assertTrue(array_eq(exc, NKron(ket_0, ket_0, ket_1, ket_0, ket_0, ket_0), tol)) c_1 = CreationOperator('down', 1, 2) exc = NDot(c_1.JW, NKron(ket_0, ket_0, ket_0, ket_0)) self.assertTrue(array_eq(exc, NKron(ket_0, ket_0, ket_0, ket_1), tol)) def test_annihilation_ground(self): a_0 = AnnihilationOperator('down', 0, 1) exc = NDot(a_0.JW, NKron(ket_0, ket_0)) self.assertTrue(array_eq(exc, NKron(ket_0, [[0], [0]]), tol)) a_1 = AnnihilationOperator('up', 2, 3) exc = NDot(a_1.JW, NKron(ket_0, ket_0, ket_0, ket_0, ket_0, ket_0)) self.assertTrue(array_eq(exc, NKron(ket_0, ket_0, np.array([[0], [0]]), ket_0, ket_0, ket_0), tol)) # TODO: test on excited states # TODO: test on more complex states if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.eye", "numpy.zeros", "numpy.array" ]
[((8537, 8552), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8550, 8552), False, 'import unittest\n'), ((5537, 5557), 'numpy.eye', 'np.eye', (['(2 ** c_0.dim)'], {}), '(2 ** c_0.dim)\n', (5543, 5557), True, 'import numpy as np\n'), ((5834, 5872), 'numpy.zeros', 'np.zeros', (['(2 ** c_0.dim, 2 ** c_0.dim)'], {}), '((2 ** c_0.dim, 2 ** c_0.dim))\n', (5842, 5872), True, 'import numpy as np\n'), ((6146, 6184), 'numpy.zeros', 'np.zeros', (['(2 ** c_0.dim, 2 ** c_0.dim)'], {}), '((2 ** c_0.dim, 2 ** c_0.dim))\n', (6154, 6184), True, 'import numpy as np\n'), ((6465, 6503), 'numpy.zeros', 'np.zeros', (['(2 ** c_0.dim, 2 ** c_0.dim)'], {}), '((2 ** c_0.dim, 2 ** c_0.dim))\n', (6473, 6503), True, 'import numpy as np\n'), ((6811, 6849), 'numpy.zeros', 'np.zeros', (['(2 ** c_0.dim, 2 ** c_0.dim)'], {}), '((2 ** c_0.dim, 2 ** c_0.dim))\n', (6819, 6849), True, 'import numpy as np\n'), ((7118, 7156), 'numpy.zeros', 'np.zeros', (['(2 ** a_0.dim, 2 ** a_0.dim)'], {}), '((2 ** a_0.dim, 2 ** a_0.dim))\n', (7126, 7156), True, 'import numpy as np\n'), ((8332, 8352), 'numpy.array', 'np.array', (['[[0], [0]]'], {}), '([[0], [0]])\n', (8340, 8352), True, 'import numpy as np\n')]
import logging from numba import njit import numpy as np from scipy.interpolate import interp1d from strax import exporter, deterministic_hash from ..load_resource import load_config export, __all__ = exporter() logging.basicConfig(handlers=[logging.StreamHandler()]) log = logging.getLogger('wfsim.core') log.setLevel('WARNING') __all__ += ['_cached_pmt_current_templates', '_cached_uniform_to_pe_arr'] _cached_pmt_current_templates = {} _cached_uniform_to_pe_arr = {} @export class Pulse(object): """Pulse building class""" def __init__(self, config): self.config = config self.config.update(self.config.get(self.__class__.__name__, {})) self.resource = load_config(config) self.init_pmt_current_templates() self.init_spe_scaling_factor_distributions() self.config['turned_off_pmts'] = np.arange(len(config['gains']))[np.array(config['gains']) == 0] self.current_max = np.max(np.array(self._pmt_current_templates), axis=1) self.current_2_adc = self.config['pmt_circuit_load_resistor'] \ * self.config['external_amplification'] \ / (self.config['digitizer_voltage_range'] / 2 ** (self.config['digitizer_bits'])) self.clear_pulse_cache() def __call__(self, *args): """ PMTs' response to incident photons Use _photon_timings, _photon_channels to build pulses """ if ('_photon_timings' not in self.__dict__) or \ ('_photon_channels' not in self.__dict__): raise NotImplementedError # The pulse cache should be immediately transferred after call this function self.clear_pulse_cache() # Correct for PMT Transition Time Spread (skip for pmt after-pulses) # note that PMT datasheet provides FWHM TTS, so sigma = TTS/(2*sqrt(2*log(2)))=TTS/2.35482 if '_photon_gains' not in self.__dict__: self._photon_timings += np.random.normal(self.config['pmt_transit_time_mean'], self.config['pmt_transit_time_spread'] / 2.35482, len(self._photon_timings)).astype(np.int64) dt = self.config.get('sample_duration', 10) # Getting dt from the lib just once self._n_photon = self._n_photon_bottom = 0 # For truth output self._n_pe = self._n_pe_bottom = 0 self._n_photon_trigger = self._n_photon_trigger_bottom = 0 self._n_pe_trigger = self._n_pe_trigger_bottom = 0 self._raw_area = self._raw_area_bottom = 0 self._raw_area_trigger = self._raw_area_trigger_bottom = 0 counts_start = 0 # Secondary loop index for assigning channel for channel, counts in zip(*np.unique(self._photon_channels, return_counts=True)): # Use 'counts' amount of photon for this channel _channel_photon_timings = self._photon_timings[counts_start:counts_start+counts] counts_start += counts if channel in self.config['turned_off_pmts']: continue # If gain of each photon is not specifically assigned # Sample from spe scaling factor distribution and to individual gain # In contrast to pmt afterpulse that should have gain determined before this step if '_photon_gains' not in self.__dict__: _channel_photon_gains = self.config['gains'][channel] \ * self.uniform_to_pe_arr(np.random.random(len(_channel_photon_timings)), channel) # Add some double photoelectron emission by adding another sampled gain n_double_pe = np.random.binomial(len(_channel_photon_timings), p=self.config['p_double_pe_emision']) _channel_photon_gains[:n_double_pe] += self.config['gains'][channel] \ * self.uniform_to_pe_arr(np.random.random(n_double_pe), channel) else: n_double_pe = 0 _channel_photon_gains = np.array(self._photon_gains[self._photon_channels == channel]) # += truth per channel to internal truth fields self.add_truth( _channel_photon_timings, _channel_photon_gains, dt, channel, n_double_pe,) # Build a simulated waveform, length depends on min and max of photon timings min_timing, max_timing = np.min( _channel_photon_timings), np.max(_channel_photon_timings) pulse_left = (int(min_timing // dt) - int(self.config['samples_to_store_before']) - self.config.get('samples_before_pulse_center', 2)) pulse_right = (int(max_timing // dt) + int(self.config['samples_to_store_after']) + self.config.get('samples_after_pulse_center', 20)) pulse_current = np.zeros(pulse_right - pulse_left + 1) Pulse.add_current(_channel_photon_timings.astype(np.int64), _channel_photon_gains, pulse_left, dt, self._pmt_current_templates, pulse_current) # For single event, data of pulse level is small enough to store in dataframe self._pulses.append(dict( photons = len(_channel_photon_timings), channel = channel, left = pulse_left, right = pulse_right, duration = pulse_right - pulse_left + 1, current = pulse_current,)) def init_pmt_current_templates(self): """ Create spe templates, for 10ns sample duration and 1ns rounding we have: _pmt_current_templates[i] : photon timing fall between [10*m+i, 10*m+i+1) (i, m are integers) """ h = deterministic_hash(self.config) if h in _cached_pmt_current_templates: self._pmt_current_templates = _cached_pmt_current_templates[h] return # Interpolate on cdf ensures that each spe pulse would sum up to 1 pe*sample duration^-1 pe_pulse_function = interp1d( self.config.get('pe_pulse_ts'), np.cumsum(self.config.get('pe_pulse_ys')), bounds_error=False, fill_value=(0, 1)) # Samples are always multiples of sample_duration sample_duration = self.config.get('sample_duration', 10) samples_before = self.config.get('samples_before_pulse_center', 2) samples_after = self.config.get('samples_after_pulse_center', 20) pmt_pulse_time_rounding = self.config.get('pmt_pulse_time_rounding', 1.0) # Let's fix this, so everything can be turned into int assert pmt_pulse_time_rounding == 1 samples = np.linspace(-samples_before * sample_duration, + samples_after * sample_duration, 1 + samples_before + samples_after) self._template_length = np.int(len(samples) - 1) templates = [] for r in np.arange(0, sample_duration, pmt_pulse_time_rounding): pmt_current = np.diff(pe_pulse_function(samples - r)) / sample_duration # pe / 10 ns # Normalize here to counter tiny rounding error from interpolation pmt_current *= (1 / sample_duration) / np.sum(pmt_current) # pe / 10 ns templates.append(pmt_current) self._pmt_current_templates = np.array(templates) _cached_pmt_current_templates[h] = self._pmt_current_templates log.debug('Spe waveform templates created with %s ns resolution, cached with key %s' % (pmt_pulse_time_rounding, h)) def init_spe_scaling_factor_distributions(self): h = deterministic_hash(self.config) if h in _cached_uniform_to_pe_arr: self.__uniform_to_pe_arr = _cached_uniform_to_pe_arr[h] return # Extract the spe pdf from a csv file into a pandas dataframe spe_shapes = self.resource.photon_area_distribution # Create a converter array from uniform random numbers to SPE gains (one interpolator per channel) # Scale the distributions so that they have an SPE mean of 1 and then calculate the cdf uniform_to_pe_arr = [] for ch in spe_shapes.columns[1:]: # skip the first element which is the 'charge' header if spe_shapes[ch].sum() > 0: # mean_spe = (spe_shapes['charge'].values * spe_shapes[ch]).sum() / spe_shapes[ch].sum() scaled_bins = spe_shapes['charge'].values # / mean_spe cdf = np.cumsum(spe_shapes[ch]) / np.sum(spe_shapes[ch]) else: # if sum is 0, just make some dummy axes to pass to interpolator cdf = np.linspace(0, 1, 10) scaled_bins = np.zeros_like(cdf) grid_cdf = np.linspace(0, 1, 2001) grid_scale = interp1d(cdf, scaled_bins, kind='next', bounds_error=False, fill_value=(scaled_bins[0], scaled_bins[-1]))(grid_cdf) uniform_to_pe_arr.append(grid_scale) if len(uniform_to_pe_arr): self.__uniform_to_pe_arr = np.stack(uniform_to_pe_arr) _cached_uniform_to_pe_arr[h] = self.__uniform_to_pe_arr log.debug('Spe scaling factors created, cached with key %s' % h) def uniform_to_pe_arr(self, p, channel=0): indices = (p * 2000).astype(np.int64) + 1 return self.__uniform_to_pe_arr[channel, indices] def add_truth(self, photon_timings, photon_gains, dt, channel, n_double_pe, ): """Add required information to the fields used for the truth information""" if channel in self.config['turned_off_pmts']: return if str(channel) in self.config.get('special_thresholds', {}): threshold = self.config['special_thresholds'][str(channel)] - 0.5 else: threshold = self.config['zle_threshold'] - 0.5 # Figure out if we were above threshold # - Current max is the highest value in the SPE pulse model given a # remainder [0-9] ns (offset from 10 ns sample time). # The SPE pulse model sums up to 0.1 (pe/ns), and the peak is ~0.03 (pe/ns) # - Multiply this by the sampled gain of each photon, we get (electron/ns) # - The current_2_adc take into account n_electron -> current -> voltage # -> amplification -> digitization, converting the electron/ns to adc value. remainder = (photon_timings % dt).astype(int) max_amplitude_adc = photon_gains * self.current_max[remainder] * self.current_2_adc above_threshold = max_amplitude_adc > threshold trigger_photon = np.sum(above_threshold) trigger_dpe = np.sum(above_threshold[:n_double_pe]) raw_area = np.sum(photon_gains) / self.config['gains'][channel] trigger_raw_area = np.sum(photon_gains[above_threshold]) / self.config['gains'][channel] self._n_photon += len(photon_timings) self._n_pe += len(photon_timings) + n_double_pe self._n_photon_trigger += trigger_photon self._n_pe_trigger += trigger_photon + trigger_dpe self._raw_area += raw_area self._raw_area_trigger += trigger_raw_area if channel in self.config['channels_bottom']: self._n_photon_bottom += len(photon_timings) self._n_pe_bottom += len(photon_timings) + n_double_pe self._n_photon_trigger_bottom += trigger_photon self._n_pe_trigger_bottom += trigger_photon + trigger_dpe self._raw_area_bottom += raw_area self._raw_area_trigger_bottom += trigger_raw_area def clear_pulse_cache(self): self._pulses = [] @staticmethod @njit def add_current(photon_timings, photon_gains, pulse_left, dt, pmt_current_templates, pulse_current): # """ # Simulate single channel waveform given the photon timings # photon_timing - dim-1 integer array of photon timings in unit of ns # photon_gain - dim-1 float array of ph. 2 el. gain individual photons # pulse_left - left of the pulse in unit of 10 ns # dt - mostly it is 10 ns # pmt_current_templates - list of spe templates of different reminders # pulse_current - waveform # """ if not len(photon_timings): return template_length = len(pmt_current_templates[0]) i_photons = np.argsort(photon_timings) # Convert photon_timings to int outside this function # photon_timings = photon_timings // 1 gain_total = 0 tmp_photon_timing = photon_timings[i_photons[0]] for i in i_photons: if photon_timings[i] > tmp_photon_timing: start = int(tmp_photon_timing // dt) - pulse_left reminder = int(tmp_photon_timing % dt) pulse_current[start:start + template_length] += \ pmt_current_templates[reminder] * gain_total gain_total = photon_gains[i] tmp_photon_timing = photon_timings[i] else: gain_total += photon_gains[i] start = int(tmp_photon_timing // dt) - pulse_left reminder = int(tmp_photon_timing % dt) pulse_current[start:start + template_length] += \ pmt_current_templates[reminder] * gain_total @staticmethod def singlet_triplet_delays(size, singlet_ratio, config, phase): """ Given the amount of the excimer, return time between excimer decay and their time of generation. size - amount of excimer self.phase - 'liquid' or 'gas' singlet_ratio - fraction of excimers that become singlets (NOT the ratio of singlets/triplets!) """ if phase == 'liquid': t1, t3 = (config['singlet_lifetime_liquid'], config['triplet_lifetime_liquid']) elif phase == 'gas': t1, t3 = (config['singlet_lifetime_gas'], config['triplet_lifetime_gas']) else: t1, t3 = 0, 0 delay = np.random.choice([t1, t3], size, replace=True, p=[singlet_ratio, 1 - singlet_ratio]) return (np.random.exponential(1, size) * delay).astype(np.int64)
[ "numpy.sum", "numpy.random.exponential", "numpy.argsort", "numpy.arange", "scipy.interpolate.interp1d", "strax.deterministic_hash", "numpy.unique", "numpy.zeros_like", "numpy.cumsum", "numpy.max", "numpy.linspace", "numpy.random.choice", "strax.exporter", "numpy.stack", "logging.StreamHa...
[((203, 213), 'strax.exporter', 'exporter', ([], {}), '()\n', (211, 213), False, 'from strax import exporter, deterministic_hash\n'), ((276, 307), 'logging.getLogger', 'logging.getLogger', (['"""wfsim.core"""'], {}), "('wfsim.core')\n", (293, 307), False, 'import logging\n'), ((6041, 6072), 'strax.deterministic_hash', 'deterministic_hash', (['self.config'], {}), '(self.config)\n', (6059, 6072), False, 'from strax import exporter, deterministic_hash\n'), ((6982, 7102), 'numpy.linspace', 'np.linspace', (['(-samples_before * sample_duration)', '(+samples_after * sample_duration)', '(1 + samples_before + samples_after)'], {}), '(-samples_before * sample_duration, +samples_after *\n sample_duration, 1 + samples_before + samples_after)\n', (6993, 7102), True, 'import numpy as np\n'), ((7258, 7312), 'numpy.arange', 'np.arange', (['(0)', 'sample_duration', 'pmt_pulse_time_rounding'], {}), '(0, sample_duration, pmt_pulse_time_rounding)\n', (7267, 7312), True, 'import numpy as np\n'), ((7656, 7675), 'numpy.array', 'np.array', (['templates'], {}), '(templates)\n', (7664, 7675), True, 'import numpy as np\n'), ((7957, 7988), 'strax.deterministic_hash', 'deterministic_hash', (['self.config'], {}), '(self.config)\n', (7975, 7988), False, 'from strax import exporter, deterministic_hash\n'), ((11130, 11153), 'numpy.sum', 'np.sum', (['above_threshold'], {}), '(above_threshold)\n', (11136, 11153), True, 'import numpy as np\n'), ((11176, 11213), 'numpy.sum', 'np.sum', (['above_threshold[:n_double_pe]'], {}), '(above_threshold[:n_double_pe])\n', (11182, 11213), True, 'import numpy as np\n'), ((13118, 13144), 'numpy.argsort', 'np.argsort', (['photon_timings'], {}), '(photon_timings)\n', (13128, 13144), True, 'import numpy as np\n'), ((14832, 14920), 'numpy.random.choice', 'np.random.choice', (['[t1, t3]', 'size'], {'replace': '(True)', 'p': '[singlet_ratio, 1 - singlet_ratio]'}), '([t1, t3], size, replace=True, p=[singlet_ratio, 1 -\n singlet_ratio])\n', (14848, 14920), True, 'import numpy as np\n'), ((244, 267), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (265, 267), False, 'import logging\n'), ((950, 987), 'numpy.array', 'np.array', (['self._pmt_current_templates'], {}), '(self._pmt_current_templates)\n', (958, 987), True, 'import numpy as np\n'), ((5024, 5062), 'numpy.zeros', 'np.zeros', (['(pulse_right - pulse_left + 1)'], {}), '(pulse_right - pulse_left + 1)\n', (5032, 5062), True, 'import numpy as np\n'), ((9089, 9112), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(2001)'], {}), '(0, 1, 2001)\n', (9100, 9112), True, 'import numpy as np\n'), ((9481, 9508), 'numpy.stack', 'np.stack', (['uniform_to_pe_arr'], {}), '(uniform_to_pe_arr)\n', (9489, 9508), True, 'import numpy as np\n'), ((11233, 11253), 'numpy.sum', 'np.sum', (['photon_gains'], {}), '(photon_gains)\n', (11239, 11253), True, 'import numpy as np\n'), ((11313, 11350), 'numpy.sum', 'np.sum', (['photon_gains[above_threshold]'], {}), '(photon_gains[above_threshold])\n', (11319, 11350), True, 'import numpy as np\n'), ((884, 909), 'numpy.array', 'np.array', (["config['gains']"], {}), "(config['gains'])\n", (892, 909), True, 'import numpy as np\n'), ((2758, 2810), 'numpy.unique', 'np.unique', (['self._photon_channels'], {'return_counts': '(True)'}), '(self._photon_channels, return_counts=True)\n', (2767, 2810), True, 'import numpy as np\n'), ((4075, 4137), 'numpy.array', 'np.array', (['self._photon_gains[self._photon_channels == channel]'], {}), '(self._photon_gains[self._photon_channels == channel])\n', (4083, 4137), True, 'import numpy as np\n'), ((4510, 4541), 'numpy.min', 'np.min', (['_channel_photon_timings'], {}), '(_channel_photon_timings)\n', (4516, 4541), True, 'import numpy as np\n'), ((4560, 4591), 'numpy.max', 'np.max', (['_channel_photon_timings'], {}), '(_channel_photon_timings)\n', (4566, 4591), True, 'import numpy as np\n'), ((7542, 7561), 'numpy.sum', 'np.sum', (['pmt_current'], {}), '(pmt_current)\n', (7548, 7561), True, 'import numpy as np\n'), ((8994, 9015), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10)'], {}), '(0, 1, 10)\n', (9005, 9015), True, 'import numpy as np\n'), ((9046, 9064), 'numpy.zeros_like', 'np.zeros_like', (['cdf'], {}), '(cdf)\n', (9059, 9064), True, 'import numpy as np\n'), ((9138, 9248), 'scipy.interpolate.interp1d', 'interp1d', (['cdf', 'scaled_bins'], {'kind': '"""next"""', 'bounds_error': '(False)', 'fill_value': '(scaled_bins[0], scaled_bins[-1])'}), "(cdf, scaled_bins, kind='next', bounds_error=False, fill_value=(\n scaled_bins[0], scaled_bins[-1]))\n", (9146, 9248), False, 'from scipy.interpolate import interp1d\n'), ((8822, 8847), 'numpy.cumsum', 'np.cumsum', (['spe_shapes[ch]'], {}), '(spe_shapes[ch])\n', (8831, 8847), True, 'import numpy as np\n'), ((8850, 8872), 'numpy.sum', 'np.sum', (['spe_shapes[ch]'], {}), '(spe_shapes[ch])\n', (8856, 8872), True, 'import numpy as np\n'), ((14966, 14996), 'numpy.random.exponential', 'np.random.exponential', (['(1)', 'size'], {}), '(1, size)\n', (14987, 14996), True, 'import numpy as np\n'), ((3944, 3973), 'numpy.random.random', 'np.random.random', (['n_double_pe'], {}), '(n_double_pe)\n', (3960, 3973), True, 'import numpy as np\n')]
# Note that ".mkv" file can be played using VLC under mac os # Please copy drive/707/Original Video/testX.MOV to datasets/test/ folder and run this # test1.MOV: qiye # test2.MOV: xiaohan # test3/4.MOV: shangxuan # configurations test_video_path = 'datasets/test/test1.MOV' experiment_name = "2russ2qi_D5" epoch = 200 # import cv2, os, sys, pdb, shutil import numpy as np def mkdir_if_not_exist(path): if not os.path.exists(path): os.makedirs(path) else: #delete all in the path shutil.rmtree(path) os.makedirs(path) def main(): current_dir = os.getcwd() extract_folder = os.path.join(os.getcwd(), test_video_path.replace('.MOV', '')) mkdir_if_not_exist(extract_folder) # resize video resize_video_path = test_video_path.replace('.MOV', '_resized.mp4') resize_video_command = "ffmpeg -i " + test_video_path + " -filter:v \"crop=1080:1080:420:0\" -c:a copy " + resize_video_path os.system(resize_video_command) # extract each frame of the video extract_folder_testA = os.path.join(extract_folder, 'testA') mkdir_if_not_exist(extract_folder_testA) extract_folder_testB = os.path.join(extract_folder, 'testB') mkdir_if_not_exist(extract_folder_testB) copy_command = "cp %s/* %s/" % (extract_folder_testA, extract_folder_testB) extract_video_command = "ffmpeg -i " + resize_video_path + " " + extract_folder_testA + "/%03d.png" os.system(extract_video_command) os.system(copy_command) # extract audio audio_path = resize_video_path.replace("mp4", "mp3") extract_audio_command = "ffmpeg -i " + resize_video_path + " -q:a 0 -map a " + audio_path os.system(extract_audio_command) # forward all the images run_pytorch_command = ('python test.py --gpu_ids 2 --which_epoch %d --dataroot %s --name %s --model cycle_gan --phase test --serial_batches --resize_or_crop scale_width --which_direction BtoA' % (epoch, extract_folder, experiment_name)) os.system(run_pytorch_command) fake_folder = extract_folder + "_fake" mkdir_if_not_exist(fake_folder) # copy all the files from original result folder to _fake folder copy_result_command = ("cp results/%s/test_%d/images/* %s" % (experiment_name, epoch, fake_folder)) os.system(copy_result_command) extracted_files = [s for s in os.listdir(fake_folder) if s.endswith('_fake_A.png')] extract_files_num = len(extracted_files) # combine all output images to get a full video output_video_no_sound_path = test_video_path.replace('.MOV', '_no_sound.avi') fourcc = cv2.VideoWriter_fourcc(*'MJPG') out = cv2.VideoWriter(os.path.join(current_dir, output_video_no_sound_path),fourcc, 30.0, (512, 256), True) for i in range(extract_files_num): fake_frame_name = os.path.join(fake_folder, ("%03d_fake_A.png" % (i+1))) real_frame_name = os.path.join(extract_folder_testA, ("%03d.png" % (i+1))) if os.path.exists(fake_frame_name) and os.path.exists(real_frame_name): fake_img = cv2.imread(fake_frame_name) real_img = cv2.resize(cv2.imread(real_frame_name), (256, 256)) #pdb.set_trace() img = np.concatenate((real_img, fake_img), axis=1) out.write(img) print("writing %s" % fake_frame_name) else: print("path %s not exist!" % fake_frame_name) # Release everything if job is finished out.release() print("Finished getting fake video (without sound)") # add audio to video output_video_path = test_video_path.replace('.MOV', '_output.mkv') add_audio_command = "ffmpeg -i " + output_video_no_sound_path + " -i " + audio_path + " -map 0 -map 1 -codec copy " + output_video_path os.system(add_audio_command) if __name__ == "__main__": main()
[ "cv2.VideoWriter_fourcc", "os.makedirs", "os.getcwd", "os.path.exists", "os.system", "cv2.imread", "shutil.rmtree", "os.path.join", "os.listdir", "numpy.concatenate" ]
[((593, 604), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (602, 604), False, 'import cv2, os, sys, pdb, shutil\n'), ((953, 984), 'os.system', 'os.system', (['resize_video_command'], {}), '(resize_video_command)\n', (962, 984), False, 'import cv2, os, sys, pdb, shutil\n'), ((1051, 1088), 'os.path.join', 'os.path.join', (['extract_folder', '"""testA"""'], {}), "(extract_folder, 'testA')\n", (1063, 1088), False, 'import cv2, os, sys, pdb, shutil\n'), ((1161, 1198), 'os.path.join', 'os.path.join', (['extract_folder', '"""testB"""'], {}), "(extract_folder, 'testB')\n", (1173, 1198), False, 'import cv2, os, sys, pdb, shutil\n'), ((1432, 1464), 'os.system', 'os.system', (['extract_video_command'], {}), '(extract_video_command)\n', (1441, 1464), False, 'import cv2, os, sys, pdb, shutil\n'), ((1469, 1492), 'os.system', 'os.system', (['copy_command'], {}), '(copy_command)\n', (1478, 1492), False, 'import cv2, os, sys, pdb, shutil\n'), ((1669, 1701), 'os.system', 'os.system', (['extract_audio_command'], {}), '(extract_audio_command)\n', (1678, 1701), False, 'import cv2, os, sys, pdb, shutil\n'), ((1977, 2007), 'os.system', 'os.system', (['run_pytorch_command'], {}), '(run_pytorch_command)\n', (1986, 2007), False, 'import cv2, os, sys, pdb, shutil\n'), ((2265, 2295), 'os.system', 'os.system', (['copy_result_command'], {}), '(copy_result_command)\n', (2274, 2295), False, 'import cv2, os, sys, pdb, shutil\n'), ((2578, 2609), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (2600, 2609), False, 'import cv2, os, sys, pdb, shutil\n'), ((3734, 3762), 'os.system', 'os.system', (['add_audio_command'], {}), '(add_audio_command)\n', (3743, 3762), False, 'import cv2, os, sys, pdb, shutil\n'), ((418, 438), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (432, 438), False, 'import cv2, os, sys, pdb, shutil\n'), ((448, 465), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (459, 465), False, 'import cv2, os, sys, pdb, shutil\n'), ((516, 535), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (529, 535), False, 'import cv2, os, sys, pdb, shutil\n'), ((544, 561), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (555, 561), False, 'import cv2, os, sys, pdb, shutil\n'), ((639, 650), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (648, 650), False, 'import cv2, os, sys, pdb, shutil\n'), ((2636, 2689), 'os.path.join', 'os.path.join', (['current_dir', 'output_video_no_sound_path'], {}), '(current_dir, output_video_no_sound_path)\n', (2648, 2689), False, 'import cv2, os, sys, pdb, shutil\n'), ((2788, 2842), 'os.path.join', 'os.path.join', (['fake_folder', "('%03d_fake_A.png' % (i + 1))"], {}), "(fake_folder, '%03d_fake_A.png' % (i + 1))\n", (2800, 2842), False, 'import cv2, os, sys, pdb, shutil\n'), ((2869, 2925), 'os.path.join', 'os.path.join', (['extract_folder_testA', "('%03d.png' % (i + 1))"], {}), "(extract_folder_testA, '%03d.png' % (i + 1))\n", (2881, 2925), False, 'import cv2, os, sys, pdb, shutil\n'), ((2331, 2354), 'os.listdir', 'os.listdir', (['fake_folder'], {}), '(fake_folder)\n', (2341, 2354), False, 'import cv2, os, sys, pdb, shutil\n'), ((2937, 2968), 'os.path.exists', 'os.path.exists', (['fake_frame_name'], {}), '(fake_frame_name)\n', (2951, 2968), False, 'import cv2, os, sys, pdb, shutil\n'), ((2973, 3004), 'os.path.exists', 'os.path.exists', (['real_frame_name'], {}), '(real_frame_name)\n', (2987, 3004), False, 'import cv2, os, sys, pdb, shutil\n'), ((3029, 3056), 'cv2.imread', 'cv2.imread', (['fake_frame_name'], {}), '(fake_frame_name)\n', (3039, 3056), False, 'import cv2, os, sys, pdb, shutil\n'), ((3179, 3223), 'numpy.concatenate', 'np.concatenate', (['(real_img, fake_img)'], {'axis': '(1)'}), '((real_img, fake_img), axis=1)\n', (3193, 3223), True, 'import numpy as np\n'), ((3091, 3118), 'cv2.imread', 'cv2.imread', (['real_frame_name'], {}), '(real_frame_name)\n', (3101, 3118), False, 'import cv2, os, sys, pdb, shutil\n')]
# coding: utf-8 import numpy as np import pandas as pd ################################################## # メイン ################################################## if __name__ == '__main__': # Here is how to view the top and bottom rows of the frame: print("------------------------------------------------------------------") print("Here is how to view the top and bottom rows of the frame:") dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD')) print("------------------------------") print("df.head():") print(df.head()) print("------------------------------") print("df.tail(3):") print(df.tail(3)) # Display the index, columns: print("------------------------------------------------------------------") print("Display the index, columns:") print("------------------------------") print("df.index:") print(df.index) print("------------------------------") print("df.columns:") print(df.columns) # DataFrame.to_numpy() gives a NumPy representation of the underlying data. print("------------------------------------------------------------------") print("DataFrame.to_numpy() gives a NumPy representation of the underlying data. ") df2 = pd.DataFrame({ 'A': 1., 'B': pd.Timestamp('20130102'), 'C': pd.Series(1, index=list(range(4)), dtype='float32'), 'D': np.array([3] * 4, dtype='int32'), 'E': pd.Categorical(["test", "train", "test", "train"]), 'F': 'foo' }) print("------------------------------") print("df.to_numpy():") print(df.to_numpy()) print("------------------------------") print("df2.to_numpy():") print(df2.to_numpy()) # describe() shows a quick statistic summary of your data: print("------------------------------------------------------------------") print("describe() shows a quick statistic summary of your data:") print(df.describe()) # Transposing your data: print("------------------------------------------------------------------") print("Transposing your data:") print(df.T) # Sorting by an axis: # sort_index:行名や列名でソートする print("------------------------------------------------------------------") print("Sorting by an axis:") print("------------------------------") print("df.sort_index(axis=0, ascending=False):") print(df.sort_index(axis=0, ascending=False)) print("------------------------------") print("df.sort_index(axis=1, ascending=False):") print(df.sort_index(axis=1, ascending=False)) # Sorting by values: # sort_index:行名や列名でソートする print("------------------------------------------------------------------") print("Sorting by values:") print("------------------------------") print("df.sort_values(by='B')") print(df.sort_values(by='B', ascending=True))
[ "pandas.Timestamp", "pandas.date_range", "numpy.random.randn", "numpy.array", "pandas.Categorical" ]
[((420, 456), 'pandas.date_range', 'pd.date_range', (['"""20130101"""'], {'periods': '(6)'}), "('20130101', periods=6)\n", (433, 456), True, 'import pandas as pd\n'), ((479, 500), 'numpy.random.randn', 'np.random.randn', (['(6)', '(4)'], {}), '(6, 4)\n', (494, 500), True, 'import numpy as np\n'), ((1368, 1392), 'pandas.Timestamp', 'pd.Timestamp', (['"""20130102"""'], {}), "('20130102')\n", (1380, 1392), True, 'import pandas as pd\n'), ((1481, 1513), 'numpy.array', 'np.array', (['([3] * 4)'], {'dtype': '"""int32"""'}), "([3] * 4, dtype='int32')\n", (1489, 1513), True, 'import numpy as np\n'), ((1532, 1582), 'pandas.Categorical', 'pd.Categorical', (["['test', 'train', 'test', 'train']"], {}), "(['test', 'train', 'test', 'train'])\n", (1546, 1582), True, 'import pandas as pd\n')]
import time import h5py import cv2 import numpy as np from scipy.sparse import csr_matrix, save_npz, diags, eye from scipy.sparse.linalg import norm cv2.useOptimized() hg38dim = [248956422, 242193529, 198295559, 190214555, 181538259, 170805979, 159345973, 145138636, 138394717, 133797422, 135086622, 133275309, 114364328, 107043718, 101991189, 90338345, 83257441, 80373285, 58617616, 64444167, 46709983, 50818468] hg19dim = [249250621, 243199373, 198022430, 191154276, 180915260, 171115067, 159138663, 146364022, 141213431, 135534747, 135006516, 133851895, 115169878, 107349540, 102531392, 90354753, 81195210, 78077248, 59128983, 63025520, 48129895, 51304566] mm10dim = [195471971, 182113224, 160039680, 156508116, 151834684, 149736546, 145441459, 129401213, 124595110, 130694993, 122082543, 120129022, 120421639, 124902244, 104043685, 98207768, 94987271, 90702639, 61431566] def random_walk_cpu(P, rp, tol, dist, spr): global ngene if rp == 1: return P I = eye(ngene) Q = rp * I + (1 - rp) * P if dist < ngene: idx = np.triu_indices(ngene, 0) idxfilter = ((idx[1] - idx[0]) < dist) idx = ( np.concatenate((idx[0][idxfilter], idx[1][idxfilter])), np.concatenate((idx[1][idxfilter], idx[0][idxfilter]))) mask = csr_matrix((np.ones(len(idx[0])), (idx[0], idx[1])), P.shape) start_time = time.time() for i in range(30): Q_new = rp * I + (1 - rp) * P.dot(Q) delta = norm(Q - Q_new) Q = Q_new.copy() sparsity = Q.nnz / ngene / ngene if (dist < ngene) and (sparsity > spr): Q = Q.multiply(mask) end_time = time.time() print('Iter', i + 1, 'takes', end_time - start_time, 'seconds, loss', delta, 'sparsity', sparsity) if delta < tol: break return Q def impute_cell(indir, outdir, cell, chrom, res, genome, mode, logscale=False, pad=1, std=1, rp=0.5, tol=0.01, rwr_dist=500000000, rwr_sparsity=1, output_dist=500000000, output_format='hdf'): if chrom[:3] == 'chr': c = chrom[3:] else: c = chrom if not mode: mode = 'pad' + str(pad) + '_std' + str(std) + '_rp' + str(rp) + '_sqrtvc' if genome == 'hg38': chrom = [str(i + 1) for i in range(22)] chromsize = {x: y for x, y in zip(chrom, hg38dim)} elif genome == 'hg19': chrom = [str(i + 1) for i in range(22)] chromsize = {x: y for x, y in zip(chrom, hg19dim)} elif genome == 'mm10': chrom = [str(i + 1) for i in range(19)] chromsize = {x: y for x, y in zip(chrom, mm10dim)} else: # TODO instead of using fixed chrom info, use chrom size file raise NotImplementedError start_time = time.time() ngene = int(chromsize[c] // res) + 1 D = np.loadtxt(indir + cell + '_chr' + c + '.txt') if len(D) == 0: D = np.array([[0, 0, 0]]) elif len(D.shape) == 1: D = D.reshape(1, -1) A = csr_matrix((D[:, 2], (D[:, 0], D[:, 1])), shape=(ngene, ngene)) if logscale: A.data = np.log2(A.data + 1) end_time = time.time() print('Loading chr', c, 'takes', end_time - start_time, 'seconds') start_time = time.time() B = cv2.GaussianBlur((A + A.T).toarray().astype(np.float32), (pad * 2 + 1, pad * 2 + 1), std) end_time = time.time() print('Convolution chr', c, 'take', end_time - start_time, 'seconds') start_time = time.time() B = csr_matrix(B) B = B - diags(B.diagonal()) B = B + diags((B.sum(axis=0).A.ravel() == 0).astype(int)) d = diags(1 / B.sum(axis=0).A.ravel()) P = d.dot(B) Q = random_walk_cpu(P, rp, tol, int(rwr_dist // res) + 1, rwr_sparsity) print('RWR', time.time() - start_time) start_time = time.time() E = Q + Q.T d = E.sum(axis=0).A.ravel() d[d == 0] = 1 b = diags(1 / np.sqrt(d)) E = b.dot(E).dot(b) print('SQRTVC', time.time() - start_time) start_time = time.time() idx = np.triu_indices(E.shape[0], 0) idxfilter = ((idx[1] - idx[0]) < (output_dist // res + 1)) idx = (idx[0][idxfilter], idx[1][idxfilter]) mask = csr_matrix((np.ones(len(idx[0])), (idx[0], idx[1])), E.shape) E = E.multiply(mask) E = E.tocsr() print('Filter', time.time() - start_time) if output_format == 'npz': save_npz(outdir + cell + '_chr' + c + '_' + mode + '.npz', E) else: f = h5py.File(outdir + cell + '_chr' + c + '_' + mode + '.hdf5', 'w') g = f.create_group('Matrix') g.create_dataset('data', data=E.data, dtype='float32', compression='gzip') g.create_dataset('indices', data=E.indices, dtype=int, compression='gzip') g.create_dataset('indptr', data=E.indptr, dtype=int, compression='gzip') g.attrs['shape'] = E.shape f.close() return
[ "h5py.File", "numpy.concatenate", "numpy.log2", "numpy.triu_indices", "time.time", "cv2.useOptimized", "scipy.sparse.csr_matrix", "numpy.array", "numpy.loadtxt", "scipy.sparse.save_npz", "scipy.sparse.linalg.norm", "scipy.sparse.eye", "numpy.sqrt" ]
[((150, 168), 'cv2.useOptimized', 'cv2.useOptimized', ([], {}), '()\n', (166, 168), False, 'import cv2\n'), ((1036, 1046), 'scipy.sparse.eye', 'eye', (['ngene'], {}), '(ngene)\n', (1039, 1046), False, 'from scipy.sparse import csr_matrix, save_npz, diags, eye\n'), ((1431, 1442), 'time.time', 'time.time', ([], {}), '()\n', (1440, 1442), False, 'import time\n'), ((3027, 3038), 'time.time', 'time.time', ([], {}), '()\n', (3036, 3038), False, 'import time\n'), ((3088, 3134), 'numpy.loadtxt', 'np.loadtxt', (["(indir + cell + '_chr' + c + '.txt')"], {}), "(indir + cell + '_chr' + c + '.txt')\n", (3098, 3134), True, 'import numpy as np\n'), ((3255, 3318), 'scipy.sparse.csr_matrix', 'csr_matrix', (['(D[:, 2], (D[:, 0], D[:, 1]))'], {'shape': '(ngene, ngene)'}), '((D[:, 2], (D[:, 0], D[:, 1])), shape=(ngene, ngene))\n', (3265, 3318), False, 'from scipy.sparse import csr_matrix, save_npz, diags, eye\n'), ((3389, 3400), 'time.time', 'time.time', ([], {}), '()\n', (3398, 3400), False, 'import time\n'), ((3490, 3501), 'time.time', 'time.time', ([], {}), '()\n', (3499, 3501), False, 'import time\n'), ((3615, 3626), 'time.time', 'time.time', ([], {}), '()\n', (3624, 3626), False, 'import time\n'), ((3719, 3730), 'time.time', 'time.time', ([], {}), '()\n', (3728, 3730), False, 'import time\n'), ((3739, 3752), 'scipy.sparse.csr_matrix', 'csr_matrix', (['B'], {}), '(B)\n', (3749, 3752), False, 'from scipy.sparse import csr_matrix, save_npz, diags, eye\n'), ((4044, 4055), 'time.time', 'time.time', ([], {}), '()\n', (4053, 4055), False, 'import time\n'), ((4240, 4251), 'time.time', 'time.time', ([], {}), '()\n', (4249, 4251), False, 'import time\n'), ((4262, 4292), 'numpy.triu_indices', 'np.triu_indices', (['E.shape[0]', '(0)'], {}), '(E.shape[0], 0)\n', (4277, 4292), True, 'import numpy as np\n'), ((1112, 1137), 'numpy.triu_indices', 'np.triu_indices', (['ngene', '(0)'], {}), '(ngene, 0)\n', (1127, 1137), True, 'import numpy as np\n'), ((1528, 1543), 'scipy.sparse.linalg.norm', 'norm', (['(Q - Q_new)'], {}), '(Q - Q_new)\n', (1532, 1543), False, 'from scipy.sparse.linalg import norm\n'), ((1710, 1721), 'time.time', 'time.time', ([], {}), '()\n', (1719, 1721), False, 'import time\n'), ((3167, 3188), 'numpy.array', 'np.array', (['[[0, 0, 0]]'], {}), '([[0, 0, 0]])\n', (3175, 3188), True, 'import numpy as np\n'), ((3353, 3372), 'numpy.log2', 'np.log2', (['(A.data + 1)'], {}), '(A.data + 1)\n', (3360, 3372), True, 'import numpy as np\n'), ((4607, 4668), 'scipy.sparse.save_npz', 'save_npz', (["(outdir + cell + '_chr' + c + '_' + mode + '.npz')", 'E'], {}), "(outdir + cell + '_chr' + c + '_' + mode + '.npz', E)\n", (4615, 4668), False, 'from scipy.sparse import csr_matrix, save_npz, diags, eye\n'), ((4691, 4756), 'h5py.File', 'h5py.File', (["(outdir + cell + '_chr' + c + '_' + mode + '.hdf5')", '"""w"""'], {}), "(outdir + cell + '_chr' + c + '_' + mode + '.hdf5', 'w')\n", (4700, 4756), False, 'import h5py\n'), ((1213, 1267), 'numpy.concatenate', 'np.concatenate', (['(idx[0][idxfilter], idx[1][idxfilter])'], {}), '((idx[0][idxfilter], idx[1][idxfilter]))\n', (1227, 1267), True, 'import numpy as np\n'), ((1281, 1335), 'numpy.concatenate', 'np.concatenate', (['(idx[1][idxfilter], idx[0][idxfilter])'], {}), '((idx[1][idxfilter], idx[0][idxfilter]))\n', (1295, 1335), True, 'import numpy as np\n'), ((4000, 4011), 'time.time', 'time.time', ([], {}), '()\n', (4009, 4011), False, 'import time\n'), ((4140, 4150), 'numpy.sqrt', 'np.sqrt', (['d'], {}), '(d)\n', (4147, 4150), True, 'import numpy as np\n'), ((4196, 4207), 'time.time', 'time.time', ([], {}), '()\n', (4205, 4207), False, 'import time\n'), ((4541, 4552), 'time.time', 'time.time', ([], {}), '()\n', (4550, 4552), False, 'import time\n')]
import tensorflow as tf import numpy as np import scipy.spatial from scipy.sparse import isspmatrix def get_placeholder_by_name(name): try: return tf.get_default_graph().get_tensor_by_name(name+":0") except: return tf.placeholder(tf.int32, name=name) def align_loss(embeddings, align_labels, gamma, num_negs, names_neg, mode="L1"): def loss_metric(X, Y): if mode == "L1": loss = tf.reduce_sum(tf.abs(X - Y), 1) elif mode == "sim": loss = tf.nn.sigmoid(-tf.reduce_sum(X * Y, 1)) else: exit("wrong loss mode") return loss def get_ranking_loss(names, num_labels): neg_left = get_placeholder_by_name(names[0]) neg_right = get_placeholder_by_name(names[1]) neg_l_x = tf.nn.embedding_lookup(embeddings, neg_left) neg_r_x = tf.nn.embedding_lookup(embeddings, neg_right) neg_value = loss_metric(neg_l_x, neg_r_x) neg_value = - tf.reshape(neg_value, [num_labels, num_negs]) loss_value = neg_value + tf.reshape(pos_value, [num_labels, 1]) loss_value = tf.nn.relu(loss_value) return loss_value left_labels = align_labels[:, 0] right_labels = align_labels[:, 1] num_labels = len(align_labels) left_x = tf.nn.embedding_lookup(embeddings, left_labels) right_x = tf.nn.embedding_lookup(embeddings, right_labels) pos_value = loss_metric(left_x, right_x) + gamma loss_1 = get_ranking_loss(names_neg[:2], num_labels) loss_2 = get_ranking_loss(names_neg[2:], num_labels) final_loss = tf.reduce_sum(loss_1) + tf.reduce_sum(loss_2) final_loss /= (2.0 * num_negs * num_labels) return final_loss def class_loss(embeddings, test, y): y_pre = tf.nn.embedding_lookup(embeddings, test) if isspmatrix(y): y_test = y[test].todense() y_true = tf.reshape(tf.argmax(y_test, 1), (1,-1)) else: y_test = y[test] y_true = tf.reshape(tf.argmax(y_test, 1), (1,-1)) loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_test, logits=y_pre) return tf.reduce_mean(loss) def label_loss(embeddings, test, y): y_pre = tf.nn.embedding_lookup(embeddings, test) if isspmatrix(y): y_test = y[test].todense() else: y_test = y[test] loss = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_test, logits=y_pre) return tf.reduce_mean(loss) def get_class(embeddings, test, y, logging): y_pre = embeddings[test] if isspmatrix(y): y_test = y[test].todense() y_true = np.argmax(y_test, 1).reshape(1,-1)[0] else: y_test = y[test] y_true = np.argmax(y_test, 1).reshape(1,-1) y_pre = np.argmax(y_pre, 1).reshape(1,-1) # print(np.concatenate([y_true, y_pre])) correct_prediction = np.equal(y_pre, y_true) acc = np.mean(correct_prediction) return acc, [acc] def get_label(embeddings, test, y, logging): y_pre = embeddings[test] if isspmatrix(y): y_test = y.todense()[test] y_test = np.squeeze(np.asarray(y_test)) else: y_test = y[test] y_pre = np.argsort(-y_pre, 1) result_list = [] for K in [1,3,5]: precision = 0 NDCG = 0 y_pre_K = y_pre[:, :K] coeff = 1./np.log(np.arange(1,K+1) + 1) for i,each in enumerate(y_pre_K): if np.sum(y_test[i]) <= 0: continue precision += np.sum(y_test[i, each])/K DCG_i = np.sum(y_test[i, each]*coeff) norm = np.sum(1./np.log(np.arange(1,min(K, np.sum(y_test[i]))+1) + 1)) NDCG_i = DCG_i/norm NDCG += NDCG_i precision = precision/len(y_pre_K) NDCG = NDCG/len(y_pre_K) logging.info("Classification Precision %d: %.3f" % (K, precision * 100)) logging.info("Classification NDCG %d: %.3f" % (K, NDCG * 100)) result_list.append(round(precision, 4)) result_list.append(round(NDCG, 4)) return result_list[4], result_list def get_align(embeddings, test_pair, logging, metric="cityblock", K=(1, 5, 10, 50, 100)): def get_metrics(sim, pos=0): top_hits = [0] * len(K) mrr = 0 for ind in range(sim.shape[pos]): rank_ind = np.where(sim[(slice(None),) * pos + (ind,)].argsort() == ind)[0][0] mrr += 1/(rank_ind+1) for j in range(len(K)): if rank_ind < K[j]: top_hits[j] += 1 return top_hits, mrr embeddings_left = np.array([embeddings[e1] for e1, _ in test_pair]) embeddings_right = np.array([embeddings[e2] for _, e2 in test_pair]) sim = scipy.spatial.distance.cdist(embeddings_left, embeddings_right, metric=metric) top_hits_l2r, mrr_l2r = get_metrics(sim, pos=0) top_hits_r2l, mrr_r2l = get_metrics(sim, pos=1) test_metric = ["Hits@{}".format(K[i]) for i in range(len(K))] test_metric = " ".join(test_metric) left_result = [top_hits_l2r[i] / len(test_pair) * 100 for i in range(len(K))] right_result = [top_hits_r2l[i] / len(test_pair) * 100 for i in range(len(K))] all_result = [(left_result[i] + right_result[i])/2 for i in range(len(right_result))] left_result = [str(round(i, 3)) for i in left_result] right_result = [str(round(i, 3)) for i in right_result] all_result = [str(round(i, 3)) for i in all_result] logging.info(test_metric) logging.info("l:\t" + "\t".join(left_result)) logging.info("r:\t" + "\t".join(right_result)) logging.info("a:\t" + "\t".join(all_result)) logging.info('MRR-l: %.3f' % (mrr_l2r / len(test_pair))) logging.info('MRR-r: %.3f' % (mrr_r2l / len(test_pair))) logging.info('MRR-a: %.3f' % ((mrr_l2r+mrr_r2l)/2 / len(test_pair)))
[ "tensorflow.reduce_sum", "numpy.sum", "numpy.argmax", "tensorflow.reshape", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "numpy.argsort", "numpy.mean", "numpy.arange", "tensorflow.get_default_graph", "scipy.sparse.isspmatrix", "tensorflow.nn.relu", "tensorflow.abs", "numpy.equal", "t...
[((1283, 1330), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'left_labels'], {}), '(embeddings, left_labels)\n', (1305, 1330), True, 'import tensorflow as tf\n'), ((1345, 1393), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'right_labels'], {}), '(embeddings, right_labels)\n', (1367, 1393), True, 'import tensorflow as tf\n'), ((1748, 1788), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'test'], {}), '(embeddings, test)\n', (1770, 1788), True, 'import tensorflow as tf\n'), ((1796, 1809), 'scipy.sparse.isspmatrix', 'isspmatrix', (['y'], {}), '(y)\n', (1806, 1809), False, 'from scipy.sparse import isspmatrix\n'), ((2008, 2079), 'tensorflow.nn.softmax_cross_entropy_with_logits_v2', 'tf.nn.softmax_cross_entropy_with_logits_v2', ([], {'labels': 'y_test', 'logits': 'y_pre'}), '(labels=y_test, logits=y_pre)\n', (2050, 2079), True, 'import tensorflow as tf\n'), ((2091, 2111), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (2105, 2111), True, 'import tensorflow as tf\n'), ((2162, 2202), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'test'], {}), '(embeddings, test)\n', (2184, 2202), True, 'import tensorflow as tf\n'), ((2210, 2223), 'scipy.sparse.isspmatrix', 'isspmatrix', (['y'], {}), '(y)\n', (2220, 2223), False, 'from scipy.sparse import isspmatrix\n'), ((2306, 2374), 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'y_test', 'logits': 'y_pre'}), '(labels=y_test, logits=y_pre)\n', (2345, 2374), True, 'import tensorflow as tf\n'), ((2386, 2406), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['loss'], {}), '(loss)\n', (2400, 2406), True, 'import tensorflow as tf\n'), ((2489, 2502), 'scipy.sparse.isspmatrix', 'isspmatrix', (['y'], {}), '(y)\n', (2499, 2502), False, 'from scipy.sparse import isspmatrix\n'), ((2797, 2820), 'numpy.equal', 'np.equal', (['y_pre', 'y_true'], {}), '(y_pre, y_true)\n', (2805, 2820), True, 'import numpy as np\n'), ((2831, 2858), 'numpy.mean', 'np.mean', (['correct_prediction'], {}), '(correct_prediction)\n', (2838, 2858), True, 'import numpy as np\n'), ((2963, 2976), 'scipy.sparse.isspmatrix', 'isspmatrix', (['y'], {}), '(y)\n', (2973, 2976), False, 'from scipy.sparse import isspmatrix\n'), ((3108, 3129), 'numpy.argsort', 'np.argsort', (['(-y_pre)', '(1)'], {}), '(-y_pre, 1)\n', (3118, 3129), True, 'import numpy as np\n'), ((4500, 4549), 'numpy.array', 'np.array', (['[embeddings[e1] for e1, _ in test_pair]'], {}), '([embeddings[e1] for e1, _ in test_pair])\n', (4508, 4549), True, 'import numpy as np\n'), ((4573, 4622), 'numpy.array', 'np.array', (['[embeddings[e2] for _, e2 in test_pair]'], {}), '([embeddings[e2] for _, e2 in test_pair])\n', (4581, 4622), True, 'import numpy as np\n'), ((790, 834), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'neg_left'], {}), '(embeddings, neg_left)\n', (812, 834), True, 'import tensorflow as tf\n'), ((853, 898), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['embeddings', 'neg_right'], {}), '(embeddings, neg_right)\n', (875, 898), True, 'import tensorflow as tf\n'), ((1110, 1132), 'tensorflow.nn.relu', 'tf.nn.relu', (['loss_value'], {}), '(loss_value)\n', (1120, 1132), True, 'import tensorflow as tf\n'), ((1580, 1601), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss_1'], {}), '(loss_1)\n', (1593, 1601), True, 'import tensorflow as tf\n'), ((1604, 1625), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss_2'], {}), '(loss_2)\n', (1617, 1625), True, 'import tensorflow as tf\n'), ((241, 276), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': 'name'}), '(tf.int32, name=name)\n', (255, 276), True, 'import tensorflow as tf\n'), ((971, 1016), 'tensorflow.reshape', 'tf.reshape', (['neg_value', '[num_labels, num_negs]'], {}), '(neg_value, [num_labels, num_negs])\n', (981, 1016), True, 'import tensorflow as tf\n'), ((1050, 1088), 'tensorflow.reshape', 'tf.reshape', (['pos_value', '[num_labels, 1]'], {}), '(pos_value, [num_labels, 1])\n', (1060, 1088), True, 'import tensorflow as tf\n'), ((1874, 1894), 'tensorflow.argmax', 'tf.argmax', (['y_test', '(1)'], {}), '(y_test, 1)\n', (1883, 1894), True, 'import tensorflow as tf\n'), ((1967, 1987), 'tensorflow.argmax', 'tf.argmax', (['y_test', '(1)'], {}), '(y_test, 1)\n', (1976, 1987), True, 'import tensorflow as tf\n'), ((2693, 2712), 'numpy.argmax', 'np.argmax', (['y_pre', '(1)'], {}), '(y_pre, 1)\n', (2702, 2712), True, 'import numpy as np\n'), ((3041, 3059), 'numpy.asarray', 'np.asarray', (['y_test'], {}), '(y_test)\n', (3051, 3059), True, 'import numpy as np\n'), ((3469, 3500), 'numpy.sum', 'np.sum', (['(y_test[i, each] * coeff)'], {}), '(y_test[i, each] * coeff)\n', (3475, 3500), True, 'import numpy as np\n'), ((161, 183), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (181, 183), True, 'import tensorflow as tf\n'), ((445, 458), 'tensorflow.abs', 'tf.abs', (['(X - Y)'], {}), '(X - Y)\n', (451, 458), True, 'import tensorflow as tf\n'), ((2646, 2666), 'numpy.argmax', 'np.argmax', (['y_test', '(1)'], {}), '(y_test, 1)\n', (2655, 2666), True, 'import numpy as np\n'), ((3349, 3366), 'numpy.sum', 'np.sum', (['y_test[i]'], {}), '(y_test[i])\n', (3355, 3366), True, 'import numpy as np\n'), ((3423, 3446), 'numpy.sum', 'np.sum', (['y_test[i, each]'], {}), '(y_test[i, each])\n', (3429, 3446), True, 'import numpy as np\n'), ((2556, 2576), 'numpy.argmax', 'np.argmax', (['y_test', '(1)'], {}), '(y_test, 1)\n', (2565, 2576), True, 'import numpy as np\n'), ((3270, 3289), 'numpy.arange', 'np.arange', (['(1)', '(K + 1)'], {}), '(1, K + 1)\n', (3279, 3289), True, 'import numpy as np\n'), ((525, 548), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * Y)', '(1)'], {}), '(X * Y, 1)\n', (538, 548), True, 'import tensorflow as tf\n'), ((3554, 3571), 'numpy.sum', 'np.sum', (['y_test[i]'], {}), '(y_test[i])\n', (3560, 3571), True, 'import numpy as np\n')]
import argparse import os import hashlib import random import subprocess import h5py import numpy import constants import creator import util if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--config', default='default') parser.add_argument('--display', action='store_true', default=False) args = parser.parse_args() seed = int(hashlib.md5(args.config.encode('utf-8')).hexdigest()[:8], 16) random.seed(seed) numpy.random.seed(seed) config = util.load_config('config/collect/{:s}.yml'.format(args.config)) env = creator.create_environment(config.environment) save_dir = constants.SAVE_ROOT_DIR + args.config + '/' subprocess.check_output(['mkdir', '-p', save_dir]) save_path = save_dir + constants.SAVE_DATA_NAME assert not os.path.isfile(save_path) h5_file = h5py.File(save_path, 'w') env.init() env.set_camera('self') if not args.display: env.off_display() if config.grid: n = 0 xmin = env.world.config.xmin xmax = env.world.config.xmax ymin = env.world.config.ymin ymax = env.world.config.ymax N = config.num_div * config.num_div m_shape = (N, N, constants.MOTION_DIM) v_shape = (N, N, env.world.config.camera.agent.height, env.world.config.camera.agent.width, constants.VISION_CHANNELS) p_shape = m_shape mode = 'train' data = { 'self_vision': h5_file.create_dataset(mode + '/self_vision', v_shape, dtype='f'), 'other_vision': h5_file.create_dataset(mode + '/other_vision', v_shape, dtype='f'), 'self_vision_no_agent': h5_file.create_dataset( mode + '/self_vision_no_agent', v_shape, dtype='f'), 'other_vision_no_agent': h5_file.create_dataset( mode + '/other_vision_no_agent', v_shape, dtype='f'), 'self_position': h5_file.create_dataset( mode + '/self_position', p_shape, dtype='f'), 'other_position': h5_file.create_dataset( mode + '/other_position', p_shape, dtype='f'), } for ox in numpy.linspace(xmin, xmax, config.num_div): for oy in numpy.linspace(ymin, ymax, config.num_div): op = numpy.array([ox, oy]) t = 0 for sx in numpy.linspace(xmin, xmax, config.num_div): for sy in numpy.linspace(ymin, ymax, config.num_div): print(n, t) sp = numpy.array([sx, sy]) env.set_agent_pos(sp, op) env.set_camera('self') self_vision = env.capture() env.set_camera('other') other_vision = env.capture() env.set_camera('self') env.world.set_visible(False, False) self_vision_no_agent = env.capture() env.set_camera('other') env.world.set_visible(False, False) other_vision_no_agent = env.capture() data['self_vision'][n, t, :] = self_vision data['other_vision'][n, t, :] = other_vision data['self_vision_no_agent'][ n, t, :] = self_vision_no_agent data['other_vision_no_agent'][ n, t, :] = other_vision_no_agent data['self_position'][n, t, :] = sp data['other_position'][n, t, :] = op t += 1 n += 1 else: for mode, n_data in config.n_data.items(): print(mode, n_data) m_shape = (n_data, config.seq_length, constants.MOTION_DIM) p_shape = m_shape v_shape = (n_data, config.seq_length, env.world.config.camera.agent.height, env.world.config.camera.agent.width, constants.VISION_CHANNELS) data = { 'self_motion': h5_file.create_dataset( mode + '/self_motion', m_shape, dtype='f'), 'self_vision': h5_file.create_dataset( mode + '/self_vision', v_shape, dtype='f'), 'self_position': h5_file.create_dataset( mode + '/self_position', p_shape, dtype='f'), 'other_motion': h5_file.create_dataset( mode + '/other_motion', m_shape, dtype='f'), 'other_position': h5_file.create_dataset( mode + '/other_position', p_shape, dtype='f'), } if config.other_vision: data['other_vision'] = h5_file.create_dataset( mode + '/other_vision', v_shape, dtype='f') # do collect for n in range(n_data): env.reset() for t in range(config.seq_length): print(n, t) if config.other_vision: env.set_camera('other') ov = env.capture() data['other_vision'][n, t, :] = ov env.set_camera('self') sv, sm, om, sp, op = env.step() data['self_vision'][n, t, :] = sv data['self_motion'][n, t, :] = sm data['other_motion'][n, t, :] = om data['self_position'][n, t, :] = sp data['other_position'][n, t, :] = op
[ "h5py.File", "numpy.random.seed", "argparse.ArgumentParser", "creator.create_environment", "subprocess.check_output", "os.path.isfile", "random.seed", "numpy.array", "numpy.linspace" ]
[((186, 211), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (209, 211), False, 'import argparse\n'), ((453, 470), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (464, 470), False, 'import random\n'), ((475, 498), 'numpy.random.seed', 'numpy.random.seed', (['seed'], {}), '(seed)\n', (492, 498), False, 'import numpy\n'), ((587, 633), 'creator.create_environment', 'creator.create_environment', (['config.environment'], {}), '(config.environment)\n', (613, 633), False, 'import creator\n'), ((698, 748), 'subprocess.check_output', 'subprocess.check_output', (["['mkdir', '-p', save_dir]"], {}), "(['mkdir', '-p', save_dir])\n", (721, 748), False, 'import subprocess\n'), ((858, 883), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (867, 883), False, 'import h5py\n'), ((817, 842), 'os.path.isfile', 'os.path.isfile', (['save_path'], {}), '(save_path)\n', (831, 842), False, 'import os\n'), ((2271, 2313), 'numpy.linspace', 'numpy.linspace', (['xmin', 'xmax', 'config.num_div'], {}), '(xmin, xmax, config.num_div)\n', (2285, 2313), False, 'import numpy\n'), ((2337, 2379), 'numpy.linspace', 'numpy.linspace', (['ymin', 'ymax', 'config.num_div'], {}), '(ymin, ymax, config.num_div)\n', (2351, 2379), False, 'import numpy\n'), ((2403, 2424), 'numpy.array', 'numpy.array', (['[ox, oy]'], {}), '([ox, oy])\n', (2414, 2424), False, 'import numpy\n'), ((2473, 2515), 'numpy.linspace', 'numpy.linspace', (['xmin', 'xmax', 'config.num_div'], {}), '(xmin, xmax, config.num_div)\n', (2487, 2515), False, 'import numpy\n'), ((2547, 2589), 'numpy.linspace', 'numpy.linspace', (['ymin', 'ymax', 'config.num_div'], {}), '(ymin, ymax, config.num_div)\n', (2561, 2589), False, 'import numpy\n'), ((2657, 2678), 'numpy.array', 'numpy.array', (['[sx, sy]'], {}), '([sx, sy])\n', (2668, 2678), False, 'import numpy\n')]
# test_star_process from star_process import STAR import numpy as np if __name__ == "__main__": N = 250 mu_params = np.array( [0.05, -0.15]) sigma_params = np.array( [0.0, 0.0]) AR_params = np.array([[0.0, 0 ], [0.0, 0] ]) #gamma = 1.5 gamma = float('inf') star_model = STAR(mu_params, sigma_params, AR_params, gamma) star_model.sim(N) star_model.plot(colored=True)
[ "star_process.STAR", "numpy.array" ]
[((129, 152), 'numpy.array', 'np.array', (['[0.05, -0.15]'], {}), '([0.05, -0.15])\n', (137, 152), True, 'import numpy as np\n'), ((203, 223), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (211, 223), True, 'import numpy as np\n'), ((274, 304), 'numpy.array', 'np.array', (['[[0.0, 0], [0.0, 0]]'], {}), '([[0.0, 0], [0.0, 0]])\n', (282, 304), True, 'import numpy as np\n'), ((409, 456), 'star_process.STAR', 'STAR', (['mu_params', 'sigma_params', 'AR_params', 'gamma'], {}), '(mu_params, sigma_params, AR_params, gamma)\n', (413, 456), False, 'from star_process import STAR\n')]
import numpy as np from scipy.ndimage import map_coordinates import zarr from numcodecs import Blosc from bigstream import stitch import dask.array as da from scipy.ndimage import zoom import ClusterWrap WORKER_BUFFER = 8 def position_grid(shape, dtype=np.uint16): """ """ coords = np.array( np.meshgrid(*[range(x) for x in shape], indexing='ij'), dtype=dtype, ) return np.ascontiguousarray(np.moveaxis(coords, 0, -1)) def affine_to_grid(matrix, grid, displacement=False): """ """ mm = matrix[:3, :-1] tt = matrix[:3, -1] result = np.einsum('...ij,...j->...i', mm, grid) + tt if displacement: result = result - grid return result def interpolate_image(image, X, order=1): """ """ X = np.moveaxis(X, -1, 0) return map_coordinates(image, X, order=order, mode='constant') def apply_global_affine(fix, mov, fix_spacing, mov_spacing, affine, order=1): """ """ grid = position_grid(fix.shape) * fix_spacing coords = affine_to_grid(affine, grid) / mov_spacing return interpolate_image(mov, coords, order=order) # DASK versions for big data def position_grid_dask(shape, blocksize): """ """ coords = da.meshgrid(*[range(x) for x in shape], indexing='ij') coords = da.stack(coords, axis=-1).astype(np.uint16) return da.rechunk(coords, chunks=tuple(blocksize + [3,])) def affine_to_grid_dask(matrix, grid, displacement=False): """ """ ndims = len(matrix.shape) matrix = matrix.astype(np.float32).squeeze() lost_dims = ndims - len(matrix.shape) mm = matrix[:3, :-1] tt = matrix[:3, -1] result = da.einsum('...ij,...j->...i', mm, grid) + tt if displacement: result = result - grid if lost_dims > 0: result = result.reshape((1,)*lost_dims + result.shape) return result def local_affines_to_position_field( shape, spacing, blocksize, local_affines, global_affine=None, write_path=None, lazy=True, # cluster_kwargs={}, ): """ """ # get number of jobs needed block_grid = local_affines.shape[:3] nblocks = np.prod(block_grid) overlap = [int(round(x/8)) for x in blocksize] # compose with global affine total_affines = np.copy(local_affines) if global_affine is not None: g = np.eye(4) g[:3, :] = global_affine for i in range(nblocks): x, y, z = np.unravel_index(i, block_grid) l = np.eye(4) l[:3, :] = total_affines[x, y, z] total_affines[x, y, z] = np.matmul(g, l)[:3, :] # create cluster # with ClusterWrap.cluster(**cluster_kwargs) as cluster: # if write_path is not None or not lazy: # cluster.scale_cluster(nblocks + WORKER_BUFFER) # create position grid grid_da = position_grid_dask( np.array(blocksize)*block_grid, blocksize, ) grid_da = grid_da * spacing.astype(np.float32) grid_da = grid_da[..., None] # needed for map_overlap # wrap total_affines as dask array total_affines_da = da.from_array( total_affines.astype(np.float32), chunks=(1, 1, 1, 3, 4), ) # strip off dummy axis from position grid block def wrapped_affine_to_grid_dask(x, y): y = y.squeeze() return affine_to_grid_dask(x, y) # compute affine transforms as position coordinates coords = da.map_overlap( wrapped_affine_to_grid_dask, total_affines_da, grid_da, depth=[0, tuple(overlap)+(0,)], boundary=0, trim=False, align_arrays=False, dtype=np.float32, new_axis=[5,6], chunks=(1,1,1,)+tuple(x+2*y for x, y in zip(blocksize, overlap))+(3,), ) # stitch affine position fields coords = stitch.stitch_fields(coords, blocksize) # crop to original shape and rechunk coords = coords[:shape[0], :shape[1], :shape[2]] coords = coords.rechunk(tuple(blocksize + [3,])) # if user wants to write to disk if write_path is not None: compressor = Blosc(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE) coords_disk = zarr.open(write_path, 'w', shape=coords.shape, chunks=tuple(blocksize + [3,]), dtype=coords.dtype, compressor=compressor, ) da.to_zarr(coords, coords_disk) return coords_disk # if user wants to compute and return full field if not lazy: return coords.compute() # if user wants to return compute graph w/o executing if lazy: return coords def apply_position_field( fix, mov, fix_spacing, mov_spacing, transform, blocksize, transpose=[False,]*3, write_path=None, lazy=True, # cluster_kwargs={}, ): """ """ # get number of jobs needed block_grid = np.ceil(np.array(fix.shape) / blocksize).astype(int) if transpose[0]: block_grid = block_grid[::-1] nblocks = np.prod(block_grid) # start cluster #with ClusterWrap.cluster(**cluster_kwargs) as cluster: # if write_path is not None or not lazy: # cluster.scale_cluster(nblocks + WORKER_BUFFER) # wrap transform as dask array, define chunks transform_da = transform if not isinstance(transform, da.Array): transform_da = da.from_array(transform) if transpose[2]: transform_da = transform_da.transpose(2,1,0,3) transform_da = transform_da[..., ::-1] transform_da = transform_da.rechunk(tuple(blocksize + [3,])) # function for getting per block origins and spans def get_origin_and_span(t_block, mov_spacing): mins = t_block.min(axis=(0,1,2)) maxs = t_block.max(axis=(0,1,2)) os = np.empty((2,3)) os[0] = np.maximum(0, mins - 3*mov_spacing) os[1] = maxs - mins + 6*mov_spacing return os.reshape((1,1,1,2,3)) # get per block origins and spans os = da.map_blocks( get_origin_and_span, transform_da, mov_spacing=mov_spacing, dtype=np.float32, new_axis=[4,], chunks=(1,1,1,2,3), ).compute() # extract crop info and convert to voxel units origins = os[..., 0, :] span = np.max(os[..., 1, :], axis=(0,1,2)) origins_vox = np.round(origins / mov_spacing).astype(int) span = np.ceil(span / mov_spacing).astype(int) # wrap moving data as dask array mov_da = da.from_array(mov) if transpose[1]: mov_da = mov_da.transpose(2,1,0) # pad moving data dask array for blocking pads = [] for sh, sp in zip(mov_da.shape, span): diff = sp - sh % sp pad = (0, diff) if sh % sp > 0 else (0, 0) pads.append(pad) mov_da = da.pad(mov_da, pads) # construct moving blocks o, s, bg = origins_vox, span, block_grid mov_blocks = [[[mov_da[o[i,j,k,0]:o[i,j,k,0]+s[0], o[i,j,k,1]:o[i,j,k,1]+s[1], o[i,j,k,2]:o[i,j,k,2]+s[2]] for k in range(bg[2])] for j in range(bg[1])] for i in range(bg[0])] mov_da = da.block(mov_blocks)[..., None] mov_da = mov_da.rechunk(tuple(span) + (1,)) # wrap origins as dask array, define chunks origins_da = da.from_array(origins) origins_da = origins_da.rechunk((1,1,1,3)) # put transform in voxel units # position vectors are in moving coordinate system origins_da = origins_da / mov_spacing transform_da = transform_da / mov_spacing # wrap interpolate function def wrapped_interpolate_image(x, y, origin): x = x.squeeze() y = y - origin return interpolate_image(x, y) # map the interpolate function aligned = da.map_blocks( wrapped_interpolate_image, mov_da, transform_da, origins_da, dtype=np.uint16, chunks=tuple(blocksize), drop_axis=[3,], ) # if user wants to write to disk if write_path is not None: compressor = Blosc(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE) aligned_disk = zarr.open(write_path, 'w', shape=transform_da.shape[:-1], chunks=aligned.chunksize, dtype=aligned.dtype, compressor=compressor, ) da.to_zarr(aligned, aligned_disk) return aligned_disk # if user wants to compute and return full resampled image if not lazy: return aligned.compute() # if user wants to return compute graph w/o executing if lazy: return aligned def apply_local_affines( fix, mov, fix_spacing, mov_spacing, local_affines, blocksize, global_affine=None, write_path=None, lazy=True, transpose=[False,]*3, # cluster_kwargs={}, ): """ """ # get position field shape pf_shape = fix.shape if transpose[0]: pf_shape = pf_shape[::-1] # get task graph for local affines position field local_affines_pf = local_affines_to_position_field( pf_shape, fix_spacing, blocksize, local_affines, global_affine=global_affine, lazy=True, # cluster_kwargs=cluster_kwargs, ) # align aligned = apply_position_field( fix, mov, fix_spacing, mov_spacing, local_affines_pf, blocksize, write_path=write_path, lazy=lazy, transpose=transpose, #cluster_kwargs=cluster_kwargs, ) return aligned # TODO: refactor this function def compose_position_fields( fields, spacing, output, blocksize=[256,]*3, displacement=None, cluster_kwargs={}, ): """ """ # get number of jobs needed block_grid = np.ceil(np.array(fields[0].shape[:-1]) / blocksize).astype(int) nblocks = np.prod(block_grid) with ClusterWrap.cluster(**cluster_kwargs) as cluster: cluster.scale_cluster(nblocks + WORKER_BUFFER) # wrap fields as dask arrays fields_da = da.stack([da.from_array(f, chunks=blocksize+[3,]) for f in fields]) # accumulate composed = da.sum(fields_da, axis=0) # modify for multiple position fields if displacement is not None: raise NotImplementedError("composing displacement fields not implemented yet") else: grid = position_grid_dask(composed.shape[:3], blocksize) * spacing.astype(np.float32) composed = composed - (len(fields) - 1)*grid # write in parallel as 3D array to zarr file compressor = Blosc(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE) composed_disk = zarr.open(output, 'w', shape=composed.shape, chunks=composed.chunksize, dtype=composed.dtype, compressor=compressor, ) da.to_zarr(composed, composed_disk) # return pointer to zarr file return composed_disk
[ "numpy.moveaxis", "numpy.maximum", "numpy.empty", "numpy.einsum", "numpy.round", "numpy.prod", "dask.array.block", "zarr.open", "numpy.eye", "numpy.copy", "numpy.max", "dask.array.einsum", "dask.array.to_zarr", "numpy.ceil", "bigstream.stitch.stitch_fields", "dask.array.map_blocks", ...
[((777, 798), 'numpy.moveaxis', 'np.moveaxis', (['X', '(-1)', '(0)'], {}), '(X, -1, 0)\n', (788, 798), True, 'import numpy as np\n'), ((810, 865), 'scipy.ndimage.map_coordinates', 'map_coordinates', (['image', 'X'], {'order': 'order', 'mode': '"""constant"""'}), "(image, X, order=order, mode='constant')\n", (825, 865), False, 'from scipy.ndimage import map_coordinates\n'), ((2147, 2166), 'numpy.prod', 'np.prod', (['block_grid'], {}), '(block_grid)\n', (2154, 2166), True, 'import numpy as np\n'), ((2272, 2294), 'numpy.copy', 'np.copy', (['local_affines'], {}), '(local_affines)\n', (2279, 2294), True, 'import numpy as np\n'), ((3801, 3840), 'bigstream.stitch.stitch_fields', 'stitch.stitch_fields', (['coords', 'blocksize'], {}), '(coords, blocksize)\n', (3821, 3840), False, 'from bigstream import stitch\n'), ((4960, 4979), 'numpy.prod', 'np.prod', (['block_grid'], {}), '(block_grid)\n', (4967, 4979), True, 'import numpy as np\n'), ((6205, 6242), 'numpy.max', 'np.max', (['os[..., 1, :]'], {'axis': '(0, 1, 2)'}), '(os[..., 1, :], axis=(0, 1, 2))\n', (6211, 6242), True, 'import numpy as np\n'), ((6405, 6423), 'dask.array.from_array', 'da.from_array', (['mov'], {}), '(mov)\n', (6418, 6423), True, 'import dask.array as da\n'), ((6707, 6727), 'dask.array.pad', 'da.pad', (['mov_da', 'pads'], {}), '(mov_da, pads)\n', (6713, 6727), True, 'import dask.array as da\n'), ((7307, 7329), 'dask.array.from_array', 'da.from_array', (['origins'], {}), '(origins)\n', (7320, 7329), True, 'import dask.array as da\n'), ((9751, 9770), 'numpy.prod', 'np.prod', (['block_grid'], {}), '(block_grid)\n', (9758, 9770), True, 'import numpy as np\n'), ((430, 456), 'numpy.moveaxis', 'np.moveaxis', (['coords', '(0)', '(-1)'], {}), '(coords, 0, -1)\n', (441, 456), True, 'import numpy as np\n'), ((593, 632), 'numpy.einsum', 'np.einsum', (['"""...ij,...j->...i"""', 'mm', 'grid'], {}), "('...ij,...j->...i', mm, grid)\n", (602, 632), True, 'import numpy as np\n'), ((1665, 1704), 'dask.array.einsum', 'da.einsum', (['"""...ij,...j->...i"""', 'mm', 'grid'], {}), "('...ij,...j->...i', mm, grid)\n", (1674, 1704), True, 'import dask.array as da\n'), ((2341, 2350), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2347, 2350), True, 'import numpy as np\n'), ((4079, 4134), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""zstd"""', 'clevel': '(9)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE)\n", (4084, 4134), False, 'from numcodecs import Blosc\n'), ((4321, 4352), 'dask.array.to_zarr', 'da.to_zarr', (['coords', 'coords_disk'], {}), '(coords, coords_disk)\n', (4331, 4352), True, 'import dask.array as da\n'), ((5316, 5340), 'dask.array.from_array', 'da.from_array', (['transform'], {}), '(transform)\n', (5329, 5340), True, 'import dask.array as da\n'), ((5731, 5747), 'numpy.empty', 'np.empty', (['(2, 3)'], {}), '((2, 3))\n', (5739, 5747), True, 'import numpy as np\n'), ((5763, 5800), 'numpy.maximum', 'np.maximum', (['(0)', '(mins - 3 * mov_spacing)'], {}), '(0, mins - 3 * mov_spacing)\n', (5773, 5800), True, 'import numpy as np\n'), ((7161, 7181), 'dask.array.block', 'da.block', (['mov_blocks'], {}), '(mov_blocks)\n', (7169, 7181), True, 'import dask.array as da\n'), ((8044, 8099), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""zstd"""', 'clevel': '(9)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE)\n", (8049, 8099), False, 'from numcodecs import Blosc\n'), ((8123, 8255), 'zarr.open', 'zarr.open', (['write_path', '"""w"""'], {'shape': 'transform_da.shape[:-1]', 'chunks': 'aligned.chunksize', 'dtype': 'aligned.dtype', 'compressor': 'compressor'}), "(write_path, 'w', shape=transform_da.shape[:-1], chunks=aligned.\n chunksize, dtype=aligned.dtype, compressor=compressor)\n", (8132, 8255), False, 'import zarr\n'), ((8293, 8326), 'dask.array.to_zarr', 'da.to_zarr', (['aligned', 'aligned_disk'], {}), '(aligned, aligned_disk)\n', (8303, 8326), True, 'import dask.array as da\n'), ((9781, 9818), 'ClusterWrap.cluster', 'ClusterWrap.cluster', ([], {}), '(**cluster_kwargs)\n', (9800, 9818), False, 'import ClusterWrap\n'), ((10057, 10082), 'dask.array.sum', 'da.sum', (['fields_da'], {'axis': '(0)'}), '(fields_da, axis=0)\n', (10063, 10082), True, 'import dask.array as da\n'), ((10502, 10557), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""zstd"""', 'clevel': '(9)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='zstd', clevel=9, shuffle=Blosc.BITSHUFFLE)\n", (10507, 10557), False, 'from numcodecs import Blosc\n'), ((10582, 10702), 'zarr.open', 'zarr.open', (['output', '"""w"""'], {'shape': 'composed.shape', 'chunks': 'composed.chunksize', 'dtype': 'composed.dtype', 'compressor': 'compressor'}), "(output, 'w', shape=composed.shape, chunks=composed.chunksize,\n dtype=composed.dtype, compressor=compressor)\n", (10591, 10702), False, 'import zarr\n'), ((10741, 10776), 'dask.array.to_zarr', 'da.to_zarr', (['composed', 'composed_disk'], {}), '(composed, composed_disk)\n', (10751, 10776), True, 'import dask.array as da\n'), ((1297, 1322), 'dask.array.stack', 'da.stack', (['coords'], {'axis': '(-1)'}), '(coords, axis=-1)\n', (1305, 1322), True, 'import dask.array as da\n'), ((2439, 2470), 'numpy.unravel_index', 'np.unravel_index', (['i', 'block_grid'], {}), '(i, block_grid)\n', (2455, 2470), True, 'import numpy as np\n'), ((2487, 2496), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (2493, 2496), True, 'import numpy as np\n'), ((2864, 2883), 'numpy.array', 'np.array', (['blocksize'], {}), '(blocksize)\n', (2872, 2883), True, 'import numpy as np\n'), ((5930, 6063), 'dask.array.map_blocks', 'da.map_blocks', (['get_origin_and_span', 'transform_da'], {'mov_spacing': 'mov_spacing', 'dtype': 'np.float32', 'new_axis': '[4]', 'chunks': '(1, 1, 1, 2, 3)'}), '(get_origin_and_span, transform_da, mov_spacing=mov_spacing,\n dtype=np.float32, new_axis=[4], chunks=(1, 1, 1, 2, 3))\n', (5943, 6063), True, 'import dask.array as da\n'), ((6259, 6290), 'numpy.round', 'np.round', (['(origins / mov_spacing)'], {}), '(origins / mov_spacing)\n', (6267, 6290), True, 'import numpy as np\n'), ((6314, 6341), 'numpy.ceil', 'np.ceil', (['(span / mov_spacing)'], {}), '(span / mov_spacing)\n', (6321, 6341), True, 'import numpy as np\n'), ((2580, 2595), 'numpy.matmul', 'np.matmul', (['g', 'l'], {}), '(g, l)\n', (2589, 2595), True, 'import numpy as np\n'), ((9958, 9998), 'dask.array.from_array', 'da.from_array', (['f'], {'chunks': '(blocksize + [3])'}), '(f, chunks=blocksize + [3])\n', (9971, 9998), True, 'import dask.array as da\n'), ((4842, 4861), 'numpy.array', 'np.array', (['fix.shape'], {}), '(fix.shape)\n', (4850, 4861), True, 'import numpy as np\n'), ((9681, 9711), 'numpy.array', 'np.array', (['fields[0].shape[:-1]'], {}), '(fields[0].shape[:-1])\n', (9689, 9711), True, 'import numpy as np\n')]