code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
import numpy as np
from simpa.utils import Tags
from simpa.utils.libraries.molecule_library import MolecularComposition
from simpa.utils.libraries.structure_library.StructureBase import GeometricalStructure
class CircularTubularStructure(GeometricalStructure):
"""
Defines a circular tube which is defined by a start and end point as well as a radius. This structure implements
partial volume effects. The tube can be set to adhere to a deformation defined by the
simpa.utils.deformation_manager. The start and end points of the tube will then be shifted along the z-axis
accordingly.
Example usage:
# single_structure_settings initialization
structure = Settings()
structure[Tags.PRIORITY] = 9
structure[Tags.STRUCTURE_START_MM] = [50, 0, 50]
structure[Tags.STRUCTURE_END_MM] = [50, 100, 50]
structure[Tags.STRUCTURE_RADIUS_MM] = 5
structure[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.blood()
structure[Tags.CONSIDER_PARTIAL_VOLUME] = True
structure[Tags.ADHERE_TO_DEFORMATION] = True
structure[Tags.STRUCTURE_TYPE] = Tags.CIRCULAR_TUBULAR_STRUCTURE
"""
def get_params_from_settings(self, single_structure_settings):
params = (np.asarray(single_structure_settings[Tags.STRUCTURE_START_MM]),
np.asarray(single_structure_settings[Tags.STRUCTURE_END_MM]),
np.asarray(single_structure_settings[Tags.STRUCTURE_RADIUS_MM]),
single_structure_settings[Tags.CONSIDER_PARTIAL_VOLUME])
return params
def to_settings(self):
settings = super().to_settings()
settings[Tags.STRUCTURE_START_MM] = self.params[0]
settings[Tags.STRUCTURE_END_MM] = self.params[1]
settings[Tags.STRUCTURE_RADIUS_MM] = self.params[2]
return settings
def get_enclosed_indices(self):
start_mm, end_mm, radius_mm, partial_volume = self.params
start_voxels = start_mm / self.voxel_spacing
end_voxels = end_mm / self.voxel_spacing
radius_voxels = radius_mm / self.voxel_spacing
x, y, z = np.meshgrid(np.arange(self.volume_dimensions_voxels[0]),
np.arange(self.volume_dimensions_voxels[1]),
np.arange(self.volume_dimensions_voxels[2]),
indexing='ij')
x = x + 0.5
y = y + 0.5
z = z + 0.5
if partial_volume:
radius_margin = 0.5
else:
radius_margin = 0.7071
target_vector = np.subtract(np.stack([x, y, z], axis=-1), start_voxels)
if self.do_deformation:
# the deformation functional needs mm as inputs and returns the result in reverse indexing order...
deformation_values_mm = self.deformation_functional_mm(np.arange(self.volume_dimensions_voxels[0], step=1) *
self.voxel_spacing,
np.arange(self.volume_dimensions_voxels[1], step=1) *
self.voxel_spacing).T
deformation_values_mm = deformation_values_mm.reshape(self.volume_dimensions_voxels[0],
self.volume_dimensions_voxels[1], 1, 1)
deformation_values_mm = np.tile(deformation_values_mm, (1, 1, self.volume_dimensions_voxels[2], 3))
target_vector = target_vector + (deformation_values_mm / self.voxel_spacing)
cylinder_vector = np.subtract(end_voxels, start_voxels)
target_radius = np.linalg.norm(target_vector, axis=-1) * np.sin(
np.arccos((np.dot(target_vector, cylinder_vector)) /
(np.linalg.norm(target_vector, axis=-1) * np.linalg.norm(cylinder_vector))))
volume_fractions = np.zeros(self.volume_dimensions_voxels)
filled_mask = target_radius <= radius_voxels - 1 + radius_margin
border_mask = (target_radius > radius_voxels - 1 + radius_margin) & \
(target_radius < radius_voxels + 2 * radius_margin)
volume_fractions[filled_mask] = 1
volume_fractions[border_mask] = 1 - (target_radius - (radius_voxels - radius_margin))[border_mask]
volume_fractions[volume_fractions < 0] = 0
if partial_volume:
mask = filled_mask | border_mask
else:
mask = filled_mask
return mask, volume_fractions[mask]
def define_circular_tubular_structure_settings(tube_start_mm: list,
tube_end_mm: list,
molecular_composition: MolecularComposition,
radius_mm: float = 2,
priority: int = 10,
consider_partial_volume: bool = False,
adhere_to_deformation: bool = False):
"""
TODO
"""
return {
Tags.STRUCTURE_START_MM: tube_start_mm,
Tags.STRUCTURE_END_MM: tube_end_mm,
Tags.STRUCTURE_RADIUS_MM: radius_mm,
Tags.PRIORITY: priority,
Tags.MOLECULE_COMPOSITION: molecular_composition,
Tags.CONSIDER_PARTIAL_VOLUME: consider_partial_volume,
Tags.ADHERE_TO_DEFORMATION: adhere_to_deformation,
Tags.STRUCTURE_TYPE: Tags.CIRCULAR_TUBULAR_STRUCTURE
}
|
[
"numpy.tile",
"numpy.asarray",
"numpy.subtract",
"numpy.stack",
"numpy.zeros",
"numpy.dot",
"numpy.linalg.norm",
"numpy.arange"
] |
[((3772, 3809), 'numpy.subtract', 'np.subtract', (['end_voxels', 'start_voxels'], {}), '(end_voxels, start_voxels)\n', (3783, 3809), True, 'import numpy as np\n'), ((4076, 4115), 'numpy.zeros', 'np.zeros', (['self.volume_dimensions_voxels'], {}), '(self.volume_dimensions_voxels)\n', (4084, 4115), True, 'import numpy as np\n'), ((1402, 1464), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_START_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_START_MM])\n', (1412, 1464), True, 'import numpy as np\n'), ((1484, 1544), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_END_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_END_MM])\n', (1494, 1544), True, 'import numpy as np\n'), ((1564, 1627), 'numpy.asarray', 'np.asarray', (['single_structure_settings[Tags.STRUCTURE_RADIUS_MM]'], {}), '(single_structure_settings[Tags.STRUCTURE_RADIUS_MM])\n', (1574, 1627), True, 'import numpy as np\n'), ((2286, 2329), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[0]'], {}), '(self.volume_dimensions_voxels[0])\n', (2295, 2329), True, 'import numpy as np\n'), ((2361, 2404), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[1]'], {}), '(self.volume_dimensions_voxels[1])\n', (2370, 2404), True, 'import numpy as np\n'), ((2436, 2479), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[2]'], {}), '(self.volume_dimensions_voxels[2])\n', (2445, 2479), True, 'import numpy as np\n'), ((2733, 2761), 'numpy.stack', 'np.stack', (['[x, y, z]'], {'axis': '(-1)'}), '([x, y, z], axis=-1)\n', (2741, 2761), True, 'import numpy as np\n'), ((3581, 3656), 'numpy.tile', 'np.tile', (['deformation_values_mm', '(1, 1, self.volume_dimensions_voxels[2], 3)'], {}), '(deformation_values_mm, (1, 1, self.volume_dimensions_voxels[2], 3))\n', (3588, 3656), True, 'import numpy as np\n'), ((3835, 3873), 'numpy.linalg.norm', 'np.linalg.norm', (['target_vector'], {'axis': '(-1)'}), '(target_vector, axis=-1)\n', (3849, 3873), True, 'import numpy as np\n'), ((2988, 3039), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[0]'], {'step': '(1)'}), '(self.volume_dimensions_voxels[0], step=1)\n', (2997, 3039), True, 'import numpy as np\n'), ((3196, 3247), 'numpy.arange', 'np.arange', (['self.volume_dimensions_voxels[1]'], {'step': '(1)'}), '(self.volume_dimensions_voxels[1], step=1)\n', (3205, 3247), True, 'import numpy as np\n'), ((3907, 3945), 'numpy.dot', 'np.dot', (['target_vector', 'cylinder_vector'], {}), '(target_vector, cylinder_vector)\n', (3913, 3945), True, 'import numpy as np\n'), ((3972, 4010), 'numpy.linalg.norm', 'np.linalg.norm', (['target_vector'], {'axis': '(-1)'}), '(target_vector, axis=-1)\n', (3986, 4010), True, 'import numpy as np\n'), ((4013, 4044), 'numpy.linalg.norm', 'np.linalg.norm', (['cylinder_vector'], {}), '(cylinder_vector)\n', (4027, 4044), True, 'import numpy as np\n')]
|
import os
import numpy as np
import pandas as pd
from scipy import sparse as sp
from typing import Callable, List, Tuple, Dict
from os.path import join
from . import utils, process_dat
from . import SETTINGS_POLIMI as SETTINGS
os.environ['NUMEXPR_MAX_THREADS'] = str(SETTINGS.hyp['cores'])
pd.options.mode.chained_assignment = None # allow assigning to copy of DataFrame slice without warnings
def simulate_batch(initial_user_state: np.ndarray, models: tuple, hyp: dict, stg: dict,
tevmin: float, tevmax: float,
tevmin_train: float, tevmax_train: float, tevmean_train: float,
verbose: int = 0, user_max_lam: np.ndarray = None, user_n_imp: np.ndarray = None,
fix_n_imp: bool = False) -> pd.DataFrame:
"""
Runs simulation given models of members (consumption and visits) and recommenders (impressions).
Idea is to sample "visit potential points" for each user based on an upper bound of intensity
with homogeneous Poisson process, then use rejection sampling to decide the actual visit time points.
@param initial_user_state: (n_users, n_items) csr_matrix start state for each member
@param models: (UserModel, [RecModel], VisitModel) tuple
@param hyp: hyperparameter dict
@param stg: settings dict
@param tevmin: float min time of visits
@param tevmax: float max time of visits
@param tevmin_train: float min time of visits in training data
@param tevmax_train: float max time of visits in training data
@param tevmean_train: float mean time of visits in training data
@param verbose: bool verbose mode
@param user_max_lam: np.array maximum intensity per member
@param user_n_imp: np.array mean number of impressions per member
@param fix_n_imp: if true then take `user_n_imp` fixed impressions per memeber
@return: simulated dataset of impressions
"""
# need local import otherwise multiprocessing will not work (silent error):
from . import sim_models
import tensorflow
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tensorflow.keras.backend.set_floatx('float64')
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
user_model, rec_models, visit_model = models # unpack models
# initialize user_states: list of np.array representing complete history for each user
user_states = initial_user_state.toarray().copy() # tracks current user state for all users
#user_states = initial_user_state.copy() # tracks current user state for all users
# define some constants:
if user_max_lam is None:
user_max_lam = hyp['max_lam'] * np.ones(stg['NU']) # estimate upper bound for all users
n_potential_visits = [np.random.poisson(lam=m * stg['T']) for m in user_max_lam] # num events per user
# create np.array of NU-by-N visit deltas for each user
# (indicate non-visits with nan):
max_n_visits = max(n_potential_visits)
user_potential_visits = np.nan + np.zeros((stg['NU'], max_n_visits)) # stg['INF_TIME'] +
for u, n_points in enumerate(n_potential_visits):
user_potential_visits[u, :n_points] = np.sort(np.random.uniform(low=tevmin, high=tevmax, size=n_points))
# user_potential_visits is now the array indicating global visit time for set of potential visits per user
print('tevmin, tevmax', tevmin, tevmax)
arb_rec_model = rec_models[0]
time_rec = isinstance(arb_rec_model, sim_models.RecModelTime)
if time_rec:
# create time features for each potential visit per member:
T = np.zeros((max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1))
for u in range(stg['NU']):
T[:, u, :] = arb_rec_model.process_time_feature(user_potential_visits[u, :], create_bins=False).toarray()
# randomly draw num of impressions for each user and potential visit
# (todo: refactor this part into separate function)
if user_n_imp is None:
imp_shape = (stg['NU'], max_n_visits)
if fix_n_imp:
user_nimp = stg['lambda_impression']*np.ones(imp_shape)
else:
user_nimp = np.random.poisson(stg['lambda_impression'],
size=imp_shape) # number of impressions at each potential visit
else:
if fix_n_imp:
user_nimp = np.repeat(user_n_imp[:,np.newaxis], max_n_visits, axis=1)
else:
user_nimp = np.array([np.random.poisson(user_n_imp) for _ in range(max_n_visits)]).T
user_nimp = np.minimum(int(stg['NI']/2), np.maximum(1, user_nimp)) # ensure n_impressions per visit 1 <= n_imp <= num items/2.
user_nimp = user_nimp.astype('int64')
iteration = 0
# init simulation, update on every iteration of the main loop:
simdict = {'user_id': np.zeros(0, dtype='int64'),
'time': np.zeros(0),
'action': np.zeros(0, dtype='int64'),
'potential_action': np.zeros(0, dtype='int64'),
'state': [],
'reward': np.zeros(0)}
simulation = pd.DataFrame(simdict)
print('running batch simulation...')
while iteration < max_n_visits:
# process all users in each iteration (all users who have not had final visit).
# decide which users will be potentially visiting in this time block
# in order to prepare features for visit_model prediction:
# evaluate intensity function for all potential visitors, then decide which ones
# are actually visiting with rejection sampling:
pvs, = np.where(~np.isnan(user_potential_visits[:, iteration])) # potential visitors
# prepare feature vector X (one per potentially active user)
if hyp['hyp_study']['constant_rate']:
X = np.zeros(1)
else:
X = sim_models.process_features_static_points(simulation, user_potential_visits[pvs, iteration], pvs, (
stg['NI'], hyp['visit_model_hyp']['window_size'], tevmean_train, tevmin_train, tevmax_train),
init_user_states=initial_user_state)
# update prediction cache for user and rec models
rec_states = np.hstack((user_states, T[iteration, :, :])) if time_rec else user_states
[rec_model.populate_cache(rec_states) for rec_model in rec_models]
user_model.populate_cache(user_states)
if verbose:
print('updated user/rec policy per user.')
print('processed stochastic process features.')
if X.shape[0] > 0:
if hyp['hyp_study']['constant_rate']:
pvs_lam = np.zeros_like(pvs)
accept_pr = np.ones_like(pvs)
else:
mix = hyp['visit_model_hyp']['self_exciting_mixture']
pvs_lam_norm = (1-mix)*visit_model._model.predict(X.toarray()) + mix*visit_model._lambda_e_model.predict(X.toarray()) # predicted lambda for each active user
pvs_lam = pvs_lam_norm * visit_model.time_scale # model predicts over [-1,+1] time, need to spread over
# original range
accept_pr = pvs_lam.ravel() / user_max_lam[pvs]
print_every = 20
if (iteration % print_every) == 0:
print('iteration %i, num. of active users' % iteration, pvs_lam.ravel().shape)
print('pvs_lam', pvs_lam.ravel())
print('max_lam', user_max_lam[pvs])
assert np.all(accept_pr <= 1.0), pvs_lam.ravel().max()
is_visit = np.array(np.random.binomial(1, accept_pr), dtype=np.bool_)
uz_visit = pvs[is_visit] # decide which users are actually visiting
if verbose: print('sampled visiting users.')
# iterate over visiting users to draw recommendations:
for u in uz_visit:
user_state = user_states[u, :].copy() # pull out current user state
rec_state = rec_states[u, :]
n_imp = user_nimp[u, iteration]
rec_prop = SETTINGS.hyp['rec_prop'] # draw rec_id based on global probability
rec_id = np.random.choice(np.arange(len(rec_models), dtype='int16'), p=rec_prop)
# draw recommendation for user, depending on which rec_id to use:
az = rec_models[rec_id].select(rec_state, n_imp, hyp, stg)
# select count depends on whether using Bernoulli or Categorical model:
select_count = az if isinstance(user_model, sim_models.UserModelBinary) else hyp['user_select_count']
# draw consumed title for user (i.e. title they would have consumed if they had been recommended it)
cz = user_model.select(user_state, select_count, hyp, stg)
assert n_imp > 0, n_imp
simdict, user_state = calculate_reward_by_overlap(user_state, u, n_imp, az, cz, user_potential_visits,
iteration, rec_id, stg)
# update user state
user_states[u, :] = user_state # update current user state for user u
try:
new_sim = pd.DataFrame(simdict)
except ValueError:
print([len(x) for x in [simdict['user_id'], simdict['state'], simdict['action'], simdict['potential_action'], simdict['time']]])
raise ValueError()
simulation = simulation.append(new_sim, ignore_index=True, sort=False)
iteration += 1
return simulation
def calculate_reward_by_overlap(user_state: np.ndarray, u: int, n_imp: int, az: np.ndarray, cz: np.ndarray,
user_potential_visits: np.ndarray, iteration: int, rec_id: int, stg: Dict) \
-> Tuple[Dict, np.ndarray]:
"""
Calculates reward by inspecting actions taken by member and recommender and looking for any overlap.
@param user_state: np.array(n_members, n_items) representing state of each member
@param u: int, member id
@param n_imp: int, number of impressions
@param az: np.array of actions taken by recommender
@param cz: np.array of (potential) actions taken by member
@param user_potential_visits: np.array(n_users, n_iterations) of time of visit for each member
@param iteration: int, iteration id
@param rec_id: int, recommender id
@param stg: dict of settings
@return: dictionary representing new rows for the simulation, updated user state
"""
A = np.bincount(az, minlength=stg['NI'])
C = np.bincount(cz, minlength=stg['NI'])
R = A * C
streamed, = np.where(R > 0)
# build list of streamed and non-streamed actions
az_success = list(streamed)
cz_success = list(streamed)
az_fail = list(set(az) - set(az_success))
cz_fail = list(set(cz) - set(cz_success))
len_rz = min(1, len(streamed))
simdict = {'user_id': np.array([u] * n_imp, dtype='int64'), # np.repeat(u,n_imp,dtype='int64'),
'time': [user_potential_visits[u, iteration]] * n_imp, # np.repeat(global_t,n_imp),
'action': az_success + az_fail,
'potential_action': [-1] * n_imp, # cz_success+cz_fail,
'state': [utils.bow(user_state)] * n_imp,
'reward': [1] * len_rz + [0] * (n_imp - len_rz),
'rec_id': rec_id}
user_state[np.random.permutation(streamed)[:1]] = 1
return simdict, user_state
def load_models(user_model_path: str, rec_model_paths: str, visit_model_path: str, hyp: Dict, stg: Dict,
rec_type: str = 'static', user_binary: bool = False) -> Tuple:
# load models from disk
from . import sim_models
# load user model:
if user_binary:
user_model = sim_models.UserModelBinary(stg['NI'], stg['NI'], hyp['user_model_hyp'])
else:
user_model = sim_models.UserModel(stg['NI'], stg['NI'], hyp['user_model_hyp'])
user_model.load(user_model_path)
# load recommender models (multiple models because we consider multiple recommenders in any single simulation):
ceil_t = np.ceil(stg['T']).astype('int')
rec_models = []
for rec_model_path in rec_model_paths:
if type(rec_model_path) == str:
if rec_type == 'static':
rec_model = sim_models.RecModel(stg['NI'], stg['NI'], hyp['rec_model_hyp'])
rec_model.load(rec_model_path)
elif rec_type == 'time':
rec_model = sim_models.RecModelTime(stg['NI'], stg['NI'], hyp['rec_model_hyp'], ceil_t)
rec_model.load(rec_model_path)
elif rec_type == 'nmf':
print('nmf model with hyp =',SETTINGS.hyp['hyp_study'])
rec_model = sim_models.NMFRec(stg['NI'], SETTINGS.hyp['hyp_study'])
if len(rec_model_path)>0:
nmf_rec_model_dat = pd.read_csv(rec_model_path) # path is to history of data not model here
rec_model.fit(nmf_rec_model_dat, stg['NI'])
else:
raise Exception('rec model type unrecognized: ' + rec_type)
else:
rec_model = rec_model_path
rec_models.append(rec_model)
# load user visit model:
visit_model = sim_models.VisitModel(stg['NI'], stg['NU'], hyp['visit_model_hyp'])
visit_model.load(visit_model_path, None)
return (user_model, rec_models, visit_model)
def batch_sim(uids: np.ndarray, kwargs: Dict) -> pd.DataFrame:
print('batch sim on uids', uids.min(), 'to', uids.max(), '(inclusive)')
stg_local = kwargs['stg'].copy()
uid_min, uid_max = uids.min(), uids.max()+1
stg_local['NU'] = uid_max - uid_min
stg_local['T'] = kwargs['tevmax']
init_states = kwargs['S_init'][uid_min:uid_max, :]
model_paths = kwargs['model_paths']
if 'hyp' in kwargs:
local_hyp = kwargs['hyp']
else:
local_hyp = SETTINGS.hyp
if kwargs['user_max_lam'] is not None:
user_max_lam = kwargs['user_max_lam'][uid_min:uid_max]
else:
user_max_lam = None
user_path, rec_path, visit_path = model_paths['user_model'], model_paths['rec_model'], model_paths['visit_model']
models = load_models(user_path, rec_path, visit_path, local_hyp, stg_local, rec_type='nmf', user_binary=True)
s = simulate_batch(init_states, models, local_hyp, stg_local, kwargs['tevmin'],
kwargs['tevmax'], kwargs['tevmin_train'], kwargs['tevmax_train'], kwargs['tevmean_train'],
user_max_lam=user_max_lam, user_n_imp=kwargs['empirical_mean_imp_per_visit'][uid_min:uid_max],
fix_n_imp=kwargs['fix_n_imp'] if 'fix_n_imp' in kwargs else False)
# adjust uid to avoid clash with other child processes:
s.user_id = s.user_id + uid_min
return s
def prepare_sim(simulation: pd.DataFrame, stg: Dict, base_path: str) -> Dict:
# find initial states for all users:
# please note: groupby preserves order when sort=False https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
first_imps = simulation.sort_values(['time']).groupby('user_id',sort=False).first().sort_values(['user_id'])
user_ids = np.sort(first_imps.index)
# initial_user_state is np.array NU-x-NI int64
S_init = utils.inv_bow_all(first_imps.state.values, stg['NI'], dense=False).tocsr()
# update num. users to reflect only users with streams in observation:
stg_local = stg.copy()
n_users = S_init.shape[0]
np.random.seed(0)
uids = np.random.choice(np.arange(stg['NU'],dtype='int32'),size=n_users,replace=False)
tevmean, tevmin, tevmax = process_dat.calc_tev(simulation)
# calculate average number of visits per user (defined as user_id-by-time group of impressions):
sg = simulation.groupby(['user_id','time'])
empirical_n_visits = sg.count().groupby('user_id')['action'].count().values
# calculate average number of impressions per visit per user
imp_series = sg['action'].count().groupby('user_id').mean()
assert np.all(imp_series.index == user_ids) # make sure user ids match up
return {'S_init': S_init,
'stg': stg,
'tevmax': tevmax,
'tevmin': tevmin,
'tevmean': tevmean,
'user_max_lam': None,
'empirical_mean_imp_per_visit': imp_series.values,
'base_path': base_path
}
def prepare_sim_contentwise(simulation: pd.DataFrame, stg: Dict, hyp: Dict, user_lam: np.ndarray, base_path: str) -> Dict:
# find initial states for all users:
# please note: groupby preserves order when sort=False https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html
first_imps = simulation.sort_values(['time']).groupby('user_id',sort=False).first().sort_values(['user_id'])
user_ids = np.sort(first_imps.index)
# initial_user_state is np.array NU-x-NI int64
S_init = utils.inv_bow_all(first_imps.state.values, stg['NI'], dense=False).tocsr()
np.random.seed(0)
tevmean, tevmin, tevmax = process_dat.calc_tev(simulation)
# calculate average number of visits per user (defined as user_id-by-time group of impressions):
sg = simulation.groupby(['user_id','round_time'])
empirical_n_visits = sg.first().groupby('user_id').action.count().values
# calculate average number of impressions per visit per user
imp_series = sg['action'].count().groupby('user_id').mean()
assert np.all(imp_series.index == user_ids) # make sure user ids match up
if not(hyp['constant_rate']): user_lam = None
return {'S_init': S_init,
'stg': stg,
'tevmax': tevmax,
'tevmin': tevmin,
'tevmean': tevmean,
'user_max_lam': user_lam,
'empirical_mean_imp_per_visit': imp_series.values,
'base_path': base_path
}
def parsim(rec_model_config: List, **kwargs):
user_set = np.arange(kwargs['S_init'].shape[0], dtype='int64')
test_id = SETTINGS.simulation_components['ab_test_id']
# add model_paths to kwargs and pass through to batch_sim:
kwargs['model_paths'] = {'user_model': join(kwargs['base_path'], SETTINGS.filepaths['user_model_test']) % test_id,
'rec_model': [join(kwargs['base_path'], SETTINGS.filepaths['rec_model_t_test']) % (test_id, cell_id, rec_id) for
test_id, cell_id, rec_id in rec_model_config],
'visit_model': join(kwargs['base_path'], SETTINGS.filepaths['visit_model_test-%s' % test_id] + '.big')
}
return utils.parallelize_fnc(batch_sim, user_set, kwargs, int(SETTINGS.hyp['cores']/2))
|
[
"pandas.read_csv",
"numpy.hstack",
"numpy.array",
"numpy.arange",
"numpy.random.binomial",
"numpy.repeat",
"numpy.random.poisson",
"numpy.where",
"numpy.sort",
"numpy.random.seed",
"pandas.DataFrame",
"numpy.maximum",
"numpy.random.permutation",
"numpy.ceil",
"numpy.ones",
"tensorflow.keras.backend.set_floatx",
"numpy.isnan",
"numpy.bincount",
"warnings.filterwarnings",
"numpy.ones_like",
"os.path.join",
"numpy.zeros",
"numpy.random.uniform",
"numpy.all",
"numpy.zeros_like"
] |
[((2162, 2208), 'tensorflow.keras.backend.set_floatx', 'tensorflow.keras.backend.set_floatx', (['"""float64"""'], {}), "('float64')\n", (2197, 2208), False, 'import tensorflow\n'), ((2233, 2295), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (2256, 2295), False, 'import warnings\n'), ((5154, 5175), 'pandas.DataFrame', 'pd.DataFrame', (['simdict'], {}), '(simdict)\n', (5166, 5175), True, 'import pandas as pd\n'), ((10694, 10730), 'numpy.bincount', 'np.bincount', (['az'], {'minlength': "stg['NI']"}), "(az, minlength=stg['NI'])\n", (10705, 10730), True, 'import numpy as np\n'), ((10739, 10775), 'numpy.bincount', 'np.bincount', (['cz'], {'minlength': "stg['NI']"}), "(cz, minlength=stg['NI'])\n", (10750, 10775), True, 'import numpy as np\n'), ((10806, 10821), 'numpy.where', 'np.where', (['(R > 0)'], {}), '(R > 0)\n', (10814, 10821), True, 'import numpy as np\n'), ((15382, 15407), 'numpy.sort', 'np.sort', (['first_imps.index'], {}), '(first_imps.index)\n', (15389, 15407), True, 'import numpy as np\n'), ((15688, 15705), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (15702, 15705), True, 'import numpy as np\n'), ((16239, 16275), 'numpy.all', 'np.all', (['(imp_series.index == user_ids)'], {}), '(imp_series.index == user_ids)\n', (16245, 16275), True, 'import numpy as np\n'), ((17035, 17060), 'numpy.sort', 'np.sort', (['first_imps.index'], {}), '(first_imps.index)\n', (17042, 17060), True, 'import numpy as np\n'), ((17209, 17226), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (17223, 17226), True, 'import numpy as np\n'), ((17672, 17708), 'numpy.all', 'np.all', (['(imp_series.index == user_ids)'], {}), '(imp_series.index == user_ids)\n', (17678, 17708), True, 'import numpy as np\n'), ((18152, 18203), 'numpy.arange', 'np.arange', (["kwargs['S_init'].shape[0]"], {'dtype': '"""int64"""'}), "(kwargs['S_init'].shape[0], dtype='int64')\n", (18161, 18203), True, 'import numpy as np\n'), ((2823, 2858), 'numpy.random.poisson', 'np.random.poisson', ([], {'lam': "(m * stg['T'])"}), "(lam=m * stg['T'])\n", (2840, 2858), True, 'import numpy as np\n'), ((3084, 3119), 'numpy.zeros', 'np.zeros', (["(stg['NU'], max_n_visits)"], {}), "((stg['NU'], max_n_visits))\n", (3092, 3119), True, 'import numpy as np\n'), ((3675, 3749), 'numpy.zeros', 'np.zeros', (["(max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1)"], {}), "((max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1))\n", (3683, 3749), True, 'import numpy as np\n'), ((4651, 4675), 'numpy.maximum', 'np.maximum', (['(1)', 'user_nimp'], {}), '(1, user_nimp)\n', (4661, 4675), True, 'import numpy as np\n'), ((4891, 4917), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (4899, 4917), True, 'import numpy as np\n'), ((4942, 4953), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (4950, 4953), True, 'import numpy as np\n'), ((4980, 5006), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (4988, 5006), True, 'import numpy as np\n'), ((5043, 5069), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (5051, 5069), True, 'import numpy as np\n'), ((5124, 5135), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (5132, 5135), True, 'import numpy as np\n'), ((11093, 11129), 'numpy.array', 'np.array', (['([u] * n_imp)'], {'dtype': '"""int64"""'}), "([u] * n_imp, dtype='int64')\n", (11101, 11129), True, 'import numpy as np\n'), ((15734, 15769), 'numpy.arange', 'np.arange', (["stg['NU']"], {'dtype': '"""int32"""'}), "(stg['NU'], dtype='int32')\n", (15743, 15769), True, 'import numpy as np\n'), ((18721, 18812), 'os.path.join', 'join', (["kwargs['base_path']", "(SETTINGS.filepaths['visit_model_test-%s' % test_id] + '.big')"], {}), "(kwargs['base_path'], SETTINGS.filepaths['visit_model_test-%s' %\n test_id] + '.big')\n", (18725, 18812), False, 'from os.path import join\n'), ((2740, 2758), 'numpy.ones', 'np.ones', (["stg['NU']"], {}), "(stg['NU'])\n", (2747, 2758), True, 'import numpy as np\n'), ((3254, 3311), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'tevmin', 'high': 'tevmax', 'size': 'n_points'}), '(low=tevmin, high=tevmax, size=n_points)\n', (3271, 3311), True, 'import numpy as np\n'), ((4234, 4293), 'numpy.random.poisson', 'np.random.poisson', (["stg['lambda_impression']"], {'size': 'imp_shape'}), "(stg['lambda_impression'], size=imp_shape)\n", (4251, 4293), True, 'import numpy as np\n'), ((4437, 4495), 'numpy.repeat', 'np.repeat', (['user_n_imp[:, np.newaxis]', 'max_n_visits'], {'axis': '(1)'}), '(user_n_imp[:, np.newaxis], max_n_visits, axis=1)\n', (4446, 4495), True, 'import numpy as np\n'), ((5858, 5869), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (5866, 5869), True, 'import numpy as np\n'), ((6285, 6329), 'numpy.hstack', 'np.hstack', (['(user_states, T[iteration, :, :])'], {}), '((user_states, T[iteration, :, :]))\n', (6294, 6329), True, 'import numpy as np\n'), ((7574, 7598), 'numpy.all', 'np.all', (['(accept_pr <= 1.0)'], {}), '(accept_pr <= 1.0)\n', (7580, 7598), True, 'import numpy as np\n'), ((11556, 11587), 'numpy.random.permutation', 'np.random.permutation', (['streamed'], {}), '(streamed)\n', (11577, 11587), True, 'import numpy as np\n'), ((12272, 12289), 'numpy.ceil', 'np.ceil', (["stg['T']"], {}), "(stg['T'])\n", (12279, 12289), True, 'import numpy as np\n'), ((18369, 18433), 'os.path.join', 'join', (["kwargs['base_path']", "SETTINGS.filepaths['user_model_test']"], {}), "(kwargs['base_path'], SETTINGS.filepaths['user_model_test'])\n", (18373, 18433), False, 'from os.path import join\n'), ((4177, 4195), 'numpy.ones', 'np.ones', (['imp_shape'], {}), '(imp_shape)\n', (4184, 4195), True, 'import numpy as np\n'), ((5658, 5703), 'numpy.isnan', 'np.isnan', (['user_potential_visits[:, iteration]'], {}), '(user_potential_visits[:, iteration])\n', (5666, 5703), True, 'import numpy as np\n'), ((6720, 6738), 'numpy.zeros_like', 'np.zeros_like', (['pvs'], {}), '(pvs)\n', (6733, 6738), True, 'import numpy as np\n'), ((6767, 6784), 'numpy.ones_like', 'np.ones_like', (['pvs'], {}), '(pvs)\n', (6779, 6784), True, 'import numpy as np\n'), ((7654, 7686), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'accept_pr'], {}), '(1, accept_pr)\n', (7672, 7686), True, 'import numpy as np\n'), ((18488, 18553), 'os.path.join', 'join', (["kwargs['base_path']", "SETTINGS.filepaths['rec_model_t_test']"], {}), "(kwargs['base_path'], SETTINGS.filepaths['rec_model_t_test'])\n", (18492, 18553), False, 'from os.path import join\n'), ((9290, 9311), 'pandas.DataFrame', 'pd.DataFrame', (['simdict'], {}), '(simdict)\n', (9302, 9311), True, 'import pandas as pd\n'), ((4543, 4572), 'numpy.random.poisson', 'np.random.poisson', (['user_n_imp'], {}), '(user_n_imp)\n', (4560, 4572), True, 'import numpy as np\n'), ((13061, 13088), 'pandas.read_csv', 'pd.read_csv', (['rec_model_path'], {}), '(rec_model_path)\n', (13072, 13088), True, 'import pandas as pd\n')]
|
from . import DATA_DIR
import pandas as pd
import xarray as xr
import numpy as np
from pathlib import Path
import csv
REMIND_ELEC_MARKETS = (DATA_DIR / "remind_electricity_markets.csv")
REMIND_ELEC_EFFICIENCIES = (DATA_DIR / "remind_electricity_efficiencies.csv")
REMIND_ELEC_EMISSIONS = (DATA_DIR / "remind_electricity_emissions.csv")
GAINS_TO_REMIND_FILEPATH = (DATA_DIR / "GAINStoREMINDtechmap.csv")
class RemindDataCollection:
"""
Class that extracts data from REMIND output files.
:ivar scenario: name of a Remind scenario
:vartype scenario: str
"""
def __init__(self, scenario, year, filepath_remind_files):
self.scenario = scenario
self.year = year
self.filepath_remind_files = filepath_remind_files
self.data = self.get_remind_data()
self.gains_data = self.get_gains_data()
self.electricity_market_labels = self.get_remind_electricity_market_labels()
self.electricity_efficiency_labels = (
self.get_remind_electricity_efficiency_labels()
)
self.electricity_emission_labels = self.get_remind_electricity_emission_labels()
self.rev_electricity_market_labels = self.get_rev_electricity_market_labels()
self.rev_electricity_efficiency_labels = (
self.get_rev_electricity_efficiency_labels()
)
self.electricity_markets = self.get_remind_electricity_markets()
self.electricity_efficiencies = self.get_remind_electricity_efficiencies()
self.electricity_emissions = self.get_remind_electricity_emissions()
def get_remind_electricity_emission_labels(self):
"""
Loads a csv file into a dictionary. This dictionary contains labels of electricity emissions
in Remind.
:return: dictionary that contains emission names equivalence
:rtype: dict
"""
with open(REMIND_ELEC_EMISSIONS) as f:
return dict(filter(None, csv.reader(f, delimiter=";")))
def get_remind_electricity_market_labels(self):
"""
Loads a csv file into a dictionary. This dictionary contains labels of electricity markets
in Remind.
:return: dictionary that contains market names equivalence
:rtype: dict
"""
with open(REMIND_ELEC_MARKETS) as f:
return dict(filter(None, csv.reader(f, delimiter=";")))
def get_remind_electricity_efficiency_labels(self):
"""
Loads a csv file into a dictionary. This dictionary contains labels of electricity technologies efficiency
in Remind.
:return: dictionary that contains market names equivalence
:rtype: dict
"""
with open(REMIND_ELEC_EFFICIENCIES) as f:
return dict(filter(None, csv.reader(f, delimiter=";")))
def get_rev_electricity_market_labels(self):
return {v: k for k, v in self.electricity_market_labels.items()}
def get_rev_electricity_efficiency_labels(self):
return {v: k for k, v in self.electricity_efficiency_labels.items()}
def get_remind_data(self):
"""
Read the REMIND csv result file and return an `xarray` with dimensions:
* region
* variable
* year
:return: an multi-dimensional array with Remind data
:rtype: xarray.core.dataarray.DataArray
"""
filename = self.scenario + ".mif"
filepath = Path(self.filepath_remind_files) / filename
df = pd.read_csv(
filepath, sep=";", index_col=["Region", "Variable", "Unit"]
).drop(columns=["Model", "Scenario", "Unnamed: 24"])
df.columns = df.columns.astype(int)
# Filter the dataframe
df = df.loc[
(df.index.get_level_values("Variable").str.contains("SE"))
| (df.index.get_level_values("Variable").str.contains("Tech"))
]
variables = df.index.get_level_values("Variable").unique()
regions = df.index.get_level_values("Region").unique()
years = df.columns
array = xr.DataArray(
np.zeros((len(variables), len(regions), len(years), 1)),
coords=[variables, regions, years, np.arange(1)],
dims=["variable", "region", "year", "value"],
)
for r in regions:
val = df.loc[(df.index.get_level_values("Region") == r), :]
array.loc[dict(region=r, value=0)] = val
return array
def get_gains_data(self):
"""
Read the GAINS emissions csv file and return an `xarray` with dimensions:
* region
* pollutant
* sector
* year
:return: an multi-dimensional array with GAINS emissions data
:rtype: xarray.core.dataarray.DataArray
"""
filename = "GAINS emission factors.csv"
filepath = Path(self.filepath_remind_files) / filename
gains_emi = pd.read_csv(
filepath,
skiprows=4,
names=["year", "region", "GAINS", "pollutant", "scenario", "factor"],
)
gains_emi["unit"] = "Mt/TWa"
gains_emi = gains_emi[gains_emi.scenario == "SSP2"]
sector_mapping = pd.read_csv(GAINS_TO_REMIND_FILEPATH).drop(
["noef", "elasticity"], axis=1
)
gains_emi = (
gains_emi.join(sector_mapping.set_index("GAINS"), on="GAINS")
.dropna()
.drop(["scenario", "REMIND"], axis=1)
.pivot_table(
index=["region", "GAINS", "pollutant", "unit"],
values="factor",
columns="year",
)
)
regions = gains_emi.index.get_level_values("region").unique()
years = gains_emi.columns.values
pollutants = gains_emi.index.get_level_values("pollutant").unique()
sectors = gains_emi.index.get_level_values("GAINS").unique()
array = xr.DataArray(
np.zeros((len(pollutants), len(sectors), len(regions), len(years), 1)),
coords=[pollutants, sectors, regions, years, np.arange(1)],
dims=["pollutant", "sector", "region", "year", "value"],
)
for r in regions:
for s in sectors:
val = gains_emi.loc[
(gains_emi.index.get_level_values("region") == r)
& (gains_emi.index.get_level_values("GAINS") == s),
:,
]
array.loc[dict(region=r, sector=s, value=0)] = val
return array / 8760 # per TWha --> per TWh
def get_remind_electricity_markets(self, drop_hydrogen=True):
"""
This method retrieves the market share for each electricity-producing technology, for a specified year,
for each region provided by REMIND.
Electricity production from hydrogen can be removed from the mix (unless specified, it is removed).
:param drop_hydrogen: removes hydrogen from the region-specific electricity mix if `True`.
:type drop_hydrogen: bool
:return: an multi-dimensional array with electricity technologies market share for a given year, for all regions.
:rtype: xarray.core.dataarray.DataArray
"""
# If hydrogen is not to be considered, it is removed from the technologies labels list
if drop_hydrogen:
list_technologies = [
l
for l in list(self.electricity_market_labels.values())
if "Hydrogen" not in l
]
else:
list_technologies = list(self.electricity_market_labels.values())
# If the year specified is not contained within the range of years given by REMIND
if (
self.year < self.data.year.values.min()
or self.year > self.data.year.values.max()
):
raise KeyError("year not valid, must be between 2005 and 2150")
# Otherwise, if the year specified corresponds exactly to a year given by REMIND
elif self.year in self.data.coords["year"]:
# The contribution of each technology, for a specified year, for a specified region is normalized to 1.
return self.data.loc[list_technologies, :, self.year] / self.data.loc[
list_technologies, :, self.year
].groupby("region").sum(axis=0)
# Finally, if the specified year falls in between two periods provided by REMIND
else:
# Interpolation between two periods
data_to_interp_from = self.data.loc[
list_technologies, :, :
] / self.data.loc[list_technologies, :, :].groupby("region").sum(axis=0)
return data_to_interp_from.interp(year=self.year)
def get_remind_electricity_efficiencies(self, drop_hydrogen=True):
"""
This method retrieves efficiency values for electricity-producing technology, for a specified year,
for each region provided by REMIND.
Electricity production from hydrogen can be removed from the mix (unless specified, it is removed).
:param drop_hydrogen: removes hydrogen from the region-specific electricity mix if `True`.
:type drop_hydrogen: bool
:return: an multi-dimensional array with electricity technologies market share for a given year, for all regions.
:rtype: xarray.core.dataarray.DataArray
"""
# If hydrogen is not to be considered, it is removed from the technologies labels list
if drop_hydrogen:
list_technologies = [
l
for l in list(self.electricity_efficiency_labels.values())
if "Hydrogen" not in l
]
else:
list_technologies = list(self.electricity_efficiency_labels.values())
# If the year specified is not contained within the range of years given by REMIND
if (
self.year < self.data.year.values.min()
or self.year > self.data.year.values.max()
):
raise KeyError("year not valid, must be between 2005 and 2150")
# Otherwise, if the year specified corresponds exactly to a year given by REMIND
elif self.year in self.data.coords["year"]:
# The contribution of each technologies, for a specified year, for a specified region is normalized to 1.
return (
self.data.loc[list_technologies, :, self.year] / 100
) # Percentage to ratio
# Finally, if the specified year falls in between two periods provided by REMIND
else:
# Interpolation between two periods
data_to_interp_from = self.data.loc[list_technologies, :, :]
return (
data_to_interp_from.interp(year=self.year) / 100
) # Percentage to ratio
def get_remind_electricity_emissions(self):
"""
This method retrieves emission values for electricity-producing technology, for a specified year,
for each region provided by REMIND.
:return: an multi-dimensional array with emissions for different technologies for a given year, for all regions.
:rtype: xarray.core.dataarray.DataArray
"""
# If the year specified is not contained within the range of years given by REMIND
if (
self.year < self.gains_data.year.values.min()
or self.year > self.gains_data.year.values.max()
):
raise KeyError("year not valid, must be between 2005 and 2150")
# Otherwise, if the year specified corresponds exactly to a year given by REMIND
elif self.year in self.gains_data.coords["year"]:
# The contribution of each technologies, for a specified year, for a specified region is normalized to 1.
return self.gains_data.loc[dict(year=self.year, value=0)]
# Finally, if the specified year falls in between two periods provided by REMIND
else:
# Interpolation between two periods
return self.gains_data.loc[dict(value=0)].interp(year=self.year)
|
[
"csv.reader",
"numpy.arange",
"pandas.read_csv",
"pathlib.Path"
] |
[((4893, 5000), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'skiprows': '(4)', 'names': "['year', 'region', 'GAINS', 'pollutant', 'scenario', 'factor']"}), "(filepath, skiprows=4, names=['year', 'region', 'GAINS',\n 'pollutant', 'scenario', 'factor'])\n", (4904, 5000), True, 'import pandas as pd\n'), ((3419, 3451), 'pathlib.Path', 'Path', (['self.filepath_remind_files'], {}), '(self.filepath_remind_files)\n', (3423, 3451), False, 'from pathlib import Path\n'), ((4828, 4860), 'pathlib.Path', 'Path', (['self.filepath_remind_files'], {}), '(self.filepath_remind_files)\n', (4832, 4860), False, 'from pathlib import Path\n'), ((3476, 3548), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'sep': '""";"""', 'index_col': "['Region', 'Variable', 'Unit']"}), "(filepath, sep=';', index_col=['Region', 'Variable', 'Unit'])\n", (3487, 3548), True, 'import pandas as pd\n'), ((5167, 5204), 'pandas.read_csv', 'pd.read_csv', (['GAINS_TO_REMIND_FILEPATH'], {}), '(GAINS_TO_REMIND_FILEPATH)\n', (5178, 5204), True, 'import pandas as pd\n'), ((1954, 1982), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (1964, 1982), False, 'import csv\n'), ((2351, 2379), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (2361, 2379), False, 'import csv\n'), ((2773, 2801), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (2783, 2801), False, 'import csv\n'), ((4179, 4191), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (4188, 4191), True, 'import numpy as np\n'), ((6041, 6053), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (6050, 6053), True, 'import numpy as np\n')]
|
import pickle
import torch
import numpy as np
from attention import make_model
SRC_STOI = None
TARGET_ITOS = None
TRG_EOS_TOKEN = None
TRG_SOS_TOKEN = None
def load_metadata(meta_path):
global SRC_STOI, TARGET_ITOS, TRG_EOS_TOKEN, TRG_SOS_TOKEN
with open(meta_path, 'rb') as f:
metadata = pickle.load(f)
SRC_STOI = metadata['src_stoi']
TARGET_ITOS = metadata['target_itos']
TRG_EOS_TOKEN= metadata['trg_eos_index']
TRG_SOS_TOKEN = metadata['trg_sos_index']
def greedy_decode(model, src, src_mask, src_lengths, max_len=100, sos_index=1, eos_index=None):
"""Greedily decode a sentence."""
with torch.no_grad():
encoder_hidden, encoder_final = model.encode(src, src_mask, src_lengths)
prev_y = torch.ones(1, 1).fill_(sos_index).type_as(src)
trg_mask = torch.ones_like(prev_y)
output = []
hidden = None
for i in range(max_len):
with torch.no_grad():
out, hidden, pre_output = model.decode(
encoder_hidden, encoder_final, src_mask,
prev_y, trg_mask, hidden)
# we predict from the pre-output layer, which is
# a combination of Decoder state, prev emb, and context
prob = model.generator(pre_output[:, -1])
_, next_word = torch.max(prob, dim=1)
next_word = next_word.data.item()
output.append(next_word)
prev_y = torch.ones(1, 1).type_as(src).fill_(next_word)
output = np.array(output)
# cut off everything starting from </s>
# (only when eos_index provided)
if eos_index is not None:
first_eos = np.where(output==eos_index)[0]
if len(first_eos) > 0:
output = output[:first_eos[0]]
return output
def lookup_words(x, vocab=None):
if vocab is not None:
x = [vocab[i] for i in x]
return [str(t) for t in x]
def inference_logic(src, model):
print('inference logic')
hypotheses = []
src_lengths = [len(src)]
src_index = []
for i in src:
src_index.append(SRC_STOI[i])
src = torch.LongTensor(src_index)
src = src.unsqueeze(0)
src_mask = torch.ones(src_lengths) > 0
src_lengths = torch.LongTensor(src_lengths)
pred = greedy_decode(
model,
src,
src_mask,
src_lengths,
max_len=25,
sos_index=TRG_SOS_TOKEN,
eos_index=TRG_EOS_TOKEN,
)
hypotheses.append(pred)
return hypotheses
def translate_sentence(german_sentence, weights_path, metadata_path):
# Load model metadata
print('loading metadata')
load_metadata(metadata_path)
# Load model
global SRC_STOI, TARGET_ITOS
print('loading model')
model = make_model(weights_path, len(SRC_STOI), len(TARGET_ITOS))
german_sentence = german_sentence.split()
hypotheses = inference_logic(german_sentence, model)
hypotheses = [lookup_words(x, TARGET_ITOS) for x in hypotheses]
hypotheses = [" ".join(x) for x in hypotheses]
return hypotheses[0]
|
[
"torch.ones_like",
"numpy.where",
"torch.LongTensor",
"torch.max",
"pickle.load",
"numpy.array",
"torch.no_grad",
"torch.ones"
] |
[((1476, 1492), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (1484, 1492), True, 'import numpy as np\n'), ((2095, 2122), 'torch.LongTensor', 'torch.LongTensor', (['src_index'], {}), '(src_index)\n', (2111, 2122), False, 'import torch\n'), ((2212, 2241), 'torch.LongTensor', 'torch.LongTensor', (['src_lengths'], {}), '(src_lengths)\n', (2228, 2241), False, 'import torch\n'), ((311, 325), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (322, 325), False, 'import pickle\n'), ((641, 656), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (654, 656), False, 'import torch\n'), ((822, 845), 'torch.ones_like', 'torch.ones_like', (['prev_y'], {}), '(prev_y)\n', (837, 845), False, 'import torch\n'), ((1296, 1318), 'torch.max', 'torch.max', (['prob'], {'dim': '(1)'}), '(prob, dim=1)\n', (1305, 1318), False, 'import torch\n'), ((2166, 2189), 'torch.ones', 'torch.ones', (['src_lengths'], {}), '(src_lengths)\n', (2176, 2189), False, 'import torch\n'), ((924, 939), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (937, 939), False, 'import torch\n'), ((1630, 1659), 'numpy.where', 'np.where', (['(output == eos_index)'], {}), '(output == eos_index)\n', (1638, 1659), True, 'import numpy as np\n'), ((756, 772), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (766, 772), False, 'import torch\n'), ((1411, 1427), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (1421, 1427), False, 'import torch\n')]
|
import torch.utils.data as data
import os
import numpy as np
import cv2
#/mnt/lustre/share/dingmingyu/new_list_lane.txt
class MyDataset(data.Dataset):
def __init__(self, file, dir_path, new_width, new_height, label_width, label_height):
imgs = []
fw = open(file, 'r')
lines = fw.readlines()
for line in lines:
words = line.strip().split()
imgs.append((words[0], words[1]))
self.imgs = imgs
self.dir_path = dir_path
self.height = new_height
self.width = new_width
self.label_height = label_height
self.label_width = label_width
def __getitem__(self, index):
path, label = self.imgs[index]
path = os.path.join(self.dir_path, path)
img = cv2.imread(path).astype(np.float32)
img = img[:,:,:3]
img = cv2.resize(img, (self.width, self.height))
img -= [104, 117, 123]
img = img.transpose(2, 0, 1)
gt = cv2.imread(label,-1)
gt = cv2.resize(gt, (self.label_width, self.label_height), interpolation = cv2.INTER_NEAREST)
if len(gt.shape) == 3:
gt = gt[:,:,0]
gt_num_list = list(np.unique(gt))
gt_num_list.remove(0)
target_ins = np.zeros((4, gt.shape[0],gt.shape[1])).astype('uint8')
for index, ins in enumerate(gt_num_list):
target_ins[index,:,:] += (gt==ins)
return img, target_ins, len(gt_num_list)
def __len__(self):
return len(self.imgs)
|
[
"numpy.unique",
"os.path.join",
"numpy.zeros",
"cv2.resize",
"cv2.imread"
] |
[((725, 758), 'os.path.join', 'os.path.join', (['self.dir_path', 'path'], {}), '(self.dir_path, path)\n', (737, 758), False, 'import os\n'), ((849, 891), 'cv2.resize', 'cv2.resize', (['img', '(self.width, self.height)'], {}), '(img, (self.width, self.height))\n', (859, 891), False, 'import cv2\n'), ((973, 994), 'cv2.imread', 'cv2.imread', (['label', '(-1)'], {}), '(label, -1)\n', (983, 994), False, 'import cv2\n'), ((1007, 1098), 'cv2.resize', 'cv2.resize', (['gt', '(self.label_width, self.label_height)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(gt, (self.label_width, self.label_height), interpolation=cv2.\n INTER_NEAREST)\n', (1017, 1098), False, 'import cv2\n'), ((1184, 1197), 'numpy.unique', 'np.unique', (['gt'], {}), '(gt)\n', (1193, 1197), True, 'import numpy as np\n'), ((773, 789), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (783, 789), False, 'import cv2\n'), ((1250, 1289), 'numpy.zeros', 'np.zeros', (['(4, gt.shape[0], gt.shape[1])'], {}), '((4, gt.shape[0], gt.shape[1]))\n', (1258, 1289), True, 'import numpy as np\n')]
|
import tensorflow as tf
from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding
from tensorflow.keras.activations import softmax, linear
import tensorflow.keras.backend as K
import numpy as np
def gelu(x):
return 0.5*x*(1+tf.tanh(np.sqrt(2/np.pi)*(x+0.044715*tf.pow(x, 3))))
class scaledDotProductAttentionLayer(tf.keras.layers.Layer):
def call(self, x, training):
q, k, v = x
qk = tf.matmul(q, k, transpose_b=True)/K.sqrt(tf.cast(K.shape(k)[-1], tf.float32))
return tf.matmul(softmax(qk, axis=-1), v)
class multiHeadAttentionLayer(tf.keras.layers.Layer):
def __init__(self, d_model, head=12):
super(multiHeadAttentionLayer, self).__init__()
self.head = head
self.permute = Permute((2, 1, 3))
self.re1 = Reshape((-1, self.head, d_model//self.head))
self.re2 = Reshape((-1, d_model))
self.linear = Dense(d_model)
def call(self, x, training):
q, k, v = x
# subspace header
q_s = self.permute(self.re1(q))
k_s = self.permute(self.re1(k))
v_s = self.permute(self.re1(v))
# combine head
head = scaledDotProductAttentionLayer()([q_s, k_s, v_s], training)
scaled_attention = self.permute(head)
concat_attention = self.re2(self.permute(scaled_attention))
multi_head = self.linear(concat_attention)
return multi_head
class mlpLayer(tf.keras.layers.Layer):
def __init__(self, hidden_dim, output_dim):
super(mlpLayer, self).__init__()
self.d1 = Dense(hidden_dim, activation=gelu)#, kernel_regularizer=tf.keras.regularizers.l2(0.1))
self.d2 = Dense(output_dim)#, kernel_regularizer=tf.keras.regularizers.l2(0.1))
def call(self, x, training):
x = self.d1(x)
return self.d2(x)
class transformerBlock(tf.keras.layers.Layer):
def __init__(self, d_model, head_num=12, h_dim=3072):
super(transformerBlock, self).__init__()
self.q_d = Dense(d_model)
self.k_d = Dense(d_model)
self.v_d = Dense(d_model)
self.ln1 = LayerNormalization(epsilon=1e-6)
self.ln2 = LayerNormalization(epsilon=1e-6)
self.mlp = mlpLayer(h_dim, d_model)
self.att = multiHeadAttentionLayer(d_model, head_num)
self.drop = Dropout(0.1)
def call(self, x, training):
y = self.ln1(x)
# multi head attention
q = self.q_d(y) # query
k = self.k_d(y) # key
v = self.v_d(y) # value
y = self.att([q, k, v], training)
# y = self.drop(y)
# skip connection
x = x + y
# MLP layer
y = self.ln2(x)
y = self.mlp(y, training)
# self.drop(y)
# skip connection
return x + y
class PatchEmbedding(tf.keras.layers.Layer):
def __init__(self, num_patch, embed_dim, **kwargs):
super(PatchEmbedding, self).__init__(**kwargs)
self.num_patch = num_patch
self.proj = Dense(embed_dim)
self.pos_embed = Embedding(input_dim=num_patch+1, output_dim=embed_dim)
def call(self, patch):
pos = tf.range(start=0, limit=self.num_patch+1, delta=1)
return self.proj(patch) + self.pos_embed(pos)
class visionTransformerLayer(tf.keras.layers.Layer):
def __init__(self, image_size, patch_size, d_model=768, layer_num=12, head_num=12, h_dim=3072):
super(visionTransformerLayer, self).__init__()
self.num_patches = (image_size // patch_size) ** 2
self.d_model = d_model
self.image_size = image_size
self.patch_size = patch_size
self.layer_num = layer_num
# learnabel class embedding
self.class_emb = Dense(1)
self.pos_emb = Embedding(input_dim=self.num_patches + 1, output_dim=768)
self.patch_emb = [PatchEmbedding(self.num_patches, d_model) for i in range(layer_num)]
self.per = Permute((2, 1))
# self.class_emb = self.add_weight(shape=(1, 1, self.d_model),
# initializer='random_normal',
# trainable=True)
# learnable position embedding
# self.pos_emb = self.add_weight(shape=(1, 1, self.d_model),
# initializer='random_normal',
# trainable=True)
self.dense = Dense(d_model, activation='linear')
self.t_layer = [transformerBlock(d_model, head_num, h_dim) for i in range(layer_num)]
def call(self, x, training):
# feature extraction
batch_size = tf.shape(x)[0]
# resize image
x = tf.image.resize(x, [self.image_size, self.image_size])
# extract patch
patches = tf.image.extract_patches(
images=x,
sizes=[1, self.patch_size, self.patch_size, 1],
strides=[1, self.patch_size, self.patch_size, 1],
rates=[1, 1, 1, 1],
padding='VALID',
)
patches = Reshape((self.num_patches, -1))(patches)
print('patches:', patches.shape, self.patch_size, self.num_patches)
x = self.dense(patches)
print(f'patches: {x.shape}')
pos = tf.range(start=0, limit=self.num_patches + 1, delta=1)
class_emb = self.per(self.class_emb(self.per(x)))
pos_emb = self.pos_emb(pos)#self.per(self.pos_emb(self.per(x)))
# class_emb = tf.broadcast_to(self.class_emb, [batch_size, 1, self.d_model])
print('class_emb:', pos_emb.shape)
x = tf.concat([class_emb, x], axis=1)
x = x + pos_emb
# transformer block
for i in range(self.layer_num):
x = self.patch_emb[i](x)
x = self.t_layer[i](x, training)
return x
def visionTransformer(input_dim, output_dim, image_size=32, patch_size=8, d_model=768, layer_num=12, head_num=12, h_dim=3072):
inputs = tf.keras.Input(shape=input_dim)
ViT_layer = visionTransformerLayer(image_size, patch_size, d_model, layer_num, head_num, h_dim)
y = ViT_layer(inputs)
print('y :', y.shape)
# y = Dense(output_dim, activation=gelu)(y[:, 0])
y = GlobalAveragePooling1D()(y)
outputs = Dense(output_dim, activation='softmax')(y)
print(outputs.shape)
return tf.keras.Model(inputs, outputs, name='vit'), ViT_layer
|
[
"tensorflow.shape",
"numpy.sqrt",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.backend.shape",
"tensorflow.keras.layers.Reshape",
"tensorflow.pow",
"tensorflow.keras.layers.Permute",
"tensorflow.image.extract_patches",
"tensorflow.keras.activations.softmax",
"tensorflow.concat",
"tensorflow.keras.layers.GlobalAveragePooling1D",
"tensorflow.matmul",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Embedding",
"tensorflow.range",
"tensorflow.keras.Input",
"tensorflow.image.resize",
"tensorflow.keras.Model",
"tensorflow.keras.layers.LayerNormalization"
] |
[((6093, 6124), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': 'input_dim'}), '(shape=input_dim)\n', (6107, 6124), True, 'import tensorflow as tf\n'), ((810, 828), 'tensorflow.keras.layers.Permute', 'Permute', (['(2, 1, 3)'], {}), '((2, 1, 3))\n', (817, 828), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((848, 894), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(-1, self.head, d_model // self.head)'], {}), '((-1, self.head, d_model // self.head))\n', (855, 894), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((912, 934), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(-1, d_model)'], {}), '((-1, d_model))\n', (919, 934), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((957, 971), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (962, 971), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((1645, 1679), 'tensorflow.keras.layers.Dense', 'Dense', (['hidden_dim'], {'activation': 'gelu'}), '(hidden_dim, activation=gelu)\n', (1650, 1679), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((1750, 1767), 'tensorflow.keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (1755, 1767), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2076, 2090), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2081, 2090), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2110, 2124), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2115, 2124), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2144, 2158), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2149, 2158), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2178, 2211), 'tensorflow.keras.layers.LayerNormalization', 'LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (2196, 2211), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2230, 2263), 'tensorflow.keras.layers.LayerNormalization', 'LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (2248, 2263), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2398, 2410), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.1)'], {}), '(0.1)\n', (2405, 2410), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3083, 3099), 'tensorflow.keras.layers.Dense', 'Dense', (['embed_dim'], {}), '(embed_dim)\n', (3088, 3099), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3125, 3181), 'tensorflow.keras.layers.Embedding', 'Embedding', ([], {'input_dim': '(num_patch + 1)', 'output_dim': 'embed_dim'}), '(input_dim=num_patch + 1, output_dim=embed_dim)\n', (3134, 3181), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3222, 3274), 'tensorflow.range', 'tf.range', ([], {'start': '(0)', 'limit': '(self.num_patch + 1)', 'delta': '(1)'}), '(start=0, limit=self.num_patch + 1, delta=1)\n', (3230, 3274), True, 'import tensorflow as tf\n'), ((3809, 3817), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (3814, 3817), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3841, 3898), 'tensorflow.keras.layers.Embedding', 'Embedding', ([], {'input_dim': '(self.num_patches + 1)', 'output_dim': '(768)'}), '(input_dim=self.num_patches + 1, output_dim=768)\n', (3850, 3898), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4031, 4046), 'tensorflow.keras.layers.Permute', 'Permute', (['(2, 1)'], {}), '((2, 1))\n', (4038, 4046), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4520, 4555), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {'activation': '"""linear"""'}), "(d_model, activation='linear')\n", (4525, 4555), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4801, 4855), 'tensorflow.image.resize', 'tf.image.resize', (['x', '[self.image_size, self.image_size]'], {}), '(x, [self.image_size, self.image_size])\n', (4816, 4855), True, 'import tensorflow as tf\n'), ((4907, 5086), 'tensorflow.image.extract_patches', 'tf.image.extract_patches', ([], {'images': 'x', 'sizes': '[1, self.patch_size, self.patch_size, 1]', 'strides': '[1, self.patch_size, self.patch_size, 1]', 'rates': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(images=x, sizes=[1, self.patch_size, self.\n patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates\n =[1, 1, 1, 1], padding='VALID')\n", (4931, 5086), True, 'import tensorflow as tf\n'), ((5375, 5429), 'tensorflow.range', 'tf.range', ([], {'start': '(0)', 'limit': '(self.num_patches + 1)', 'delta': '(1)'}), '(start=0, limit=self.num_patches + 1, delta=1)\n', (5383, 5429), True, 'import tensorflow as tf\n'), ((5700, 5733), 'tensorflow.concat', 'tf.concat', (['[class_emb, x]'], {'axis': '(1)'}), '([class_emb, x], axis=1)\n', (5709, 5733), True, 'import tensorflow as tf\n'), ((6339, 6363), 'tensorflow.keras.layers.GlobalAveragePooling1D', 'GlobalAveragePooling1D', ([], {}), '()\n', (6361, 6363), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((6381, 6420), 'tensorflow.keras.layers.Dense', 'Dense', (['output_dim'], {'activation': '"""softmax"""'}), "(output_dim, activation='softmax')\n", (6386, 6420), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((6460, 6503), 'tensorflow.keras.Model', 'tf.keras.Model', (['inputs', 'outputs'], {'name': '"""vit"""'}), "(inputs, outputs, name='vit')\n", (6474, 6503), True, 'import tensorflow as tf\n'), ((476, 509), 'tensorflow.matmul', 'tf.matmul', (['q', 'k'], {'transpose_b': '(True)'}), '(q, k, transpose_b=True)\n', (485, 509), True, 'import tensorflow as tf\n'), ((579, 599), 'tensorflow.keras.activations.softmax', 'softmax', (['qk'], {'axis': '(-1)'}), '(qk, axis=-1)\n', (586, 599), False, 'from tensorflow.keras.activations import softmax, linear\n'), ((4742, 4753), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (4750, 4753), True, 'import tensorflow as tf\n'), ((5166, 5197), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(self.num_patches, -1)'], {}), '((self.num_patches, -1))\n', (5173, 5197), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((303, 321), 'numpy.sqrt', 'np.sqrt', (['(2 / np.pi)'], {}), '(2 / np.pi)\n', (310, 321), True, 'import numpy as np\n'), ((525, 535), 'tensorflow.keras.backend.shape', 'K.shape', (['k'], {}), '(k)\n', (532, 535), True, 'import tensorflow.keras.backend as K\n'), ((332, 344), 'tensorflow.pow', 'tf.pow', (['x', '(3)'], {}), '(x, 3)\n', (338, 344), True, 'import tensorflow as tf\n')]
|
import numpy as np
import multiprocessing
import sys
have_cext = False
try:
from .. import _cext
have_cext = True
except ImportError:
pass
except:
print("the C extension is installed...but failed to load!")
pass
try:
import xgboost
except ImportError:
pass
except:
print("xgboost is installed...but failed to load!")
pass
try:
import lightgbm
except ImportError:
pass
except:
print("lightgbm is installed...but failed to load!")
pass
try:
import catboost
except ImportError:
pass
except:
print("catboost is installed...but failed to load!")
pass
class TreeExplainer:
"""Uses the Tree SHAP method to explain the output of ensemble tree models.
Tree SHAP is a fast and exact method to estimate SHAP values for tree models and ensembles
of trees. It depends on fast C++ implementations either inside the package or in the
compiled C extention.
"""
def __init__(self, model, **kwargs):
self.model_type = "internal"
if str(type(model)).endswith("sklearn.ensemble.forest.RandomForestRegressor'>"):
self.trees = [Tree(e.tree_) for e in model.estimators_]
elif str(type(model)).endswith("sklearn.tree.tree.DecisionTreeRegressor'>"):
self.trees = [Tree(model.tree_)]
elif str(type(model)).endswith("sklearn.ensemble.forest.RandomForestClassifier'>"):
self.trees = [Tree(e.tree_, normalize=True) for e in model.estimators_]
elif str(type(model)).endswith("xgboost.core.Booster'>"):
self.model_type = "xgboost"
self.trees = model
elif str(type(model)).endswith("xgboost.sklearn.XGBClassifier'>"):
self.model_type = "xgboost"
self.trees = model.get_booster()
elif str(type(model)).endswith("xgboost.sklearn.XGBRegressor'>"):
self.model_type = "xgboost"
self.trees = model.get_booster()
elif str(type(model)).endswith("lightgbm.basic.Booster'>"):
self.model_type = "lightgbm"
self.trees = model
elif str(type(model)).endswith("lightgbm.sklearn.LGBMRegressor'>"):
self.model_type = "lightgbm"
self.trees = model.booster_
elif str(type(model)).endswith("lightgbm.sklearn.LGBMClassifier'>"):
self.model_type = "lightgbm"
self.trees = model.booster_
elif str(type(model)).endswith("catboost.core.CatBoostRegressor'>"):
self.model_type = "catboost"
self.trees = model
elif str(type(model)).endswith("catboost.core.CatBoostClassifier'>"):
self.model_type = "catboost"
self.trees = model
else:
raise Exception("Model type not yet supported by TreeExplainer: " + str(type(model)))
def shap_values(self, X, **kwargs):
""" Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array or pandas.DataFrame
A matrix of samples (# samples x # features) on which to explain the model's output.
Returns
-------
For a models with a single output this returns a matrix of SHAP values
(# samples x # features + 1). The last column is the base value of the model, which is
the expected value of the model applied to the background dataset. This causes each row to
sum to the model output for that sample. For models with vector outputs this returns a list
of such matrices, one for each output.
"""
# shortcut using the C++ version of Tree SHAP in XGBoost, LightGBM, and CatBoost
phi = None
if self.model_type == "xgboost":
if not str(type(X)).endswith("xgboost.core.DMatrix'>"):
X = xgboost.DMatrix(X)
phi = self.trees.predict(X, pred_contribs=True)
elif self.model_type == "lightgbm":
phi = self.trees.predict(X, pred_contrib=True)
if phi.shape[1] != X.shape[1] + 1:
phi = phi.reshape(X.shape[0], phi.shape[1]//(X.shape[1]+1), X.shape[1]+1)
elif self.model_type == "catboost": # thanks to the CatBoost team for implementing this...
phi = self.trees.get_feature_importance(data=catboost.Pool(X), fstr_type='ShapValues')
if phi is not None:
if len(phi.shape) == 3:
return [phi[:, i, :] for i in range(phi.shape[1])]
else:
return phi
# convert dataframes
if str(type(X)).endswith("pandas.core.series.Series'>"):
X = X.values
elif str(type(X)).endswith("pandas.core.frame.DataFrame'>"):
X = X.values
assert str(type(X)).endswith("'numpy.ndarray'>"), "Unknown instance type: " + str(type(X))
assert len(X.shape) == 1 or len(X.shape) == 2, "Instance must have 1 or 2 dimensions!"
self.n_outputs = self.trees[0].values.shape[1]
# single instance
if len(X.shape) == 1:
phi = np.zeros((X.shape[0] + 1, self.n_outputs))
x_missing = np.zeros(X.shape[0], dtype=np.bool)
for t in self.trees:
self.tree_shap(t, X, x_missing, phi)
phi /= len(self.trees)
if self.n_outputs == 1:
return phi[:, 0]
else:
return [phi[:, i] for i in range(self.n_outputs)]
elif len(X.shape) == 2:
x_missing = np.zeros(X.shape[1], dtype=np.bool)
self._current_X = X
self._current_x_missing = x_missing
# Only python 3 can serialize a method to send to another process
if sys.version_info[0] >= 3:
pool = multiprocessing.Pool()
phi = np.stack(pool.map(self._tree_shap_ind, range(X.shape[0])), 0)
pool.close()
else:
phi = np.stack(map(self._tree_shap_ind, range(X.shape[0])), 0)
if self.n_outputs == 1:
return phi[:, :, 0]
else:
return [phi[:, :, i] for i in range(self.n_outputs)]
def shap_interaction_values(self, X, **kwargs):
# shortcut using the C++ version of Tree SHAP in XGBoost and LightGBM
if self.model_type == "xgboost":
if not str(type(X)).endswith("xgboost.core.DMatrix'>"):
X = xgboost.DMatrix(X)
phi = self.trees.predict(X, pred_interactions=True)
if len(phi.shape) == 4:
return [phi[:, i, :, :] for i in range(phi.shape[1])]
else:
return phi
else:
raise Exception("Interaction values not yet supported for model type: " + self.model_type)
def _tree_shap_ind(self, i):
phi = np.zeros((self._current_X.shape[1] + 1, self.n_outputs))
for t in self.trees:
self.tree_shap(t, self._current_X[i,:], self._current_x_missing, phi)
phi /= len(self.trees)
return phi
def tree_shap(self, tree, x, x_missing, phi, condition=0, condition_feature=0):
# start the recursive algorithm
assert have_cext, "C extension was not built during install!"
_cext.tree_shap(
tree.max_depth, tree.children_left, tree.children_right, tree.children_default, tree.features,
tree.thresholds, tree.values, tree.node_sample_weight,
x, x_missing, phi, condition, condition_feature
)
class Tree:
def __init__(self, children_left, children_right, children_default, feature, threshold, value, node_sample_weight):
self.children_left = children_left.astype(np.int32)
self.children_right = children_right.astype(np.int32)
self.children_default = children_default.astype(np.int32)
self.features = feature.astype(np.int32)
self.thresholds = threshold
self.values = value
self.node_sample_weight = node_sample_weight
# we compute the expectations to make sure they follow the SHAP logic
assert have_cext, "C extension was not built during install!"
self.max_depth = _cext.compute_expectations(
self.children_left, self.children_right, self.node_sample_weight,
self.values
)
def __init__(self, tree, normalize=False):
if str(type(tree)).endswith("'sklearn.tree._tree.Tree'>"):
self.children_left = tree.children_left.astype(np.int32)
self.children_right = tree.children_right.astype(np.int32)
self.children_default = self.children_left # missing values not supported in sklearn
self.features = tree.feature.astype(np.int32)
self.thresholds = tree.threshold.astype(np.float64)
if normalize:
self.values = (tree.value[:,0,:].T / tree.value[:,0,:].sum(1)).T
else:
self.values = tree.value[:,0,:]
self.node_sample_weight = tree.weighted_n_node_samples.astype(np.float64)
# we compute the expectations to make sure they follow the SHAP logic
self.max_depth = _cext.compute_expectations(
self.children_left, self.children_right, self.node_sample_weight,
self.values
)
|
[
"numpy.zeros",
"xgboost.DMatrix",
"catboost.Pool",
"multiprocessing.Pool"
] |
[((6770, 6826), 'numpy.zeros', 'np.zeros', (['(self._current_X.shape[1] + 1, self.n_outputs)'], {}), '((self._current_X.shape[1] + 1, self.n_outputs))\n', (6778, 6826), True, 'import numpy as np\n'), ((5023, 5065), 'numpy.zeros', 'np.zeros', (['(X.shape[0] + 1, self.n_outputs)'], {}), '((X.shape[0] + 1, self.n_outputs))\n', (5031, 5065), True, 'import numpy as np\n'), ((5090, 5125), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {'dtype': 'np.bool'}), '(X.shape[0], dtype=np.bool)\n', (5098, 5125), True, 'import numpy as np\n'), ((3788, 3806), 'xgboost.DMatrix', 'xgboost.DMatrix', (['X'], {}), '(X)\n', (3803, 3806), False, 'import xgboost\n'), ((5458, 5493), 'numpy.zeros', 'np.zeros', (['X.shape[1]'], {'dtype': 'np.bool'}), '(X.shape[1], dtype=np.bool)\n', (5466, 5493), True, 'import numpy as np\n'), ((6371, 6389), 'xgboost.DMatrix', 'xgboost.DMatrix', (['X'], {}), '(X)\n', (6386, 6389), False, 'import xgboost\n'), ((5717, 5739), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (5737, 5739), False, 'import multiprocessing\n'), ((4263, 4279), 'catboost.Pool', 'catboost.Pool', (['X'], {}), '(X)\n', (4276, 4279), False, 'import catboost\n')]
|
import numpy as np
from unityagents import UnityEnvironment
"""UnityEnv is a wrapper around UnityEnvironment
The main purpose for this Env is to establish a common interface which most environments expose
"""
class UnityEnv:
def __init__(self,
env_path,
train_mode = True
):
self.brain = None
self.brain_name = None
self.train_mode = train_mode
self.env = self.create_unity_env(env_path)
#env details
self.action_space = self.brain.vector_action_space_size
self.observation_space = self.brain.vector_observation_space_size
print(f'Action space {self.action_space}')
print(f'State space {self.observation_space}')
#backwards compatibility
self.action_dim = self.action_space
#self.observation_space = self.env.observation_space
self.state_dim = int(np.prod(self.observation_space))
def extract_env_details(self, env_info):
next_state = env_info.vector_observations # get the next state
reward = env_info.rewards # get the reward
done = env_info.local_done # see if episode has finished
return next_state, reward, done
def create_unity_env(self, env_path):
env = UnityEnvironment(file_name=env_path)
self.brain_name = env.brain_names[0]
self.brain = env.brains[self.brain_name]
return env
def reset(self):
env_info = self.env.reset(train_mode=self.train_mode)[self.brain_name]
return self.extract_env_details(env_info)[0]
def step(self, actions):
actions = np.clip(actions, -1, 1)
# torch.clamp(actions, min=-1, max=1)
self.env.step(actions)[self.brain_name]
env_info = self.env.step(actions)[self.brain_name]
next_states, rewards, dones = self.extract_env_details(env_info)
return next_states, rewards, np.array(dones)
# return next_state, reward, np.array([done])
|
[
"numpy.clip",
"numpy.prod",
"unityagents.UnityEnvironment",
"numpy.array"
] |
[((1294, 1330), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': 'env_path'}), '(file_name=env_path)\n', (1310, 1330), False, 'from unityagents import UnityEnvironment\n'), ((1649, 1672), 'numpy.clip', 'np.clip', (['actions', '(-1)', '(1)'], {}), '(actions, -1, 1)\n', (1656, 1672), True, 'import numpy as np\n'), ((925, 956), 'numpy.prod', 'np.prod', (['self.observation_space'], {}), '(self.observation_space)\n', (932, 956), True, 'import numpy as np\n'), ((1940, 1955), 'numpy.array', 'np.array', (['dones'], {}), '(dones)\n', (1948, 1955), True, 'import numpy as np\n')]
|
import torch
from torch import nn
import pdb, os
from shapely.geometry import *
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema
import random
import string
all_types = [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],\
[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],\
[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],\
[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]]
class kePostProcessor(nn.Module):
def __init__(self, keer=None, cfg=None):
super(kePostProcessor, self).__init__()
self.keer = keer
self.cfg = cfg
def forward(self, ft_x, ft_y, mty, boxes):
ke_prob_x = ft_x
ke_prob_y = ft_y
mty_prob = mty
boxes_per_image = [box.bbox.size(0) for box in boxes]
ke_prob_x = ke_prob_x.split(boxes_per_image, dim=0)
ke_prob_y = ke_prob_y.split(boxes_per_image, dim=0)
mty_prob = mty_prob.split(boxes_per_image, dim=0)
results = []
for prob_x, prob_y, prob_mty, box in zip(ke_prob_x, ke_prob_y, mty_prob, boxes):
bbox = BoxList(box.bbox, box.size, mode='xyxy')
for field in box.fields():
bbox.add_field(field, box.get_field(field))
if self.keer:
prob_x, rescores_x = self.keer(prob_x, box)
prob_y, rescores_y = self.keer(prob_y, box)
rescores = (rescores_x+rescores_y)*0.5
if self.cfg.MODEL.ROI_KE_HEAD.RESCORING:
bbox.add_field('scores', rescores)
prob = torch.cat((prob_x,prob_y), dim = -2)
prob = prob[..., :1]
prob = textKES(prob, box.size)
bbox.add_field('ke', prob)
bbox.add_field('mty', prob_mty)
results.append(bbox)
return results
# TODO remove and use only the keer
import numpy as np
import cv2
def scores_to_probs(scores):
"""Transforms CxHxW of scores to probabilities spatially."""
channels = scores.shape[0]
for c in range(channels):
temp = scores[c, :, :]
max_score = temp.max()
temp = np.exp(temp - max_score) / np.sum(np.exp(temp - max_score))
scores[c, :, :] = temp
return scores
def kes_decode(kes):
# BDN decode
for ix, i in enumerate(kes):
mnd = i[0, 0]
nkes = i.shape[1]-2
kes[ix][0, 1:5] = kes[ix][0, 1:5]*2 - mnd
return kes
def heatmaps_to_kes(maps, rois, scores, cfg):
"""Extract predicted ke locations from heatmaps. Output has shape
(#rois, 4, #kes) with the 4 rows corresponding to (x, y, logit, prob)
for each ke.
"""
# This function converts a discrete image coordinate in a HEATMAP_SIZE x
# HEATMAP_SIZE image to a continuous ke coordinate. We maintain
# consistency with kes_to_heatmap_labels by using the conversion from
# Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
# continuous coordinate.
offset_x = rois[:, 0]
offset_y = rois[:, 1]
widths = rois[:, 2] - rois[:, 0]
heights = rois[:, 3] - rois[:, 1]
widths = np.maximum(widths, 1)
heights = np.maximum(heights, 1)
widths_ceil = np.ceil(widths)
heights_ceil = np.ceil(heights)
resol = cfg.MODEL.ROI_KE_HEAD.RESOLUTION # cfg.mo... 56
if maps.shape[-2:] == (1, resol):
xory_mode = 0 # x mode
elif maps.shape[-2:] == (resol, 1):
xory_mode = 1 # y mode
else:
assert(0), 'invalid mode.'
# print("maps", maps.shape, maps[0,0], maps[0,1])
# NCHW to NHWC for use with OpenCV
maps = np.transpose(maps, [0, 2, 3, 1])
min_size = 0 # cfg
num_kes = int(cfg.MODEL.ROI_KE_HEAD.NUM_KES/2)+2
d_preds = np.zeros(
(len(rois), 2, num_kes), dtype=np.float32)
d_scores = np.zeros(scores.shape, dtype=np.float32)
assert(len(rois) == maps.shape[0]), 'shape mismatch {}, {}, {}, {}'.format(str(len(rois)), \
str(rois.shape), \
str(maps.shape[0]), \
str(maps.shape))
normal = 0
innormal = 0
for i in range(len(rois)):
if min_size > 0:
roi_map_width = int(np.maximum(widths_ceil[i], min_size))
roi_map_height = int(np.maximum(heights_ceil[i], min_size))
else:
roi_map_width = widths_ceil[i]
roi_map_height = heights_ceil[i]
width_correction = widths[i] / roi_map_width
height_correction = heights[i] / roi_map_height
np.set_printoptions(suppress=True)
# print(i, "stop", maps.shape, np.around(maps[i][0, :, :], decimals=2))
if not xory_mode:
roi_map = cv2.resize(
maps[i], (roi_map_width, 1), interpolation=cv2.INTER_CUBIC)
else:
roi_map = cv2.resize(
maps[i], (1, roi_map_height), interpolation=cv2.INTER_CUBIC)
# print(roi_map.shape, np.around(roi_map[0, :, :], decimals=2))
# Bring back to CHW
roi_map = np.transpose(roi_map, [2, 0, 1])
roi_map_probs = scores_to_probs(roi_map.copy())
# kescore visulize.
map_vis = np.transpose(maps[i], [2, 0, 1])
map_vis = scores_to_probs(map_vis.copy())
sum_score = []
if cfg.MODEL.ROI_KE_HEAD.RESCORING:
for k in range(num_kes):
if map_vis[k].shape[0] == 1:
x = np.arange(0, len(map_vis[k][0]), 1)
y = map_vis[k][0]
else:
x = np.arange(0, len(map_vis[k][:, 0]), 1)
y = map_vis[k][:, 0]
top = y.max()
atop = y.argmax()
# lf2&1
lf2 = max(atop-2, 0)
lf1 = max(atop-1, 0)
rt2 = min(atop+2, 55)
rt1 = min(atop+1, 55)
sum_score.append(top+y[lf2]+y[lf1]+y[rt1]+y[rt2])
kes_score_mean = sum(sum_score)*1.0/len(sum_score)
gama = cfg.MODEL.ROI_KE_HEAD.RESCORING_GAMA
final_score = (scores[i]*(2.0-gama)+gama*kes_score_mean)*0.5
# rescore
d_scores[i] = final_score
else:
d_scores[i] = scores[i]
w = roi_map.shape[2]
for k in range(num_kes):
pos = roi_map[k, :, :].argmax()
x_int = pos % w
y_int = (pos - x_int) // w
assert (roi_map_probs[k, y_int, x_int] ==
roi_map_probs[k, :, :].max())
x = (x_int + 0.5) * width_correction
y = (y_int + 0.5) * height_correction
if not xory_mode:
d_preds[i, 0, k] = x + offset_x[i]
d_preds[i, 1, k] = roi_map_probs[k, y_int, x_int]
else:
d_preds[i, 0, k] = y + offset_y[i]
d_preds[i, 1, k] = roi_map_probs[k, y_int, x_int]
out_kes_d = kes_decode(d_preds)
return np.transpose(out_kes_d, [0, 2, 1]), d_scores
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.ke import textKES
class KEer(object):
"""
Projects a set of masks in an image on the locations
specified by the bounding boxes
"""
def __init__(self, padding=0, cfg =None):
self.padding = padding
self.cfg =cfg
def compute_flow_field_cpu(self, boxes):
im_w, im_h = boxes.size
boxes_data = boxes.bbox
num_boxes = len(boxes_data)
device = boxes_data.device
TO_REMOVE = 1
boxes_data = boxes_data.int()
box_widths = boxes_data[:, 2] - boxes_data[:, 0] + TO_REMOVE
box_heights = boxes_data[:, 3] - boxes_data[:, 1] + TO_REMOVE
box_widths.clamp_(min=1)
box_heights.clamp_(min=1)
boxes_data = boxes_data.tolist()
box_widths = box_widths.tolist()
box_heights = box_heights.tolist()
flow_field = torch.full((num_boxes, im_h, im_w, 2), -2)
# TODO maybe optimize to make it GPU-friendly with advanced indexing
# or dedicated kernel
for i in range(num_boxes):
w = box_widths[i]
h = box_heights[i]
if w < 2 or h < 2:
continue
x = torch.linspace(-1, 1, w)
y = torch.linspace(-1, 1, h)
# meshogrid
x = x[None, :].expand(h, w)
y = y[:, None].expand(h, w)
b = boxes_data[i]
x_0 = max(b[0], 0)
x_1 = min(b[2] + 0, im_w)
y_0 = max(b[1], 0)
y_1 = min(b[3] + 0, im_h)
flow_field[i, y_0:y_1, x_0:x_1, 0] = x[(y_0 - b[1]):(y_1 - b[1]),(x_0 - b[0]):(x_1 - b[0])]
flow_field[i, y_0:y_1, x_0:x_1, 1] = y[(y_0 - b[1]):(y_1 - b[1]),(x_0 - b[0]):(x_1 - b[0])]
return flow_field.to(device)
def compute_flow_field(self, boxes):
return self.compute_flow_field_cpu(boxes)
# TODO make it work better for batches
def forward_single_image(self, masks, boxes):
boxes = boxes.convert('xyxy')
if self.padding:
boxes = BoxList(boxes.bbox.clone(), boxes.size, boxes.mode)
masks, scale = expand_masks(masks, self.padding)
boxes.bbox = expand_boxes(boxes.bbox, scale)
flow_field = self.compute_flow_field(boxes)
result = torch.nn.functional.grid_sample(masks, flow_field)
return result
def to_points(self, masks):
height, width = masks.shape[-2:]
m = masks.view(masks.shape[:2] + (-1,))
scores, pos = m.max(-1)
x_int = pos % width
y_int = (pos - x_int) // width
result = torch.stack([x_int.float(), y_int.float(), torch.ones_like(x_int, dtype=torch.float32)], dim=2)
return result
def __call__(self, masks, boxes):
# TODO do this properly
if isinstance(boxes, BoxList):
boxes = [boxes]
if isinstance(masks, list):
masks = torch.stack(masks, dim=0)
assert(len(masks.size()) == 4)
scores = boxes[0].get_field("scores")
result, rescores = heatmaps_to_kes(masks.detach().cpu().numpy(), boxes[0].bbox.cpu().numpy(), scores.cpu().numpy(), self.cfg)
return torch.from_numpy(result).to(masks.device), torch.from_numpy(rescores).to(masks.device)
def make_roi_ke_post_processor(cfg):
if cfg.MODEL.ROI_KE_HEAD.POSTPROCESS_KES:
keer = KEer(padding=0, cfg=cfg)
else:
keer = None
ke_post_processor = kePostProcessor(keer,cfg)
return ke_post_processor
|
[
"torch.nn.functional.grid_sample",
"numpy.ceil",
"torch.ones_like",
"cv2.resize",
"torch.full",
"maskrcnn_benchmark.structures.ke.textKES",
"torch.stack",
"torch.from_numpy",
"maskrcnn_benchmark.structures.bounding_box.BoxList",
"numpy.exp",
"numpy.zeros",
"torch.linspace",
"numpy.maximum",
"numpy.transpose",
"torch.cat",
"numpy.set_printoptions"
] |
[((3298, 3319), 'numpy.maximum', 'np.maximum', (['widths', '(1)'], {}), '(widths, 1)\n', (3308, 3319), True, 'import numpy as np\n'), ((3334, 3356), 'numpy.maximum', 'np.maximum', (['heights', '(1)'], {}), '(heights, 1)\n', (3344, 3356), True, 'import numpy as np\n'), ((3375, 3390), 'numpy.ceil', 'np.ceil', (['widths'], {}), '(widths)\n', (3382, 3390), True, 'import numpy as np\n'), ((3410, 3426), 'numpy.ceil', 'np.ceil', (['heights'], {}), '(heights)\n', (3417, 3426), True, 'import numpy as np\n'), ((3784, 3816), 'numpy.transpose', 'np.transpose', (['maps', '[0, 2, 3, 1]'], {}), '(maps, [0, 2, 3, 1])\n', (3796, 3816), True, 'import numpy as np\n'), ((3983, 4023), 'numpy.zeros', 'np.zeros', (['scores.shape'], {'dtype': 'np.float32'}), '(scores.shape, dtype=np.float32)\n', (3991, 4023), True, 'import numpy as np\n'), ((4904, 4938), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (4923, 4938), True, 'import numpy as np\n'), ((5400, 5432), 'numpy.transpose', 'np.transpose', (['roi_map', '[2, 0, 1]'], {}), '(roi_map, [2, 0, 1])\n', (5412, 5432), True, 'import numpy as np\n'), ((5544, 5576), 'numpy.transpose', 'np.transpose', (['maps[i]', '[2, 0, 1]'], {}), '(maps[i], [2, 0, 1])\n', (5556, 5576), True, 'import numpy as np\n'), ((7349, 7383), 'numpy.transpose', 'np.transpose', (['out_kes_d', '[0, 2, 1]'], {}), '(out_kes_d, [0, 2, 1])\n', (7361, 7383), True, 'import numpy as np\n'), ((8336, 8378), 'torch.full', 'torch.full', (['(num_boxes, im_h, im_w, 2)', '(-2)'], {}), '((num_boxes, im_h, im_w, 2), -2)\n', (8346, 8378), False, 'import torch\n'), ((9749, 9799), 'torch.nn.functional.grid_sample', 'torch.nn.functional.grid_sample', (['masks', 'flow_field'], {}), '(masks, flow_field)\n', (9780, 9799), False, 'import torch\n'), ((1268, 1308), 'maskrcnn_benchmark.structures.bounding_box.BoxList', 'BoxList', (['box.bbox', 'box.size'], {'mode': '"""xyxy"""'}), "(box.bbox, box.size, mode='xyxy')\n", (1275, 1308), False, 'from maskrcnn_benchmark.structures.bounding_box import BoxList\n'), ((1764, 1799), 'torch.cat', 'torch.cat', (['(prob_x, prob_y)'], {'dim': '(-2)'}), '((prob_x, prob_y), dim=-2)\n', (1773, 1799), False, 'import torch\n'), ((1853, 1876), 'maskrcnn_benchmark.structures.ke.textKES', 'textKES', (['prob', 'box.size'], {}), '(prob, box.size)\n', (1860, 1876), False, 'from maskrcnn_benchmark.structures.ke import textKES\n'), ((2318, 2342), 'numpy.exp', 'np.exp', (['(temp - max_score)'], {}), '(temp - max_score)\n', (2324, 2342), True, 'import numpy as np\n'), ((5068, 5138), 'cv2.resize', 'cv2.resize', (['maps[i]', '(roi_map_width, 1)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(maps[i], (roi_map_width, 1), interpolation=cv2.INTER_CUBIC)\n', (5078, 5138), False, 'import cv2\n'), ((5192, 5263), 'cv2.resize', 'cv2.resize', (['maps[i]', '(1, roi_map_height)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(maps[i], (1, roi_map_height), interpolation=cv2.INTER_CUBIC)\n', (5202, 5263), False, 'import cv2\n'), ((8655, 8679), 'torch.linspace', 'torch.linspace', (['(-1)', '(1)', 'w'], {}), '(-1, 1, w)\n', (8669, 8679), False, 'import torch\n'), ((8696, 8720), 'torch.linspace', 'torch.linspace', (['(-1)', '(1)', 'h'], {}), '(-1, 1, h)\n', (8710, 8720), False, 'import torch\n'), ((10374, 10399), 'torch.stack', 'torch.stack', (['masks'], {'dim': '(0)'}), '(masks, dim=0)\n', (10385, 10399), False, 'import torch\n'), ((2352, 2376), 'numpy.exp', 'np.exp', (['(temp - max_score)'], {}), '(temp - max_score)\n', (2358, 2376), True, 'import numpy as np\n'), ((4574, 4610), 'numpy.maximum', 'np.maximum', (['widths_ceil[i]', 'min_size'], {}), '(widths_ceil[i], min_size)\n', (4584, 4610), True, 'import numpy as np\n'), ((4645, 4682), 'numpy.maximum', 'np.maximum', (['heights_ceil[i]', 'min_size'], {}), '(heights_ceil[i], min_size)\n', (4655, 4682), True, 'import numpy as np\n'), ((10104, 10147), 'torch.ones_like', 'torch.ones_like', (['x_int'], {'dtype': 'torch.float32'}), '(x_int, dtype=torch.float32)\n', (10119, 10147), False, 'import torch\n'), ((10640, 10664), 'torch.from_numpy', 'torch.from_numpy', (['result'], {}), '(result)\n', (10656, 10664), False, 'import torch\n'), ((10683, 10709), 'torch.from_numpy', 'torch.from_numpy', (['rescores'], {}), '(rescores)\n', (10699, 10709), False, 'import torch\n')]
|
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
perc_heads = st.number_input(label='Chance of Coins Landing on Heads', min_value=0.0, max_value=1.0, value=.5)
graph_title = st.text_input(label='Graph Title')
binom_dist = np.random.binomial(1, perc_heads, 1000)
list_of_means = []
for i in range(0, 1000):
list_of_means.append(np.random.choice(binom_dist, 100, replace=True).mean())
fig, ax = plt.subplots()
plt.hist(list_of_means, range=[0,1])
plt.title(graph_title)
st.pyplot(fig)
|
[
"matplotlib.pyplot.hist",
"streamlit.pyplot",
"streamlit.number_input",
"numpy.random.choice",
"matplotlib.pyplot.title",
"streamlit.text_input",
"matplotlib.pyplot.subplots",
"numpy.random.binomial"
] |
[((98, 200), 'streamlit.number_input', 'st.number_input', ([], {'label': '"""Chance of Coins Landing on Heads"""', 'min_value': '(0.0)', 'max_value': '(1.0)', 'value': '(0.5)'}), "(label='Chance of Coins Landing on Heads', min_value=0.0,\n max_value=1.0, value=0.5)\n", (113, 200), True, 'import streamlit as st\n'), ((214, 248), 'streamlit.text_input', 'st.text_input', ([], {'label': '"""Graph Title"""'}), "(label='Graph Title')\n", (227, 248), True, 'import streamlit as st\n'), ((263, 302), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'perc_heads', '(1000)'], {}), '(1, perc_heads, 1000)\n', (281, 302), True, 'import numpy as np\n'), ((451, 465), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (463, 465), True, 'import matplotlib.pyplot as plt\n'), ((468, 505), 'matplotlib.pyplot.hist', 'plt.hist', (['list_of_means'], {'range': '[0, 1]'}), '(list_of_means, range=[0, 1])\n', (476, 505), True, 'import matplotlib.pyplot as plt\n'), ((506, 528), 'matplotlib.pyplot.title', 'plt.title', (['graph_title'], {}), '(graph_title)\n', (515, 528), True, 'import matplotlib.pyplot as plt\n'), ((530, 544), 'streamlit.pyplot', 'st.pyplot', (['fig'], {}), '(fig)\n', (539, 544), True, 'import streamlit as st\n'), ((378, 425), 'numpy.random.choice', 'np.random.choice', (['binom_dist', '(100)'], {'replace': '(True)'}), '(binom_dist, 100, replace=True)\n', (394, 425), True, 'import numpy as np\n')]
|
import os
import requests
import time
import json
import io
import numpy as np
import pandas as pd
import paavo_queries as paavo_queries
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
## NOTE: Table 9_koko access is forbidden from the API for some reasons.
# url to the API
MAIN_PAAVO_URL = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/'
def paavo_url(level, table):
"""Helper to make url to the paavo API"""
return MAIN_PAAVO_URL + str(level) + '/' + table
def fetch_csv(url, destination_directory, file_name, query={"query": [], "response": {"format": "csv"}}):
"""Fetch a single file from PXweb API. File name should end with '.csv'"""
response = requests.post(url, json=query, stream=True, allow_redirects=True)
if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
destination_file = os.path.join(destination_directory, file_name)
if response.status_code == 200:
open(destination_file, 'wb').write(response.content)
print('Downloaded ' + file_name + ' from ' + url)
else:
print('Could not download ' + file_name + ' from ' + url)
print('HTTP/1.1 ' + str(response.status_code))
time.sleep(1)
def fetch_paavo(destination_directory):
"""Fetch the whole Paavo directory"""
# Getting levels from Paavo database
levels = []
response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/')
response_texts = json.loads(response.text)
for response_text in response_texts:
levels.append(str(response_text['id']))
paavo_directory = os.path.join(destination_directory, 'paavo_raw')
for level in levels:
response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/' + str(level))
response_texts = json.loads(response.text)
table_data = {}
for response_text in response_texts:
table_data[response_text['id']] = str(response_text['text']).split('. ')[-1].replace("'", "").replace(" ", "_")
for (id, name) in table_data.items():
url = paavo_url(level, id)
file_name = name + '.csv'
fetch_csv(url, paavo_directory, file_name)
def fetch_dataframe(url, query={"query": [], "response": {"format": "csv"}}):
"""Download a table from PXweb API to a DataFrame"""
response = requests.post(url, json=query, stream=True, allow_redirects=True)
if response.status_code == 200:
byte_data = io.BytesIO(response.content)
df = pd.read_csv(byte_data, sep=',', encoding='iso-8859-1')
print('Downloaded data from ' + url)
return df
else:
print('Could not download from ' + url)
print('HTTP/1.1 ' + str(response.status_code))
return pd.DataFrame()
time.sleep(0.2)
def paavo_data():
"""Download the whole paavo directory to a dictionary with names as keys and dataframes as values"""
data = {}
# Getting levels from paavo database
levels = []
response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/')
response_texts = json.loads(response.text)
for response_text in response_texts:
levels.append(str(response_text['id']))
for level in levels:
response = requests.post(
'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/' + str(level))
response_texts = json.loads(response.text)
table_data = {}
for response_text in response_texts:
table_data[response_text['id']] = str(response_text['text']).split('. ')[-1].replace("'", "").replace(" ", "_")
for (id, name) in table_data.items():
url = paavo_url(level, id)
df = fetch_dataframe(url)
if not df.empty:
data[name] = df
time.sleep(1)
return data
def fetch_paavo_density_and_area(density_file_destination, area_file_destination):
def clean_df(df):
# Drop Finland row
df.drop(index=0, inplace=True)
# Extract postal code
df.rename(columns={df.columns[0]: 'Postal code'}, inplace=True)
df['Postal code'] = df['Postal code'].apply(lambda x: x.split(' ')[0])
# Replace '.' with 0 and set Postal code as index
df.replace({'.': 0}, inplace=True)
df.set_index('Postal code', inplace=True)
# Change data type of all columns to integer
for column in df.columns:
df[column] = df[column].astype(int)
return df
url_2013 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2015/paavo_9_koko_2015.px/'
url_2014 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2016/paavo_9_koko_2016.px/'
url_2015 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2017/paavo_9_koko_2017.px/'
url_2016 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2018/paavo_9_koko_2018.px/'
url_2017 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2019/paavo_9_koko_2019.px/'
dfs = {}
years = np.array([[2014], [2015], [2016], [2017]])
# Download and clean each dataframe
dfs[2013] = clean_df(fetch_dataframe(url_2013, paavo_queries.surface_population_query))
dfs[2014] = clean_df(fetch_dataframe(url_2014, paavo_queries.surface_population_query))
dfs[2015] = clean_df(fetch_dataframe(url_2015, paavo_queries.surface_population_query))
dfs[2016] = clean_df(fetch_dataframe(url_2016, paavo_queries.surface_population_query))
dfs[2017] = clean_df(fetch_dataframe(url_2017, paavo_queries.surface_population_query))
# Change column labels
for (year, df) in dfs.items():
pop_str = 'Population (' + str(year) +')'
area_str = 'Surface area (' + str(year) + ')'
density_str = 'Density (' + str(year) +')'
if year > 2013:
df.rename(columns={df.columns[0]: area_str, df.columns[1]: pop_str}, inplace=True)
df.insert(2, density_str, df[pop_str] / df[area_str])
df.replace({0.0: np.nan})
else:
df.rename(columns={df.columns[0]: pop_str}, inplace=True)
df.replace({0.0: np.nan})
# Merge dataframe using Postal code index, manually adding density and surface area columns for 2013
main_table = dfs[2014]
main_table = main_table.merge(dfs[2013], how='left', on='Postal code')
main_table = main_table.merge(dfs[2015], how='left', on='Postal code')
main_table = main_table.merge(dfs[2016], how='left', on='Postal code')
main_table = main_table.merge(dfs[2017], how='left', on='Postal code')
main_table.insert(0, 'Density (2013)', np.nan)
main_table.insert(0, 'Surface area (2013)', np.nan)
densities = main_table[['Density (2014)', 'Density (2015)', 'Density (2016)', 'Density (2017)']]
# Linear regression on density. If density is negative, drop the latest density and retry. If there is only 1 usable density, copy it to the 2013 density
for index, row in densities.iterrows():
y = row.to_numpy()
valid_index = np.where(y >= 0)
valid_years = years[valid_index]
y = y[valid_index]
density_prediction = -1.0
while len(y) > 1 and density_prediction < 0:
reg = LinearRegression().fit(valid_years, y)
density_prediction = reg.predict([[2013]])
if density_prediction < 0:
y = y[:-1]
valid_years = valid_years[:-1]
if len(y) > 1:
main_table.at[index, 'Density (2013)'] = density_prediction
elif len(y) ==1:
main_table.at[index, 'Density (2013)'] = y[0]
else:
continue
# Calculate surface area using density and population
for index, row in main_table.iterrows():
if row['Population (2013)'] == np.nan:
continue
elif row['Population (2013)'] > 0 and row['Density (2013)'] > 0:
main_table.at[index, 'Surface area (2013)'] = round(row['Population (2013)']/row['Density (2013)'])
elif row['Population (2013)'] == 0 and row['Density (2013)'] == 0:
main_table.at[index, 'Surface area (2013)'] = row['Surface area (2014)']
main_table = main_table.fillna(0)
# Results
densities = main_table[['Density (2013)', 'Density (2014)', 'Density (2015)', 'Density (2016)', 'Density (2017)']]
areas = main_table[['Surface area (2013)', 'Surface area (2014)', 'Surface area (2015)', 'Surface area (2016)', 'Surface area (2017)']]
# Export to tsv files
densities.to_csv(density_file_destination, sep='\t')
areas.to_csv(area_file_destination, sep='\t')
def fetch_paavo_housing(destination_directory, postal_code_file, density_file):
def postal_standardize(df):
df= df.astype({'Postal code': str})
for i in list(df.index):
df.at[i, 'Postal code'] = '0' * (5-len(df.at[i,'Postal code']))+ df.at[i, 'Postal code']
return df
def postal_merge(left, right):
return left.merge(right, how='left', on='Postal code')
def get_mean_simple(df, n):
"""Calculate housing prices for groups of postal codes with the same first 6-n digits"""
df_n = pd.DataFrame(df['Postal code'].apply(lambda x: x[:(1 - n)]))
df_n.rename(columns={df_n.columns[0]: 'Postal code'}, inplace=True)
df_n = df_n.join(df[['Total value', 'Number']].copy())
df_n = df_n.groupby("Postal code", as_index=False).agg("sum")
df_n['Mean'] = df_n['Total value'] / df_n['Number']
df_n.drop(['Total value', 'Number'], axis=1, inplace=True)
# df_n.set_index('Postal code', inplace=True)
return df_n
def impute_simple(df, df_n):
"""Impute using the results above"""
df_ni = df_n.set_index('Postal code')
for code in list(df_n['Postal code']):
df_rows = np.array(df[df['Postal code'].str.startswith(code)].index)
for i in df_rows:
if df.at[i, 'Mean'] == 0 or np.isnan(df.at[i, 'Mean']):
df.at[i, 'Mean'] = df_ni.at[code, 'Mean']
return df
def impute_with_density(df, postal_df):
"""Impute with respect to density using a linear model"""
def postal_truncate(n):
df_n = postal_df.copy()
df_n['Postal code'] = df_n['Postal code'].apply(lambda x: x[:(1-n)])
df_n.drop_duplicates(subset='Postal code', inplace=True)
return df_n
def impute_price(df_, n):
truncated_postal = postal_truncate(n)
for code in truncated_postal['Postal code']:
sub_df = df_[df_['Postal code'].str.startswith(code)]
good_df = sub_df[sub_df['Mean'] != 0]
bad_df = sub_df[sub_df['Mean'] == 0]
if len(good_df.index) >= 7:
good_df = good_df.nsmallest(15, 'Mean')
X = good_df['Density']
y = good_df['Mean']
X = sm.add_constant(X.values)
model = sm.OLS(y, X).fit()
for i in bad_df.index:
if df_.at[i, 'Mean'] <= 0 or np.isnan(df_.at[i, 'Mean']):
df_.at[i, 'Mean'] = int(model.predict([1, df_.at[i, 'Density']])[0])
return df_
for i in range(3,6):
df = impute_price(df, i)
return df
main_table = postal_standardize(pd.read_csv(postal_code_file, sep='\t'))
density = postal_standardize(pd.read_csv(density_file, sep='\t'))
density = density.fillna(0)
postal_code = main_table.copy()
year_list = list(range(2005, 2018))
base_query = paavo_queries.ts_housing_query['query']
for year in year_list:
for quarter in range(5):
# Construct the json query
new_query = [{"code": "Vuosi", "selection": {"filter": "item", "values": [str(year)]}}, {"code": "Neljännes", "selection": {"filter": "item", "values": [str(quarter)]}}] + base_query
quarter_query = {"query": new_query, "response": {"format": "csv"}}
if quarter == 0:
mean_label = 'Housing price (' + str(year) + ')'
else:
mean_label = str(year) + 'Q' +str(quarter)
# Get the data table for the quarter
quarter_frame = postal_standardize(fetch_dataframe(paavo_queries.housing_url, query= quarter_query))
# Leave only Postal code and house price
quarter_frame = quarter_frame[['Postal code', 'Mean', 'Number']]
# Replace missing value '.' with '0'
quarter_frame.replace({'.': '0'}, inplace=True)
# Change mean to housing price and convert to float, number to Int
quarter_frame['Mean'] = quarter_frame['Mean'].astype(int)
quarter_frame['Number'] = quarter_frame['Number'].astype(int)
# Calculate the total housing value for each row
quarter_frame['Total value'] = quarter_frame['Mean'] * quarter_frame['Number']
# Get the complete postal code
quarter_frame = postal_merge(postal_code, quarter_frame)
# Change the numbers of houses where the prices are hidden to 0 so that the calculation of the group mean is not affected
for code in list(quarter_frame.index):
if quarter_frame.at[code, 'Mean'] == 0 or np.isnan(quarter_frame.at[code, 'Mean']):
quarter_frame.at[code, 'Number'] = 0
if year < 2013:
# Calculating the average housing price of postal codes with the same first 3, 2, 1 digits
quarter_frame_3 = get_mean_simple(quarter_frame, 3)
quarter_frame_4 = get_mean_simple(quarter_frame, 4)
quarter_frame_5 = get_mean_simple(quarter_frame, 5)
# Fill df_4 empty values with that of df_5 and df_3 with that of df_4
quarter_frame_4 = impute_simple(quarter_frame_4, quarter_frame_5)
quarter_frame_3 = impute_simple(quarter_frame_3, quarter_frame_4)
# Round mean values and fill empty cells with zero, though there should not be any at this point
quarter_frame_3.fillna(0, inplace=True)
quarter_frame_3['Mean'] = quarter_frame_3['Mean'].astype(int)
# Fill the year frame with mean postal code values
quarter_frame = impute_simple(quarter_frame, quarter_frame_3)
else:
# Extract density values of the year
year_density = density[['Postal code', 'Density (' + str(year) + ')']]
year_density = postal_standardize(year_density)
year_density.rename(columns={('Density (' + str(year) + ')'): 'Density'}, inplace=True)
quarter_frame = postal_merge(quarter_frame, year_density)
quarter_frame = quarter_frame.astype({'Density': float})
quarter_frame = quarter_frame.fillna(0)
# Imputing using density
quarter_frame = impute_with_density(quarter_frame, postal_code)
quarter_frame = quarter_frame.fillna(0)
# Drop unnecessary columns, set Postal code as index, rename mean by year specific label
quarter_frame = quarter_frame[['Postal code','Mean']]
#print(quarter_frame[quarter_frame['Mean'] <= 0].count())
quarter_frame.rename(columns={'Mean': mean_label}, inplace=True)
# Combine the data from the year table into the main table
main_table = postal_merge(main_table, quarter_frame)
print('Year ' + str(year) + ', quarter ' + str(quarter) + ': Done')
# Construct yearly and quarterly tables
quarter_columns = main_table.columns[main_table.columns.str.contains('Q')]
year_columns = main_table.columns[main_table.columns.str.contains('Housing')]
main_table.set_index('Postal code', inplace=True)
year_table = main_table[year_columns]
quarter_table = main_table[quarter_columns]
# Save yearly and quarterly tables to files
year_table.to_csv(os.path.join(destination_directory, 'paavo_housing_data_yearly.tsv'), sep='\t')
quarter_table.to_csv(os.path.join(destination_directory, 'paavo_housing_data_quarterly.tsv'), sep='\t')
|
[
"os.path.exists",
"json.loads",
"requests.post",
"os.makedirs",
"pandas.read_csv",
"numpy.where",
"os.path.join",
"io.BytesIO",
"time.sleep",
"numpy.array",
"statsmodels.api.add_constant",
"numpy.isnan",
"pandas.DataFrame",
"statsmodels.api.OLS",
"sklearn.linear_model.LinearRegression"
] |
[((758, 823), 'requests.post', 'requests.post', (['url'], {'json': 'query', 'stream': '(True)', 'allow_redirects': '(True)'}), '(url, json=query, stream=True, allow_redirects=True)\n', (771, 823), False, 'import requests\n'), ((947, 993), 'os.path.join', 'os.path.join', (['destination_directory', 'file_name'], {}), '(destination_directory, file_name)\n', (959, 993), False, 'import os\n'), ((1295, 1308), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1305, 1308), False, 'import time\n'), ((1474, 1575), 'requests.post', 'requests.post', (['"""http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/"""'], {}), "(\n 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/'\n )\n", (1487, 1575), False, 'import requests\n'), ((1588, 1613), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1598, 1613), False, 'import json\n'), ((1732, 1780), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_raw"""'], {}), "(destination_directory, 'paavo_raw')\n", (1744, 1780), False, 'import os\n'), ((2525, 2590), 'requests.post', 'requests.post', (['url'], {'json': 'query', 'stream': '(True)', 'allow_redirects': '(True)'}), '(url, json=query, stream=True, allow_redirects=True)\n', (2538, 2590), False, 'import requests\n'), ((2968, 2983), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (2978, 2983), False, 'import time\n'), ((3203, 3304), 'requests.post', 'requests.post', (['"""http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/"""'], {}), "(\n 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/'\n )\n", (3216, 3304), False, 'import requests\n'), ((3317, 3342), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3327, 3342), False, 'import json\n'), ((5403, 5445), 'numpy.array', 'np.array', (['[[2014], [2015], [2016], [2017]]'], {}), '([[2014], [2015], [2016], [2017]])\n', (5411, 5445), True, 'import numpy as np\n'), ((838, 875), 'os.path.exists', 'os.path.exists', (['destination_directory'], {}), '(destination_directory)\n', (852, 875), False, 'import os\n'), ((886, 920), 'os.makedirs', 'os.makedirs', (['destination_directory'], {}), '(destination_directory)\n', (897, 920), False, 'import os\n'), ((1960, 1985), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1970, 1985), False, 'import json\n'), ((2651, 2679), 'io.BytesIO', 'io.BytesIO', (['response.content'], {}), '(response.content)\n', (2661, 2679), False, 'import io\n'), ((2694, 2748), 'pandas.read_csv', 'pd.read_csv', (['byte_data'], {'sep': '""","""', 'encoding': '"""iso-8859-1"""'}), "(byte_data, sep=',', encoding='iso-8859-1')\n", (2705, 2748), True, 'import pandas as pd\n'), ((2946, 2960), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2958, 2960), True, 'import pandas as pd\n'), ((3629, 3654), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3639, 3654), False, 'import json\n'), ((7440, 7456), 'numpy.where', 'np.where', (['(y >= 0)'], {}), '(y >= 0)\n', (7448, 7456), True, 'import numpy as np\n'), ((11902, 11941), 'pandas.read_csv', 'pd.read_csv', (['postal_code_file'], {'sep': '"""\t"""'}), "(postal_code_file, sep='\\t')\n", (11913, 11941), True, 'import pandas as pd\n'), ((11977, 12012), 'pandas.read_csv', 'pd.read_csv', (['density_file'], {'sep': '"""\t"""'}), "(density_file, sep='\\t')\n", (11988, 12012), True, 'import pandas as pd\n'), ((16702, 16770), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_housing_data_yearly.tsv"""'], {}), "(destination_directory, 'paavo_housing_data_yearly.tsv')\n", (16714, 16770), False, 'import os\n'), ((16808, 16879), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_housing_data_quarterly.tsv"""'], {}), "(destination_directory, 'paavo_housing_data_quarterly.tsv')\n", (16820, 16879), False, 'import os\n'), ((4061, 4074), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (4071, 4074), False, 'import time\n'), ((7635, 7653), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (7651, 7653), False, 'from sklearn.linear_model import LinearRegression\n'), ((10430, 10456), 'numpy.isnan', 'np.isnan', (["df.at[i, 'Mean']"], {}), "(df.at[i, 'Mean'])\n", (10438, 10456), True, 'import numpy as np\n'), ((11445, 11470), 'statsmodels.api.add_constant', 'sm.add_constant', (['X.values'], {}), '(X.values)\n', (11460, 11470), True, 'import statsmodels.api as sm\n'), ((13903, 13943), 'numpy.isnan', 'np.isnan', (["quarter_frame.at[code, 'Mean']"], {}), "(quarter_frame.at[code, 'Mean'])\n", (13911, 13943), True, 'import numpy as np\n'), ((11502, 11514), 'statsmodels.api.OLS', 'sm.OLS', (['y', 'X'], {}), '(y, X)\n', (11508, 11514), True, 'import statsmodels.api as sm\n'), ((11619, 11646), 'numpy.isnan', 'np.isnan', (["df_.at[i, 'Mean']"], {}), "(df_.at[i, 'Mean'])\n", (11627, 11646), True, 'import numpy as np\n')]
|
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearchCV
import numpy as np
import pandas as pd
scaler = StandardScaler(copy=False, with_mean=False, with_std=True)
class FeatureGenerator():
def __init__(self, feature_config, random_seed=None):
self.feature_config = feature_config
if random_seed is not None:
self.seed = random_seed
self.one_hot_dict = {}
def process_x_data(self, df, train_or_test):
print('\t\tFeaturizing %s df of size %s'%(train_or_test, df.shape))
for task in self.feature_config:
for task_type, target_list in task.items():
if task_type == 'categoricals':
for col in target_list:
col_name = col['column']
df = self.impute_na(df, col_name,
col['imputation'],
'categorical')
df = self.process_one_hot(df, col_name,
train_or_test)
elif task_type == 'numeric':
df = self.process_num(target_list, df)
elif task_type == 'binary':
df = self.process_binary(target_list, df)
elif task_type == 'drop':
df.drop(target_list, axis=1, inplace=True)
print('\t\tCompleted featurization of %s df with size %s'%(train_or_test,df.shape))
return df
def process_one_hot(self, df, col_name, train_or_test):
reshaped = self.reshape_series(df[col_name])
if train_or_test == 'train':
encoder = OneHotEncoder(handle_unknown='ignore').fit(reshaped)
raw_names = encoder.categories_
col_names = ['%s_%s'%(col_name, x) for x in
raw_names[0]]
e_props = {
'encoder': encoder,
'col_names': col_names
}
self.one_hot_dict[col_name] = e_props
else:
col_encoder_dict = self.one_hot_dict[col_name]
encoder = col_encoder_dict['encoder']
col_names = col_encoder_dict['col_names']
labels = encoder.transform(reshaped)
new = df.join(pd.DataFrame(labels.todense(), columns=col_names))
new.drop(col_name, axis=1,inplace=True)
return new
def featurize(self, data_dict):
print('\tBeginning featurization')
trn_cols, trn_data, test_cols, test_data = tuple(data_dict.values())
train_df = pd.DataFrame(trn_data, columns=trn_cols)
train_y = train_df['result']
train_x = train_df.drop('result', axis=1)
featurized_trn_X = self.process_x_data(train_x, 'train')
test_df = pd.DataFrame(test_data, columns=test_cols)
test_y = test_df['result']
test_x = test_df.drop('result', axis=1)
featurized_test_X = self.process_x_data(test_x, 'test')
print('\tCompleted featurization')
return (featurized_trn_X, train_y, featurized_test_X, test_y)
def process_binary(self, target_list, df):
for col in target_list:
col_name = col['column']
df = self.impute_na(df, col_name, col['imputation'], 'binary')
return df
def process_num(self, target_list, df):
for col in target_list:
col_name = col['column']
impute_dict = col['imputation']
scale_after = col['scale']
df[col_name] = pd.to_numeric(df[col_name], errors='coerce')
df = self.impute_na(df, col_name, impute_dict, 'numeric')
if scale_after == True:
self.scale_numeric_col(df, col_name)
return df
def scale_numeric_col(self, df, col_name):
reshaped = self.reshape_series(df[col_name])
scaler.fit(reshaped)
df[col_name] = scaler.transform(reshaped)
return df
def reshape_series(self, series):
arr = np.array(series)
return arr.reshape((arr.shape[0], 1))
def impute_na(self, df, col_name, config, f_type):
series = df[col_name]
missing = df[series.isna()].shape[0]
if missing > 0:
if f_type == 'categorical':
df[col_name] = df[col_name].fillna(config['fill_value'])
elif f_type == 'numeric' or f_type == 'binary':
val_flag = np.nan
if 'missing_values' in config:
val_flag = config['missing_values']
if config['strategy'] == 'constant' and 'fill_value' in config:
imp_mean = SimpleImputer(missing_values=val_flag,
strategy=config['strategy'],
fill_value=config['fill_value'])
else:
imp_mean = SimpleImputer(missing_values=val_flag,
strategy=config['strategy'])
reshaped = self.reshape_series(series)
imp_mean.fit(reshaped)
df[col_name] = imp_mean.transform(reshaped)
return df
|
[
"sklearn.preprocessing.OneHotEncoder",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"pandas.to_numeric",
"sklearn.impute.SimpleImputer",
"pandas.DataFrame"
] |
[((373, 431), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'copy': '(False)', 'with_mean': '(False)', 'with_std': '(True)'}), '(copy=False, with_mean=False, with_std=True)\n', (387, 431), False, 'from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder\n'), ((2839, 2879), 'pandas.DataFrame', 'pd.DataFrame', (['trn_data'], {'columns': 'trn_cols'}), '(trn_data, columns=trn_cols)\n', (2851, 2879), True, 'import pandas as pd\n'), ((3050, 3092), 'pandas.DataFrame', 'pd.DataFrame', (['test_data'], {'columns': 'test_cols'}), '(test_data, columns=test_cols)\n', (3062, 3092), True, 'import pandas as pd\n'), ((4266, 4282), 'numpy.array', 'np.array', (['series'], {}), '(series)\n', (4274, 4282), True, 'import numpy as np\n'), ((3790, 3834), 'pandas.to_numeric', 'pd.to_numeric', (['df[col_name]'], {'errors': '"""coerce"""'}), "(df[col_name], errors='coerce')\n", (3803, 3834), True, 'import pandas as pd\n'), ((1940, 1978), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'handle_unknown': '"""ignore"""'}), "(handle_unknown='ignore')\n", (1953, 1978), False, 'from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder\n'), ((4907, 5011), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'missing_values': 'val_flag', 'strategy': "config['strategy']", 'fill_value': "config['fill_value']"}), "(missing_values=val_flag, strategy=config['strategy'],\n fill_value=config['fill_value'])\n", (4920, 5011), False, 'from sklearn.impute import SimpleImputer\n'), ((5143, 5210), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'missing_values': 'val_flag', 'strategy': "config['strategy']"}), "(missing_values=val_flag, strategy=config['strategy'])\n", (5156, 5210), False, 'from sklearn.impute import SimpleImputer\n')]
|
import torch
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
import torchvision.transforms as transforms
import random
import glob
import os
from PIL import Image
'''
require fix the random seeds
'''
# PotsdamDataset
rgb_means = [0.3366, 0.3599, 0.3333]
rgb_stds = [0.1030, 0.1031, 0.1066]
class PotsdamDataset(Dataset):
def __init__(self,
configs,
subset):
super(PotsdamDataset, self).__init__()
assert subset == 'train' or subset == 'valid' or subset == 'test', \
'subset should be in the set of train, valid, and test'
self.configs = configs
self.subset = subset
# sorted here when the images is not in order
self.path_images = sorted(glob.glob(os.path.join(configs.path_cropped_images, subset, '*')))
#print(self.path_images[0:10])
self.path_labels = sorted(glob.glob(os.path.join(configs.path_cropped_labels, subset, '*')))
#print(self.path_labels[0:10])
# mapping to HxWx1
self.mask_mapping = {
(255, 255, 255) : 0, # impervious surfaces
(0, 0, 255) : 1, # Buildings
(0, 255, 255) : 2, # Low Vegetation
(0, 255, 0) : 3, # Tree
(255, 255, 0) : 4, # Car
(255, 0, 0) : 5 # background/Clutter
}
def mask_to_class(self, mask):
for k in self.mask_mapping:
# all used in numpy: axis, when used in torch: dim
mask[(mask == torch.tensor(k, dtype = torch.uint8)).all(dim = 2)] = self.mask_mapping[k]
return mask[:, :, 0]
def transformation(self, image, mask):
if self.subset == 'train':
# only used for training data
if random.random() > 0.5:
image = TF.hflip(image)
mask = TF.hflip(mask)
if random.random() > 0.5:
image = TF.vflip(image)
mask = TF.vflip(mask)
if random.random() > 0.5:
image = TF.rotate(image, 10)
mask = TF.rotate(mask, 10)
if random.random() > 0.5:
image = TF.rotate(image, -10)
mask = TF.rotate(mask, -10)
image = TF.to_tensor(image)
image = TF.normalize(image, mean=rgb_means, std=rgb_stds)
# here mask's dtype uint8, the dtype of k also should be uint8 and should be a tensor
mask = torch.from_numpy(np.array(mask, dtype=np.uint8))
mask = self.mask_to_class(mask)
mask = mask.long()
return image, mask
def __getitem__(self, item):
image = Image.open(self.path_images[item])
label = Image.open(self.path_labels[item])
image, label = self.transformation(image, label)
# only need filename in testing phase, used in prediction file.
if self.subset == 'test':
return image, label, self.path_images[item]
else:
return image, label
def __len__(self):
return len(self.path_images)
|
[
"torchvision.transforms.functional.to_tensor",
"PIL.Image.open",
"os.path.join",
"torchvision.transforms.functional.hflip",
"numpy.array",
"torchvision.transforms.functional.rotate",
"torchvision.transforms.functional.vflip",
"torch.tensor",
"random.random",
"torchvision.transforms.functional.normalize"
] |
[((2291, 2310), 'torchvision.transforms.functional.to_tensor', 'TF.to_tensor', (['image'], {}), '(image)\n', (2303, 2310), True, 'import torchvision.transforms.functional as TF\n'), ((2327, 2376), 'torchvision.transforms.functional.normalize', 'TF.normalize', (['image'], {'mean': 'rgb_means', 'std': 'rgb_stds'}), '(image, mean=rgb_means, std=rgb_stds)\n', (2339, 2376), True, 'import torchvision.transforms.functional as TF\n'), ((2680, 2714), 'PIL.Image.open', 'Image.open', (['self.path_images[item]'], {}), '(self.path_images[item])\n', (2690, 2714), False, 'from PIL import Image\n'), ((2731, 2765), 'PIL.Image.open', 'Image.open', (['self.path_labels[item]'], {}), '(self.path_labels[item])\n', (2741, 2765), False, 'from PIL import Image\n'), ((2503, 2533), 'numpy.array', 'np.array', (['mask'], {'dtype': 'np.uint8'}), '(mask, dtype=np.uint8)\n', (2511, 2533), True, 'import numpy as np\n'), ((804, 858), 'os.path.join', 'os.path.join', (['configs.path_cropped_images', 'subset', '"""*"""'], {}), "(configs.path_cropped_images, subset, '*')\n", (816, 858), False, 'import os\n'), ((944, 998), 'os.path.join', 'os.path.join', (['configs.path_cropped_labels', 'subset', '"""*"""'], {}), "(configs.path_cropped_labels, subset, '*')\n", (956, 998), False, 'import os\n'), ((1799, 1814), 'random.random', 'random.random', ([], {}), '()\n', (1812, 1814), False, 'import random\n'), ((1846, 1861), 'torchvision.transforms.functional.hflip', 'TF.hflip', (['image'], {}), '(image)\n', (1854, 1861), True, 'import torchvision.transforms.functional as TF\n'), ((1885, 1899), 'torchvision.transforms.functional.hflip', 'TF.hflip', (['mask'], {}), '(mask)\n', (1893, 1899), True, 'import torchvision.transforms.functional as TF\n'), ((1916, 1931), 'random.random', 'random.random', ([], {}), '()\n', (1929, 1931), False, 'import random\n'), ((1963, 1978), 'torchvision.transforms.functional.vflip', 'TF.vflip', (['image'], {}), '(image)\n', (1971, 1978), True, 'import torchvision.transforms.functional as TF\n'), ((2002, 2016), 'torchvision.transforms.functional.vflip', 'TF.vflip', (['mask'], {}), '(mask)\n', (2010, 2016), True, 'import torchvision.transforms.functional as TF\n'), ((2033, 2048), 'random.random', 'random.random', ([], {}), '()\n', (2046, 2048), False, 'import random\n'), ((2080, 2100), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['image', '(10)'], {}), '(image, 10)\n', (2089, 2100), True, 'import torchvision.transforms.functional as TF\n'), ((2124, 2143), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['mask', '(10)'], {}), '(mask, 10)\n', (2133, 2143), True, 'import torchvision.transforms.functional as TF\n'), ((2160, 2175), 'random.random', 'random.random', ([], {}), '()\n', (2173, 2175), False, 'import random\n'), ((2207, 2228), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['image', '(-10)'], {}), '(image, -10)\n', (2216, 2228), True, 'import torchvision.transforms.functional as TF\n'), ((2252, 2272), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['mask', '(-10)'], {}), '(mask, -10)\n', (2261, 2272), True, 'import torchvision.transforms.functional as TF\n'), ((1558, 1592), 'torch.tensor', 'torch.tensor', (['k'], {'dtype': 'torch.uint8'}), '(k, dtype=torch.uint8)\n', (1570, 1592), False, 'import torch\n')]
|
import numpy as np
def random_policy(env):
counter = 0
total_rewards = 0
reward = None
rewardTracker = []
while reward != 1:
env.render()
state, reward, done, info = env.step(env.action_space.sample())
total_rewards += reward
if done:
rewardTracker.append(total_rewards)
env.reset()
counter += 1
print("Solved in {} Steps with a average return of {}".format(counter, sum(rewardTracker) / len(rewardTracker)))
def epsilon_greedy(env, epsilon, Q, state, episode):
n_actions = env.action_space.n
if np.random.rand() > epsilon:
# adding a noise to the best action from Q
action = np.argmax(Q[state, :] + np.random.randn(1, n_actions) / (episode / n_actions))
else:
action = env.action_space.sample()
# reduce the epsilon number
epsilon -= 10 ** -5
return action, epsilon
def q_learning(env, alpha, gamma, epsilon, episodes, training_steps):
Q = np.zeros([env.observation_space.n, env.action_space.n])
reward_tracker = []
for episode in range(1, episodes + 1):
total_rewards = 0
state = env.reset()
for step in range(1, training_steps):
action, epsilon = epsilon_greedy(env, epsilon, Q, state, episode)
next_state, reward, done, info = env.step(action)
Q[state, action] += alpha * (reward + gamma * np.max(Q[next_state]) - Q[state, action])
state = next_state
total_rewards += reward
reward_tracker.append(total_rewards)
if episode % (episodes * .10) == 0 and episode != 0:
print('Epsilon {:04.3f} Episode {}'.format(epsilon, episode))
print("Average Total Return: {}".format(sum(reward_tracker) / episode))
if (sum(reward_tracker[episode - 100:episode]) / 100.0) > .78:
print('Solved after {} episodes with average return of {}'
.format(episode - 100, sum(reward_tracker[episode - 100:episode]) / 100.0))
return Q
return Q
|
[
"numpy.zeros",
"numpy.random.randn",
"numpy.random.rand",
"numpy.max"
] |
[((999, 1054), 'numpy.zeros', 'np.zeros', (['[env.observation_space.n, env.action_space.n]'], {}), '([env.observation_space.n, env.action_space.n])\n', (1007, 1054), True, 'import numpy as np\n'), ((600, 616), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (614, 616), True, 'import numpy as np\n'), ((720, 749), 'numpy.random.randn', 'np.random.randn', (['(1)', 'n_actions'], {}), '(1, n_actions)\n', (735, 749), True, 'import numpy as np\n'), ((1423, 1444), 'numpy.max', 'np.max', (['Q[next_state]'], {}), '(Q[next_state])\n', (1429, 1444), True, 'import numpy as np\n')]
|
"""Sliding windows for connectivity functions."""
from frites.io import set_log_level, logger
import numpy as np
def define_windows(times, windows=None, slwin_len=None, slwin_start=None,
slwin_stop=None, slwin_step=None, verbose=None):
"""Define temporal windows.
This function can be used to either manually define temporal windows either
automatic sliding windows. Note that every input parameters should be in
the time domain (e.g seconds or milliseconds).
Parameters
----------
times : array_like
Time vector
windows : array_like | None
Manual windows (e.g (.1, .2) or [(.1, .2), (.4, .5)]).
slwin_len : float | None
Length of each sliding (e.g .2 produces 200ms window length).
slwin_start : float | None
Time point for starting sliding windows (e.g 0.1). If None, sliding
windows will start from the first time point.
slwin_stop : float | None
Time point for ending sliding windows (e.g 1.5). If None, sliding
windows will finish at the last time point.
slwin_step : float | None
Temporal step between each temporal window (e.g .1 means that each
consecutive windows are going to be separated by 100ms). This parameter
can be used to define either overlapping or non-overlapping windows. If
None, slwin_step is going to be set to slwin_step in order to produce
consecutive non-overlapping windows.
Returns
-------
win_sample : array_like
Array of shape (n_windows, 2) of temporal indexes defining where each
window (start, finish)
mean_time : array_like
Mean time vector inside each defined window of shape (n_windows,)
See also
--------
plot_windows
"""
set_log_level(verbose)
assert isinstance(times, np.ndarray)
logger.info("Defining temporal windows")
stamp = times[1] - times[0]
# -------------------------------------------------------------------------
# build windows
if (windows is None) and (slwin_len is None):
logger.info(" No input detected. Full time window is used")
win_time = np.array([[times[0], times[-1]]])
elif windows is not None:
logger.info(" Manual definition of windows")
win_time = np.atleast_2d(windows)
elif slwin_len is not None:
# manage empty inputs
if slwin_start is None: slwin_start = times[0] # noqa
if slwin_stop is None: slwin_stop = times[-1] # noqa
if slwin_step is None: slwin_step = slwin_len + stamp # noqa
logger.info(f" Definition of sliding windows (len={slwin_len}, "
f"start={slwin_start}, stop={slwin_stop}, "
f"step={slwin_step})")
# build the sliding windows
sl_start = np.arange(slwin_start, slwin_stop - slwin_len, slwin_step)
sl_stop = np.arange(slwin_start + slwin_len, slwin_stop, slwin_step)
if len(sl_start) != len(sl_stop):
min_len = min(len(sl_start), len(sl_stop))
sl_start, sl_stop = sl_start[0:min_len], sl_stop[0:min_len]
win_time = np.c_[sl_start, sl_stop]
assert (win_time.ndim == 2) and (win_time.shape[1] == 2)
# -------------------------------------------------------------------------
# time to sample conversion
win_sample = np.zeros_like(win_time, dtype=int)
times = times.reshape(-1, 1)
for n_k, k in enumerate(win_time):
win_sample[n_k, :] = np.argmin(np.abs(times - k), axis=0)
logger.info(f" {win_sample.shape[0]} windows defined")
return win_sample, win_time.mean(1)
def plot_windows(times, win_sample, x=None, title='', r_min=-.75, r_max=.75):
"""Simple plotting function for representing windows.
Parameters
----------
times : array_like
Times vector of shape (n_times,)
win_sample : array_like
Windows in samples.
x : array_like | None
A signal to use as a background. If None, a pure sine is generated
with 100ms period is generated
title : string | ''
String title to attach to the figure
r_min, r_max : float | -.75, .75
Window are represented by squares. Those two parameters can be used to
control where box start and finish along the y-axis.
Returns
-------
ax : gca
The matplotlib current axes
See also
--------
define_windows
"""
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
if x is not None:
# plot the sine
plt.plot(times, x)
# plot the windows
win_time = times[win_sample]
r_red, r_blue = [], []
for n_k, k in enumerate(win_time):
if n_k % 2 == 0:
r_red += [Rectangle((k[0], r_min), k[1] - k[0], r_max - r_min)]
elif n_k % 2 == 1:
r_blue += [Rectangle((k[0], r_min), k[1] - k[0], r_max - r_min)]
pc_blue = PatchCollection(r_blue, alpha=.5, color='blue')
pc_red = PatchCollection(r_red, alpha=.5, color='red')
plt.gca().add_collection(pc_blue)
plt.gca().add_collection(pc_red)
plt.title(title)
plt.xlim(times[0], times[-1])
return plt.gca()
|
[
"frites.io.set_log_level",
"frites.io.logger.info",
"numpy.atleast_2d",
"numpy.abs",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"matplotlib.collections.PatchCollection",
"numpy.array",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.zeros_like",
"numpy.arange"
] |
[((1791, 1813), 'frites.io.set_log_level', 'set_log_level', (['verbose'], {}), '(verbose)\n', (1804, 1813), False, 'from frites.io import set_log_level, logger\n'), ((1859, 1899), 'frites.io.logger.info', 'logger.info', (['"""Defining temporal windows"""'], {}), "('Defining temporal windows')\n", (1870, 1899), False, 'from frites.io import set_log_level, logger\n'), ((3391, 3425), 'numpy.zeros_like', 'np.zeros_like', (['win_time'], {'dtype': 'int'}), '(win_time, dtype=int)\n', (3404, 3425), True, 'import numpy as np\n'), ((3568, 3625), 'frites.io.logger.info', 'logger.info', (['f""" {win_sample.shape[0]} windows defined"""'], {}), "(f' {win_sample.shape[0]} windows defined')\n", (3579, 3625), False, 'from frites.io import set_log_level, logger\n'), ((5020, 5068), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['r_blue'], {'alpha': '(0.5)', 'color': '"""blue"""'}), "(r_blue, alpha=0.5, color='blue')\n", (5035, 5068), False, 'from matplotlib.collections import PatchCollection\n'), ((5081, 5127), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['r_red'], {'alpha': '(0.5)', 'color': '"""red"""'}), "(r_red, alpha=0.5, color='red')\n", (5096, 5127), False, 'from matplotlib.collections import PatchCollection\n'), ((5206, 5222), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (5215, 5222), True, 'import matplotlib.pyplot as plt\n'), ((5227, 5256), 'matplotlib.pyplot.xlim', 'plt.xlim', (['times[0]', 'times[-1]'], {}), '(times[0], times[-1])\n', (5235, 5256), True, 'import matplotlib.pyplot as plt\n'), ((5269, 5278), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5276, 5278), True, 'import matplotlib.pyplot as plt\n'), ((2092, 2154), 'frites.io.logger.info', 'logger.info', (['""" No input detected. Full time window is used"""'], {}), "(' No input detected. Full time window is used')\n", (2103, 2154), False, 'from frites.io import set_log_level, logger\n'), ((2174, 2207), 'numpy.array', 'np.array', (['[[times[0], times[-1]]]'], {}), '([[times[0], times[-1]]])\n', (2182, 2207), True, 'import numpy as np\n'), ((4660, 4678), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'x'], {}), '(times, x)\n', (4668, 4678), True, 'import matplotlib.pyplot as plt\n'), ((2246, 2293), 'frites.io.logger.info', 'logger.info', (['""" Manual definition of windows"""'], {}), "(' Manual definition of windows')\n", (2257, 2293), False, 'from frites.io import set_log_level, logger\n'), ((2313, 2335), 'numpy.atleast_2d', 'np.atleast_2d', (['windows'], {}), '(windows)\n', (2326, 2335), True, 'import numpy as np\n'), ((3537, 3554), 'numpy.abs', 'np.abs', (['(times - k)'], {}), '(times - k)\n', (3543, 3554), True, 'import numpy as np\n'), ((5131, 5140), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5138, 5140), True, 'import matplotlib.pyplot as plt\n'), ((5169, 5178), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5176, 5178), True, 'import matplotlib.pyplot as plt\n'), ((2619, 2755), 'frites.io.logger.info', 'logger.info', (['f""" Definition of sliding windows (len={slwin_len}, start={slwin_start}, stop={slwin_stop}, step={slwin_step})"""'], {}), "(\n f' Definition of sliding windows (len={slwin_len}, start={slwin_start}, stop={slwin_stop}, step={slwin_step})'\n )\n", (2630, 2755), False, 'from frites.io import set_log_level, logger\n'), ((2849, 2907), 'numpy.arange', 'np.arange', (['slwin_start', '(slwin_stop - slwin_len)', 'slwin_step'], {}), '(slwin_start, slwin_stop - slwin_len, slwin_step)\n', (2858, 2907), True, 'import numpy as np\n'), ((2927, 2985), 'numpy.arange', 'np.arange', (['(slwin_start + slwin_len)', 'slwin_stop', 'slwin_step'], {}), '(slwin_start + slwin_len, slwin_stop, slwin_step)\n', (2936, 2985), True, 'import numpy as np\n'), ((4848, 4900), 'matplotlib.patches.Rectangle', 'Rectangle', (['(k[0], r_min)', '(k[1] - k[0])', '(r_max - r_min)'], {}), '((k[0], r_min), k[1] - k[0], r_max - r_min)\n', (4857, 4900), False, 'from matplotlib.patches import Rectangle\n'), ((4952, 5004), 'matplotlib.patches.Rectangle', 'Rectangle', (['(k[0], r_min)', '(k[1] - k[0])', '(r_max - r_min)'], {}), '((k[0], r_min), k[1] - k[0], r_max - r_min)\n', (4961, 5004), False, 'from matplotlib.patches import Rectangle\n')]
|
# ===================================
# Import the libraries
# ===================================
import numpy as np
from matplotlib import pylab as plt
import imaging
import utility
import os,sys
# ===================================
# Which stages to run
# ===================================
do_add_noise = False
do_black_level_correction = True
do_lens_shading_correction = True
do_bad_pixel_correction = True
do_channel_gain_white_balance = True
do_bayer_denoise = False
do_demosaic = True
do_demosaic_artifact_reduction = True
do_color_correction = True
do_gamma = True
do_chromatic_aberration_correction = True
do_tone_mapping = True
do_memory_color_enhancement = True
do_noise_reduction = True
do_sharpening = True
do_distortion_correction = False
# ===================================
# Remove all the .png files
os.system("rm images/*.png")
# ===================================
# ===================================
# raw image and set up the metadata
# ===================================
# uncomment the image_name to run it via pipeline
image_name = "DSC_1339_768x512_rggb" # image content: Rose rggb
# image_name = "DSC_1339_768x512_gbrg" # image content: Rose gbrg
# image_name = "DSC_1339_768x512_grbg" # image content: Rose grbg
# image_name = "DSC_1339_768x512_bggr" # image content: Rose bggr
# image_name = "DSC_1320_2048x2048_rggb" # image content: Potrait
# image_name = "DSC_1372_6032x4032_rggb" # image content: Downtown San Jose
# image_name = "DSC_1372_12096x6032_rgb_out_demosaic" # image content: Downtown San Jose after demosaic
# read the raw image
temp = np.fromfile("images/" + image_name + ".raw", dtype="uint16", sep="")
if (image_name == "DSC_1339_768x512_rggb"):
temp = temp.reshape([512, 768])
raw = imaging.ImageInfo("1339_768x512_rggb", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("rggb")
raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1339_768x512_gbrg"):
temp = temp.reshape([512, 768])
raw = imaging.ImageInfo("1339_768x512_gbrg", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("gbrg")
raw.set_channel_gain((1.0, 1.34375, 1.94921875, 1.0)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1339_768x512_grbg"):
temp = temp.reshape([512, 768])
raw = imaging.ImageInfo("1339_768x512_grbg", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("grbg")
raw.set_channel_gain((1.0, 1.94921875, 1.34375, 1.0)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1339_768x512_bggr"):
temp = temp.reshape([512, 768])
raw = imaging.ImageInfo("1339_768x512_bggr", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("bggr")
raw.set_channel_gain((1.34375, 1.0, 1.0, 1.94921875,)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1320_2048x2048_rggb"):
temp = temp.reshape([2048, 2048])
raw = imaging.ImageInfo("1320_2048x2048_rggb", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("rggb")
raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1372_6032x4032_rggb"):
temp = temp.reshape([4032, 6032])
raw = imaging.ImageInfo("DSC_1372_6032x4032_rggb", temp)
raw.set_color_space("raw")
raw.set_bayer_pattern("rggb")
raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
data = raw.data
elif (image_name == "DSC_1372_12096x6032_rgb_out_demosaic"):
temp = temp.reshape([12096, 6032])
temp = np.float32(temp)
data = np.empty((4032, 6032, 3), dtype=np.float32)
data[:, :, 0] = temp[0:4032, :]
data[:, :, 1] = temp[4032 : 2*4032, :]
data[:, :, 2] = temp[2*4032 : 3*4032, :]
raw = imaging.ImageInfo("DSC_1372_12096x6032_rgb_out_demosaic", data)
raw.set_color_space("raw")
raw.set_bayer_pattern("rggb")
raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)
raw.set_black_level((600, 600, 600, 600))
raw.set_white_level((15520, 15520, 15520, 15520))
# the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020, -.2890, -.0715],\
[-.4535, 1.2436, .2348],\
[-.0934, .1919, .7086]])
else:
print("Warning! image_name not recognized.")
# ===================================
# Add noise
# ===================================
if do_add_noise:
noise_mean = 0
noise_standard_deviation = 100
seed = 100
clip_range = [600, 65535]
data = utility.synthetic_image_generate(\
raw.get_width(), raw.get_height()).create_noisy_image(\
data, noise_mean, noise_standard_deviation, seed, clip_range)
else:
pass
# ===================================
# Black level correction
# ===================================
if do_black_level_correction:
data = imaging.black_level_correction(data, \
raw.get_black_level(),\
raw.get_white_level(),\
[0, 2**raw.get_bit_depth() - 1])
utility.imsave(data, "images/" + image_name + "_out_black_level_correction.png", "uint16")
else:
pass
# ===================================
# Lens shading correction
# ===================================
if do_lens_shading_correction:
# normally dark_current_image and flat_field_image are
# captured in the image quality lab using flat field chart
# here we are synthetically generating thouse two images
dark_current_image, flat_field_image = utility.synthetic_image_generate(\
raw.get_width(), raw.get_height()).create_lens_shading_correction_images(\
0, 65535, 40000)
# save the dark_current_image and flat_field_image for viewing
utility.imsave(dark_current_image, "images/" + image_name + "_dark_current_image.png", "uint16")
utility.imsave(flat_field_image, "images/" + image_name + "_flat_field_image.png", "uint16")
data = imaging.lens_shading_correction(data).flat_field_compensation(\
dark_current_image, flat_field_image)
# data = lsc.approximate_mathematical_compensation([0.01759, -28.37, -13.36])
utility.imsave(data, "images/" + image_name + "_out_lens_shading_correction.png", "uint16")
else:
pass
# ===================================
# Bad pixel correction
# ===================================
if do_bad_pixel_correction:
neighborhood_size = 3
data = imaging.bad_pixel_correction(data, neighborhood_size)
utility.imsave(data, "images/" + image_name + "_out_bad_pixel_correction.png", "uint16")
else:
pass
# ===================================
# Channel gain for white balance
# ===================================
if do_channel_gain_white_balance:
data = imaging.channel_gain_white_balance(data,\
raw.get_channel_gain())
utility.imsave(data, "images/" + image_name + "_out_channel_gain_white_balance.png", "uint16")
else:
pass
# ===================================
# Bayer denoising
# ===================================
if do_bayer_denoise:
# bayer denoising parameters
neighborhood_size = 5
initial_noise_level = 65535 * 10 / 100
hvs_min = 1000
hvs_max = 2000
clip_range = [0, 65535]
threshold_red_blue = 1300
# data is the denoised output, ignoring the second output
data, _ = imaging.bayer_denoising(data).utilize_hvs_behavior(\
raw.get_bayer_pattern(), initial_noise_level, hvs_min, hvs_max, threshold_red_blue, clip_range)
utility.imsave(data, "images/" + image_name + "_out_bayer_denoising.png", "uint16")
# utility.imsave(np.clip(texture_degree_debug*65535, 0, 65535), "images/" + image_name + "_out_texture_degree_debug.png", "uint16")
else:
pass
# ===================================
# Demosacing
# ===================================
if do_demosaic:
#data = imaging.demosaic(data, raw.get_bayer_pattern()).mhc(False)
data = imaging.demosaic(data, raw.get_bayer_pattern()).directionally_weighted_gradient_based_interpolation()
utility.imsave(data, "images/" + image_name + "_out_demosaic.png", "uint16")
else:
pass
# ===================================
# Demosaic artifact reduction
# ===================================
if do_demosaic_artifact_reduction:
data = imaging.demosaic(data).post_process_local_color_ratio(0.80 * 65535)
utility.imsave(data, "images/" + image_name + "_out_local_color_ratio.png", "uint16")
edge_detection_kernel_size = 5
edge_threshold = 0.05
# first output is main output, second output is edge_location is a debug output
data, _ = imaging.demosaic(data).post_process_median_filter(edge_detection_kernel_size, edge_threshold)
utility.imsave(data, "images/" + image_name + "_out_median_filter.png", "uint16")
# utility.imsave(edge_location*65535, "images/" + image_name + "_edge_location.png", "uint16")
else:
pass
# ===================================
# Color correction
# ===================================
if do_color_correction:
data = imaging.color_correction(data, raw.get_color_matrix()).apply_cmatrix()
utility.imsave(data, "images/" + image_name + "_out_color_correction.png", "uint16")
else:
pass
# ===================================
# Gamma
# ===================================
if do_gamma:
# brightening
data = imaging.nonlinearity(data, "brightening").luma_adjustment(80.)
# gamma by value
#data = imaging.nonlinearity(data, "gamma").by_value(1/2.2, [0, 65535])
# gamma by table
# data = imaging.nonlinearity(data, "gamma").by_table("tables/gamma_2.4.txt", "gamma", [0, 65535])
# gamma by value
data = imaging.nonlinearity(data, "gamma").by_equation(-0.9, -8.0, [0, 65535])
utility.imsave(data, "images/" + image_name + "_out_gamma.png", "uint16")
else:
pass
# ===================================
# Chromatic aberration correction
# ===================================
if do_chromatic_aberration_correction:
nsr_threshold = 90.
cr_threshold = 6425./2
data = imaging.chromatic_aberration_correction(data).purple_fringe_removal(nsr_threshold, cr_threshold)
utility.imsave(data, "images/" + image_name + "_out_purple_fringe_removal.png", "uint16")
else:
pass
# ===================================
# Tone mapping
# ===================================
if do_tone_mapping:
data = imaging.tone_mapping(data).nonlinear_masking(1.0)
utility.imsave(data, "images/" + image_name + "_out_tone_mapping_nl_masking.png", "uint16")
# data = imaging.tone_mapping(data).dynamic_range_compression("normal", [-25., 260.], [0, 65535])
# utility.imsave(data, "images/" + image_name + "_out_tone_mapping_drc.png", "uint16")
else:
pass
# ===================================
# Memory color enhancement
# ===================================
if do_memory_color_enhancement:
# target_hue = [30., -115., 100.]
# hue_preference = [45., -90., 130.]
# hue_sigma = [20., 10., 5.]
# is_both_side = [True, False, False]
# multiplier = [0.6, 0.6, 0.6]
# chroma_preference = [25., 17., 30.]
# chroma_sigma = [10., 10., 5.]
target_hue = [30., -125., 100.]
hue_preference = [20., -118., 130.]
hue_sigma = [20., 10., 5.]
is_both_side = [True, False, False]
multiplier = [0.6, 0.6, 0.6]
chroma_preference = [25., 14., 30.]
chroma_sigma = [10., 10., 5.]
data = imaging.memory_color_enhancement(data).by_hue_squeeze(target_hue,\
hue_preference,\
hue_sigma,\
is_both_side,\
multiplier,\
chroma_preference,\
chroma_sigma)
utility.imsave(data, "images/" + image_name + "_out_memory_color_enhancement.png", "uint16")
else:
pass
# ===================================
# Noise reduction
# ===================================
if do_noise_reduction:
# sigma filter parameters
neighborhood_size = 7
sigma = [1000, 500, 500]
data = imaging.noise_reduction(data).sigma_filter(neighborhood_size, sigma)
utility.imsave(data, "images/" + image_name + "_out_noise_reduction.png", "uint16")
else:
pass
# ===================================
# Sharpening
# ===================================
if do_sharpening:
data = imaging.sharpening(data).unsharp_masking()
utility.imsave(data, "images/" + image_name + "_out_sharpening.png", "uint16")
else:
pass
# ===================================
# Distortion correction
# ===================================
if do_distortion_correction:
correction_type="barrel-1"
strength=0.5
zoom_type="fit"
clip_range=[0, 65535]
data = imaging.distortion_correction(data).empirical_correction(correction_type, strength, zoom_type, clip_range)
utility.imsave(data, "images/" + image_name + "_out_distortion_correction.png", "uint16")
else:
pass
|
[
"numpy.fromfile",
"imaging.bad_pixel_correction",
"imaging.chromatic_aberration_correction",
"imaging.tone_mapping",
"imaging.sharpening",
"imaging.distortion_correction",
"imaging.memory_color_enhancement",
"imaging.lens_shading_correction",
"imaging.bayer_denoising",
"numpy.empty",
"imaging.ImageInfo",
"utility.imsave",
"os.system",
"imaging.demosaic",
"imaging.nonlinearity",
"numpy.float32",
"imaging.noise_reduction"
] |
[((827, 855), 'os.system', 'os.system', (['"""rm images/*.png"""'], {}), "('rm images/*.png')\n", (836, 855), False, 'import os, sys\n'), ((1654, 1722), 'numpy.fromfile', 'np.fromfile', (["('images/' + image_name + '.raw')"], {'dtype': '"""uint16"""', 'sep': '""""""'}), "('images/' + image_name + '.raw', dtype='uint16', sep='')\n", (1665, 1722), True, 'import numpy as np\n'), ((1816, 1860), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_rggb"""', 'temp'], {}), "('1339_768x512_rggb', temp)\n", (1833, 1860), False, 'import imaging\n'), ((7897, 7991), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_black_level_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_black_level_correction.png', 'uint16')\n", (7911, 7991), False, 'import utility\n'), ((8602, 8702), 'utility.imsave', 'utility.imsave', (['dark_current_image', "('images/' + image_name + '_dark_current_image.png')", '"""uint16"""'], {}), "(dark_current_image, 'images/' + image_name +\n '_dark_current_image.png', 'uint16')\n", (8616, 8702), False, 'import utility\n'), ((8703, 8799), 'utility.imsave', 'utility.imsave', (['flat_field_image', "('images/' + image_name + '_flat_field_image.png')", '"""uint16"""'], {}), "(flat_field_image, 'images/' + image_name +\n '_flat_field_image.png', 'uint16')\n", (8717, 8799), False, 'import utility\n'), ((9001, 9096), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_lens_shading_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_lens_shading_correction.png', 'uint16')\n", (9015, 9096), False, 'import utility\n'), ((9274, 9327), 'imaging.bad_pixel_correction', 'imaging.bad_pixel_correction', (['data', 'neighborhood_size'], {}), '(data, neighborhood_size)\n', (9302, 9327), False, 'import imaging\n'), ((9332, 9424), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_bad_pixel_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_bad_pixel_correction.png', 'uint16')\n", (9346, 9424), False, 'import utility\n'), ((9707, 9805), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_channel_gain_white_balance.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_channel_gain_white_balance.png', 'uint16')\n", (9721, 9805), False, 'import utility\n'), ((10367, 10454), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_bayer_denoising.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_bayer_denoising.png',\n 'uint16')\n", (10381, 10454), False, 'import utility\n'), ((10898, 10974), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_demosaic.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_demosaic.png', 'uint16')\n", (10912, 10974), False, 'import utility\n'), ((11216, 11305), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_local_color_ratio.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_local_color_ratio.png',\n 'uint16')\n", (11230, 11305), False, 'import utility\n'), ((11560, 11645), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_median_filter.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_median_filter.png',\n 'uint16')\n", (11574, 11645), False, 'import utility\n'), ((11964, 12052), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_color_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_color_correction.png',\n 'uint16')\n", (11978, 12052), False, 'import utility\n'), ((12588, 12661), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_gamma.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_gamma.png', 'uint16')\n", (12602, 12661), False, 'import utility\n'), ((12995, 13088), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_purple_fringe_removal.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_purple_fringe_removal.png', 'uint16')\n", (13009, 13088), False, 'import utility\n'), ((13279, 13374), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_tone_mapping_nl_masking.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_tone_mapping_nl_masking.png', 'uint16')\n", (13293, 13374), False, 'import utility\n'), ((14807, 14903), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_memory_color_enhancement.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_memory_color_enhancement.png', 'uint16')\n", (14821, 14903), False, 'import utility\n'), ((15206, 15293), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_noise_reduction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_noise_reduction.png',\n 'uint16')\n", (15220, 15293), False, 'import utility\n'), ((15474, 15552), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_sharpening.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_sharpening.png', 'uint16')\n", (15488, 15552), False, 'import utility\n'), ((15917, 16010), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_distortion_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_distortion_correction.png', 'uint16')\n", (15931, 16010), False, 'import utility\n'), ((2543, 2587), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_gbrg"""', 'temp'], {}), "('1339_768x512_gbrg', temp)\n", (2560, 2587), False, 'import imaging\n'), ((3270, 3314), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_grbg"""', 'temp'], {}), "('1339_768x512_grbg', temp)\n", (3287, 3314), False, 'import imaging\n'), ((8808, 8845), 'imaging.lens_shading_correction', 'imaging.lens_shading_correction', (['data'], {}), '(data)\n', (8839, 8845), False, 'import imaging\n'), ((10209, 10238), 'imaging.bayer_denoising', 'imaging.bayer_denoising', (['data'], {}), '(data)\n', (10232, 10238), False, 'import imaging\n'), ((11144, 11166), 'imaging.demosaic', 'imaging.demosaic', (['data'], {}), '(data)\n', (11160, 11166), False, 'import imaging\n'), ((11462, 11484), 'imaging.demosaic', 'imaging.demosaic', (['data'], {}), '(data)\n', (11478, 11484), False, 'import imaging\n'), ((12192, 12233), 'imaging.nonlinearity', 'imaging.nonlinearity', (['data', '"""brightening"""'], {}), "(data, 'brightening')\n", (12212, 12233), False, 'import imaging\n'), ((12511, 12546), 'imaging.nonlinearity', 'imaging.nonlinearity', (['data', '"""gamma"""'], {}), "(data, 'gamma')\n", (12531, 12546), False, 'import imaging\n'), ((12893, 12938), 'imaging.chromatic_aberration_correction', 'imaging.chromatic_aberration_correction', (['data'], {}), '(data)\n', (12932, 12938), False, 'import imaging\n'), ((13225, 13251), 'imaging.tone_mapping', 'imaging.tone_mapping', (['data'], {}), '(data)\n', (13245, 13251), False, 'import imaging\n'), ((14254, 14292), 'imaging.memory_color_enhancement', 'imaging.memory_color_enhancement', (['data'], {}), '(data)\n', (14286, 14292), False, 'import imaging\n'), ((15132, 15161), 'imaging.noise_reduction', 'imaging.noise_reduction', (['data'], {}), '(data)\n', (15155, 15161), False, 'import imaging\n'), ((15426, 15450), 'imaging.sharpening', 'imaging.sharpening', (['data'], {}), '(data)\n', (15444, 15450), False, 'import imaging\n'), ((15806, 15841), 'imaging.distortion_correction', 'imaging.distortion_correction', (['data'], {}), '(data)\n', (15835, 15841), False, 'import imaging\n'), ((3997, 4041), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_bggr"""', 'temp'], {}), "('1339_768x512_bggr', temp)\n", (4014, 4041), False, 'import imaging\n'), ((4729, 4775), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1320_2048x2048_rggb"""', 'temp'], {}), "('1320_2048x2048_rggb', temp)\n", (4746, 4775), False, 'import imaging\n'), ((5463, 5513), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""DSC_1372_6032x4032_rggb"""', 'temp'], {}), "('DSC_1372_6032x4032_rggb', temp)\n", (5480, 5513), False, 'import imaging\n'), ((6215, 6231), 'numpy.float32', 'np.float32', (['temp'], {}), '(temp)\n', (6225, 6231), True, 'import numpy as np\n'), ((6243, 6286), 'numpy.empty', 'np.empty', (['(4032, 6032, 3)'], {'dtype': 'np.float32'}), '((4032, 6032, 3), dtype=np.float32)\n', (6251, 6286), True, 'import numpy as np\n'), ((6422, 6485), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""DSC_1372_12096x6032_rgb_out_demosaic"""', 'data'], {}), "('DSC_1372_12096x6032_rgb_out_demosaic', data)\n", (6439, 6485), False, 'import imaging\n')]
|
import os
import sys
import imp
import argparse
import time
import math
import numpy as np
from utils import utils
from utils.imageprocessing import preprocess
from utils.dataset import Dataset
from network import Network
from evaluation.lfw import LFWTest
def main(args):
paths = [
r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0002.jpg',
r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0003.jpg',
r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\a-000013.jpg',
r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg',
r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0002.jpg',
r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg',
r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0003.jpg',
r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg',
]
print('%d images to load.' % len(paths))
assert(len(paths)>0)
# Load model files and config file
network = Network()
network.load_model(args.model_dir)
# network.config.preprocess_train = []
# network.config.preprocess_test = []
images = preprocess(paths, network.config, False)
import cv2
# images = np.array([cv2.resize(img, (96, 96)) for img in images])
# images = (images - 128.) / 128.
# images = images[..., ::-1]
print(images.shape)
# print(images[0,:5,:5,0])
# Run forward pass to calculate embeddings
mu, sigma_sq = network.extract_feature(images, args.batch_size, verbose=True)
print(mu.shape, sigma_sq.shape)
print('sigma_sq', np.max(sigma_sq), np.min(sigma_sq), np.mean(sigma_sq), np.exp(np.mean(np.log(sigma_sq))))
log_sigma_sq = np.log(sigma_sq)
print('log_sigma_sq', np.max(log_sigma_sq), np.min(log_sigma_sq), np.mean(log_sigma_sq))
# print('sigma_sq', sigma_sq)
feat_pfe = np.concatenate([mu, sigma_sq], axis=1)
score = utils.pair_cosin_score(mu[::2], mu[1::2])
print(score)
score = utils.pair_MLS_score(feat_pfe[::2], feat_pfe[1::2])
print(score)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--model_dir", help="The path to the pre-trained model directory",
type=str,
default=r'D:\chenkai\Probabilistic-Face-Embeddings-master\log\resface64_relu_msarcface_am_PFE/20191229-172304-iter15')
parser.add_argument("--batch_size", help="Number of images per mini batch",
type=int, default=128)
args = parser.parse_args()
main(args)
|
[
"numpy.mean",
"utils.utils.pair_MLS_score",
"argparse.ArgumentParser",
"numpy.log",
"numpy.max",
"network.Network",
"utils.utils.pair_cosin_score",
"numpy.concatenate",
"numpy.min",
"utils.imageprocessing.preprocess"
] |
[((1241, 1250), 'network.Network', 'Network', ([], {}), '()\n', (1248, 1250), False, 'from network import Network\n'), ((1388, 1428), 'utils.imageprocessing.preprocess', 'preprocess', (['paths', 'network.config', '(False)'], {}), '(paths, network.config, False)\n', (1398, 1428), False, 'from utils.imageprocessing import preprocess\n'), ((1939, 1955), 'numpy.log', 'np.log', (['sigma_sq'], {}), '(sigma_sq)\n', (1945, 1955), True, 'import numpy as np\n'), ((2099, 2137), 'numpy.concatenate', 'np.concatenate', (['[mu, sigma_sq]'], {'axis': '(1)'}), '([mu, sigma_sq], axis=1)\n', (2113, 2137), True, 'import numpy as np\n'), ((2151, 2192), 'utils.utils.pair_cosin_score', 'utils.pair_cosin_score', (['mu[::2]', 'mu[1::2]'], {}), '(mu[::2], mu[1::2])\n', (2173, 2192), False, 'from utils import utils\n'), ((2223, 2274), 'utils.utils.pair_MLS_score', 'utils.pair_MLS_score', (['feat_pfe[::2]', 'feat_pfe[1::2]'], {}), '(feat_pfe[::2], feat_pfe[1::2])\n', (2243, 2274), False, 'from utils import utils\n'), ((2334, 2359), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2357, 2359), False, 'import argparse\n'), ((1830, 1846), 'numpy.max', 'np.max', (['sigma_sq'], {}), '(sigma_sq)\n', (1836, 1846), True, 'import numpy as np\n'), ((1848, 1864), 'numpy.min', 'np.min', (['sigma_sq'], {}), '(sigma_sq)\n', (1854, 1864), True, 'import numpy as np\n'), ((1866, 1883), 'numpy.mean', 'np.mean', (['sigma_sq'], {}), '(sigma_sq)\n', (1873, 1883), True, 'import numpy as np\n'), ((1982, 2002), 'numpy.max', 'np.max', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (1988, 2002), True, 'import numpy as np\n'), ((2004, 2024), 'numpy.min', 'np.min', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (2010, 2024), True, 'import numpy as np\n'), ((2026, 2047), 'numpy.mean', 'np.mean', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (2033, 2047), True, 'import numpy as np\n'), ((1900, 1916), 'numpy.log', 'np.log', (['sigma_sq'], {}), '(sigma_sq)\n', (1906, 1916), True, 'import numpy as np\n')]
|
import AgentControl
import Config
import Memory
import numpy as np
import itertools
class Agent:
# Role of Agent class is to coordinate between AgentControll where we do all calculations
# and Memory where we store all of the data
def __init__(self, state_size, action_size, batch_size):
self.agent_control = AgentControl.AgentControl(state_size=state_size, action_size=action_size)
self.memory = Memory.Memory(state_size, action_size, batch_size)
self.policy_loss_m = []
self.critic_loss_m = []
self.policy_loss_mm = [0] * 100
self.critic_loss_mm = [0] * 100
self.max_reward = -300
self.ep_count = 0
def set_optimizer_lr_eps(self, n_step):
self.agent_control.set_optimizer_lr_eps(n_step)
def get_action(self, state):
actions, actions_logprob = self.agent_control.get_action(state)
return actions.cpu().detach().numpy(), actions_logprob
def add_to_memory(self, state, action, actions_logprob, new_state, reward, done, n_batch_step):
self.memory.add(state, action, actions_logprob, new_state, reward, done, n_batch_step)
def calculate_old_value_state(self):
# Get NN output from collected states and pass it to the memory
self.memory.set_old_value_state(self.agent_control.get_critic_value(self.memory.states).squeeze(-1).detach())
def calculate_advantage(self):
# For basic advantage function we have to calculate future rewards we got from each state, where reward from
# last state is estimation (since we only know rewards in steps we took, not after), discount them and
# subtract from baseline which in this case will be estimated value of each state.
# GAE advantage gives us to decide we want each state advantage to be calculated with
# reward + estimate(next state) - estimate(state) which has low variance but high bias or with
# reward + gamma*next_reward + ... + gamma^n * estimate(last next state) - estimate(state) which has high
# variance but low bias. We can decide to calculate advantage with somethig between those two and Config.LAMBDA
# will be hyperparameter for that
values = self.agent_control.get_critic_value(self.memory.states).squeeze(-1).detach()
if Config.GAE:
next_values = self.agent_control.get_critic_value(self.memory.new_states).squeeze(-1).detach()
self.memory.calculate_gae_advantage(values, next_values)
else:
next_value = self.agent_control.get_critic_value(self.memory.new_states[-1]).squeeze(-1).detach()
self.memory.calculate_advantage(next_value, values)
def update(self, indices):
# Main PPO point is updating policy NN. This is done by calculating derivative of loss function and doing
# gradient descent. First we have to calculate ratio. Second to find minimum between ratio*advantage and
# clipped_ratio*advantage. Third to find mean of Config.MINIBATCH_SIZE losses.
# To calculate ratio we need new and old action probability. We already have old when we fed states to
# policy NN when we wanted to get action from it. We can get new action probabilities if we give same states
# but also actions we got. With states NN can create Normal distribution and with action he will sample the same
# part of distribution, but now with different probability because Normal distribution is different.
new_action_logprob, entropy = self.agent_control.calculate_logprob(self.memory.states[indices], self.memory.actions[indices])
ratios = self.agent_control.calculate_ratio(new_action_logprob, self.memory.action_logprobs[indices])
policy_loss = self.agent_control.update_policy(self.memory.advantages[indices], ratios, entropy)
# Similar to ratio in policy loss, we also clipped values from critic. For that we need old_value_state which
# represent old estimate of states before updates.
critic_loss = self.agent_control.update_critic(self.memory.gt[indices], self.memory.states[indices], self.memory.old_value_state[indices])
# Calculating mean losses for statistics
self.policy_loss_m.append(policy_loss.detach().item())
self.critic_loss_m.append(critic_loss.detach().item())
def record_results(self, n_step, writer, env):
self.max_reward = np.maximum(self.max_reward, np.max(env.return_queue))
self.policy_loss_mm[n_step % 100] = np.mean(self.policy_loss_m)
self.critic_loss_mm[n_step % 100] = np.mean(self.critic_loss_m)
print("Step " + str(n_step) + "/" + str(Config.NUMBER_OF_STEPS) + " Mean 100 policy loss: " + str(
np.round(np.mean(self.policy_loss_mm[:min(n_step + 1, 100)]), 4)) + " Mean 100 critic loss: " + str(
np.round(np.mean(self.critic_loss_mm[:min(n_step + 1, 100)]), 4)) + " Max reward: " + str(
np.round(self.max_reward, 2)) + " Mean 100 reward: " + str(
np.round(np.mean(env.return_queue), 2)) + " Last rewards: " + str(
np.round(list(itertools.islice(env.return_queue, min(env.episode_count, 100)-(env.episode_count-self.ep_count), min(env.episode_count, 100))), 2)) + " Ep" + str(env.episode_count))
if Config.WRITER_FLAG:
writer.add_scalar('pg_loss', np.mean(self.policy_loss_m), n_step)
writer.add_scalar('vl_loss', np.mean(self.critic_loss_m), n_step)
writer.add_scalar('rew', env.return_queue[-1], n_step)
writer.add_scalar('100rew', np.mean(env.return_queue), n_step)
self.critic_loss_m = []
self.policy_loss_m = []
self.ep_count = env.episode_count
|
[
"numpy.mean",
"AgentControl.AgentControl",
"Memory.Memory",
"numpy.max",
"numpy.round"
] |
[((340, 413), 'AgentControl.AgentControl', 'AgentControl.AgentControl', ([], {'state_size': 'state_size', 'action_size': 'action_size'}), '(state_size=state_size, action_size=action_size)\n', (365, 413), False, 'import AgentControl\n'), ((437, 487), 'Memory.Memory', 'Memory.Memory', (['state_size', 'action_size', 'batch_size'], {}), '(state_size, action_size, batch_size)\n', (450, 487), False, 'import Memory\n'), ((4587, 4614), 'numpy.mean', 'np.mean', (['self.policy_loss_m'], {}), '(self.policy_loss_m)\n', (4594, 4614), True, 'import numpy as np\n'), ((4660, 4687), 'numpy.mean', 'np.mean', (['self.critic_loss_m'], {}), '(self.critic_loss_m)\n', (4667, 4687), True, 'import numpy as np\n'), ((4516, 4540), 'numpy.max', 'np.max', (['env.return_queue'], {}), '(env.return_queue)\n', (4522, 4540), True, 'import numpy as np\n'), ((5437, 5464), 'numpy.mean', 'np.mean', (['self.policy_loss_m'], {}), '(self.policy_loss_m)\n', (5444, 5464), True, 'import numpy as np\n'), ((5516, 5543), 'numpy.mean', 'np.mean', (['self.critic_loss_m'], {}), '(self.critic_loss_m)\n', (5523, 5543), True, 'import numpy as np\n'), ((5662, 5687), 'numpy.mean', 'np.mean', (['env.return_queue'], {}), '(env.return_queue)\n', (5669, 5687), True, 'import numpy as np\n'), ((5109, 5134), 'numpy.mean', 'np.mean', (['env.return_queue'], {}), '(env.return_queue)\n', (5116, 5134), True, 'import numpy as np\n'), ((5027, 5055), 'numpy.round', 'np.round', (['self.max_reward', '(2)'], {}), '(self.max_reward, 2)\n', (5035, 5055), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import numpy as np
import speechpy
from scipy.io import wavfile
from python_speech_features import mfcc
class PythonMFCCFeatureExtraction():
def __init__(self):
pass
def audio2features(self, input_path):
(rate, sig) = wavfile.read(input_path)
mfcc_feat = mfcc(sig, dither=0, highfreq=7700, useEnergy=True, wintype='povey', numcep=23)
# TODO temporarily add 2 feats to meet Kaldi_mfcc_features_extraction API
mfcc_feat = np.append(mfcc_feat, [mfcc_feat[-1]], axis=0)
mfcc_feat = np.append(mfcc_feat, [mfcc_feat[-1]], axis=0)
mfcc_cmvn = speechpy.processing.cmvnw(mfcc_feat, win_size=301, variance_normalization=False)
return mfcc_cmvn.astype(np.float32)
|
[
"python_speech_features.mfcc",
"speechpy.processing.cmvnw",
"scipy.io.wavfile.read",
"numpy.append"
] |
[((270, 294), 'scipy.io.wavfile.read', 'wavfile.read', (['input_path'], {}), '(input_path)\n', (282, 294), False, 'from scipy.io import wavfile\n'), ((315, 393), 'python_speech_features.mfcc', 'mfcc', (['sig'], {'dither': '(0)', 'highfreq': '(7700)', 'useEnergy': '(True)', 'wintype': '"""povey"""', 'numcep': '(23)'}), "(sig, dither=0, highfreq=7700, useEnergy=True, wintype='povey', numcep=23)\n", (319, 393), False, 'from python_speech_features import mfcc\n'), ((496, 541), 'numpy.append', 'np.append', (['mfcc_feat', '[mfcc_feat[-1]]'], {'axis': '(0)'}), '(mfcc_feat, [mfcc_feat[-1]], axis=0)\n', (505, 541), True, 'import numpy as np\n'), ((562, 607), 'numpy.append', 'np.append', (['mfcc_feat', '[mfcc_feat[-1]]'], {'axis': '(0)'}), '(mfcc_feat, [mfcc_feat[-1]], axis=0)\n', (571, 607), True, 'import numpy as np\n'), ((628, 713), 'speechpy.processing.cmvnw', 'speechpy.processing.cmvnw', (['mfcc_feat'], {'win_size': '(301)', 'variance_normalization': '(False)'}), '(mfcc_feat, win_size=301, variance_normalization=False\n )\n', (653, 713), False, 'import speechpy\n')]
|
import torch
from torch import nn
import torch.nn.functional as nf
from torch.nn import init
from torch.autograd import Variable
import numpy as np
from chainer.links.loss.hierarchical_softmax import TreeParser
#class HSM(nn.Module):
# def __init__(self, input_size, vocab_size):
class HSBad(nn.Module):
def __init__(self, input_size, n_vocab):
super(HSM, self).__init__()
self.input_size = input_size
self.n_vocab = n_vocab + 3
self.l2v = nn.Linear(
in_features = self.input_size,
out_features = self.n_vocab
)
def init_params(self):
pass
def __call__(self, x, t):
v = self.l2v(x)
loss = nf.cross_entropy(v, t)
return loss
class HSFil(nn.Module):
def __init__(self, input_size, huff_tree):
super(HSM, self).__init__()
self.input_size = input_size
self.tp = TreeParser()
self.tp.parse(huff_tree)
self.n_decisions = self.tp.size()
# self.decs = nn.Embedding(
# num_embeddings = self.n_decisions,
# embedding_dim = self.input_size
# )
self.decs = nn.Parameter(
torch.Tensor(self.n_decisions, self.input_size)
)
paths_d = self.tp.get_paths()
codes_d = self.tp.get_codes()
self.n_vocab = max(paths_d.keys()) + 1
self.paths = [paths_d[i] for i in range(self.n_vocab)]
self.codes = [torch.from_numpy(codes_d[i]) for i in range(self.n_vocab)]
self.lens = [len(path) for path in self.paths]
self.begins = np.cumsum([0.0] + self.lens[:-1])
def init_params(self):
g_paths = [torch.from_numpy(path).cuda().long() for path in self.paths]
# g_paths = torch.from_numpy(np.concatenate(self.paths)).cuda().long()
self.path_mats = [self.decs[g_path].cpu() for g_path in g_paths]
def __call__(self, x, t):
# import pdb; pdb.set_trace()
curr_path_mats = [self.path_mats[i] for i in t]
vv = [pm.cuda().mv(x_i) for pm, x_i in zip(curr_path_mats, x)]
loss = -nf.logsigmoid(torch.cat(vv)).sum()/x.size()[0]
# r_paths = []
# r_codes = []
# r_xs = []
# paths = torch.cat([self.paths[t_i] for t_i in t])
# codes = torch.cat([self.codes[t_i] for t_i in t])
# import pdb; pdb.set_trace()
# for x_i, t_i in zip(x, t):
# path, code = self.paths[t_i], self.codes[t_i]
# r_paths.append(self.paths[t_i])
# r_codes.append(self.codes[t_i])
# r_xs.append(x_i.repeat(len(path), 1))
## r_xs.append(x_i.expand(len(path), self.input_size))
# #g_paths = Variable(torch.from_numpy(np.concatenate(r_paths)).long().cuda(), requires_grad=False)
## g_codes = Variable(torch.from_numpy(np.concatenate(r_codes)).cuda(), requires_grad=False)
# g_xs = torch.cat(r_xs)
## loss = nf.binary_cross_entropy(self.decs(g_paths) * g_xs, g_codes, size_average=False)
# loss = nf.logsigmoid((self.decs(g_paths) * g_xs).sum(1) * g_codes).sum()/x.size()[0]
return loss
class HSM(nn.Module):
def __init__(self, input_size, huff_tree):
super(HSM, self).__init__()
self.input_size = input_size
self.tp = TreeParser()
self.tp.parse(huff_tree)
self.n_decisions = self.tp.size()
# self.decs = nn.Linear(
# in_features = self.input_size,
# out_features = self.n_decisions
# )
# self.decs = nn.Parameter(
# torch.Tensor(self.n_decisions, self.input_size)
# )
self.decs = nn.Embedding(
num_embeddings = self.n_decisions,
embedding_dim = self.input_size
)
self.paths_d = self.tp.get_paths()
self.codes_d = self.tp.get_codes()
self.max_path = max([len(v) for v in self.paths_d.values()])
self.max_code = max([len(v) for v in self.codes_d.values()])
self.n_vocab = max(self.paths_d.keys()) + 1
def init_params(self):
# init.kaiming_normal(self.decs)
self.paths = [self.paths_d[i] for i in range(self.n_vocab)]
self.paths = [np.pad(path, (0, max(0, self.max_path - len(path))), mode='constant') for path in self.paths]
self.paths = torch.stack([torch.from_numpy(path) for path in self.paths], 0).long().cuda()
self.codes = [self.codes_d[i] for i in range(self.n_vocab)]
self.codes = [np.pad(code, (0, max(0, self.max_code - len(code))), mode='constant') for code in self.codes]
self.codes = torch.stack([torch.from_numpy(code) for code in self.codes], 0).cuda()
def __call__(self, x, t):
# import pdb; pdb.set_trace()
g_t = torch.from_numpy(t).cuda().long()
ws = self.decs(Variable(self.paths[g_t]))
# ws = self.decs(self.paths[t].view(-1)).view(x.size()[0], self.max_path, self.input_size)
scores = ws.bmm(x.unsqueeze(2)).squeeze() * Variable(self.codes[g_t])
nz_mask = scores.ne(0).detach()
loss = -nf.logsigmoid(scores.masked_select(nz_mask)).sum()/x.size()[0]
# ws = [self.decs[self.paths[t_i]] * self.codes[t_i] for t_i in t]
# ws = torch.cat([self.decs[self.paths[t_i]].mv(x_i) for t_i, x_i in zip(t, x)])
# cs = Variable(torch.cat([self.codes[t_i] for t_i in t]))
# loss = -nf.logsigmoid(ws * cs).sum()/x.size()[0]
return loss
class HSFail(nn.Module):
def __init__(self, input_size, vocab_size, branch_factor):
super(HSM, self).__init__()
self.input_size = input_size
self.vocab_size = vocab_size
self.branch_factor = branch_factor
self.level1 = nn.Linear(
in_features = self.input_size,
out_features = self.branch_factor
)
self.level2_w = nn.Parameter(
torch.Tensor(self.branch_factor, self.branch_factor, self.input_size)
)
# self.level2_b = nn.Parameter(
# torch.Tensor(self.branch_factor, self.branch_factor)
# )
def init_params(self):
init.kaiming_normal(self.level2_w)
# init.kaiming_normal(self.level2_b)
pass
def forward(self, x, t):
# import pdb; pdb.set_trace()
t1 = (t / self.branch_factor).long().cuda()
t2 = (t % self.branch_factor)
l1 = self.level1(x)
l1_ce = nf.cross_entropy(l1, Variable(t1))
# l1_log_softmax = sum([res[idx] for res, idx in zip(nf.log_softmax(l1), t1)])
# l1_log_softmax = nf.log_softmax(l1).t()[t1].diag()
### l2_w = [self.level2_w[idx] for idx in t2]
# l2_w = self.level2_w[t1]
## l2_b = self.level2_b[t1]
### l2_aff = torch.stack([mat.mv(vec) for mat, vec in zip(l2_w, x)], 0)# + l2_b
l2_aff = torch.stack([self.level2_w[idx].mv(vec) for idx, vec in zip(t2, x)], 0)
l2_ce = nf.cross_entropy(l2_aff, Variable(t2.cuda()).long())
# l2_aff = [mat.addmv(l2_b, vec) for mat, vec in zip(l2_w, x)]
# l2_aff = l2_w.bmm(x.unsqueeze(2)).squeeze() + l2_b
## l2_log_softmax = torch.stack([res[idx] for res, idx in zip(nf.log_softmax(l2_aff), t2)], 0)
# l2_log_softmax = nf.log_softmax(l2_aff).t()[t2].diag()
## ce = - (l1_log_softmax + l2_log_softmax).sum()/x.size()[0]
# ce = -l1_log_softmax/x.size()[0]
return l1_ce + l2_ce
|
[
"chainer.links.loss.hierarchical_softmax.TreeParser",
"torch.Tensor",
"torch.from_numpy",
"torch.cat",
"torch.nn.functional.cross_entropy",
"torch.nn.Linear",
"numpy.cumsum",
"torch.autograd.Variable",
"torch.nn.init.kaiming_normal",
"torch.nn.Embedding"
] |
[((463, 528), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': 'self.input_size', 'out_features': 'self.n_vocab'}), '(in_features=self.input_size, out_features=self.n_vocab)\n', (472, 528), False, 'from torch import nn\n'), ((648, 670), 'torch.nn.functional.cross_entropy', 'nf.cross_entropy', (['v', 't'], {}), '(v, t)\n', (664, 670), True, 'import torch.nn.functional as nf\n'), ((837, 849), 'chainer.links.loss.hierarchical_softmax.TreeParser', 'TreeParser', ([], {}), '()\n', (847, 849), False, 'from chainer.links.loss.hierarchical_softmax import TreeParser\n'), ((1442, 1475), 'numpy.cumsum', 'np.cumsum', (['([0.0] + self.lens[:-1])'], {}), '([0.0] + self.lens[:-1])\n', (1451, 1475), True, 'import numpy as np\n'), ((2997, 3009), 'chainer.links.loss.hierarchical_softmax.TreeParser', 'TreeParser', ([], {}), '()\n', (3007, 3009), False, 'from chainer.links.loss.hierarchical_softmax import TreeParser\n'), ((3298, 3374), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings': 'self.n_decisions', 'embedding_dim': 'self.input_size'}), '(num_embeddings=self.n_decisions, embedding_dim=self.input_size)\n', (3310, 3374), False, 'from torch import nn\n'), ((5213, 5284), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': 'self.input_size', 'out_features': 'self.branch_factor'}), '(in_features=self.input_size, out_features=self.branch_factor)\n', (5222, 5284), False, 'from torch import nn\n'), ((5555, 5589), 'torch.nn.init.kaiming_normal', 'init.kaiming_normal', (['self.level2_w'], {}), '(self.level2_w)\n', (5574, 5589), False, 'from torch.nn import init\n'), ((1072, 1119), 'torch.Tensor', 'torch.Tensor', (['self.n_decisions', 'self.input_size'], {}), '(self.n_decisions, self.input_size)\n', (1084, 1119), False, 'import torch\n'), ((1314, 1342), 'torch.from_numpy', 'torch.from_numpy', (['codes_d[i]'], {}), '(codes_d[i])\n', (1330, 1342), False, 'import torch\n'), ((4376, 4401), 'torch.autograd.Variable', 'Variable', (['self.paths[g_t]'], {}), '(self.paths[g_t])\n', (4384, 4401), False, 'from torch.autograd import Variable\n'), ((4545, 4570), 'torch.autograd.Variable', 'Variable', (['self.codes[g_t]'], {}), '(self.codes[g_t])\n', (4553, 4570), False, 'from torch.autograd import Variable\n'), ((5347, 5416), 'torch.Tensor', 'torch.Tensor', (['self.branch_factor', 'self.branch_factor', 'self.input_size'], {}), '(self.branch_factor, self.branch_factor, self.input_size)\n', (5359, 5416), False, 'import torch\n'), ((5844, 5856), 'torch.autograd.Variable', 'Variable', (['t1'], {}), '(t1)\n', (5852, 5856), False, 'from torch.autograd import Variable\n'), ((4193, 4215), 'torch.from_numpy', 'torch.from_numpy', (['code'], {}), '(code)\n', (4209, 4215), False, 'import torch\n'), ((4323, 4342), 'torch.from_numpy', 'torch.from_numpy', (['t'], {}), '(t)\n', (4339, 4342), False, 'import torch\n'), ((1517, 1539), 'torch.from_numpy', 'torch.from_numpy', (['path'], {}), '(path)\n', (1533, 1539), False, 'import torch\n'), ((1927, 1940), 'torch.cat', 'torch.cat', (['vv'], {}), '(vv)\n', (1936, 1940), False, 'import torch\n'), ((3921, 3943), 'torch.from_numpy', 'torch.from_numpy', (['path'], {}), '(path)\n', (3937, 3943), False, 'import torch\n')]
|
# -*- coding: utf-8 -*-
"""Classifying Images with Pre-trained ImageNet CNNs.
Let’s learn how to classify images with pre-trained Convolutional Neural Networks
using the Keras library.
Example:
$ python imagenet_pretrained.py --image example_images/example_01.jpg --model vgg16
$ python imagenet_pretrained.py --image example_images/example_02.jpg --model vgg19
$ python imagenet_pretrained.py --image example_images/example_03.jpg --model inception
$ python imagenet_pretrained.py --image example_images/example_04.jpg --model xception
$ python imagenet_pretrained.py --image example_images/example_05.jpg --model resnet
Attributes:
image (str):
The path to our input image.
model (str, optional):
The name of the pre-trained network to use.
"""
import argparse
import cv2
import numpy as np
from keras.applications import ResNet50
from keras.applications import InceptionV3
from keras.applications import Xception # TensorFlow ONLY
from keras.applications import VGG16
from keras.applications import VGG19
from keras.applications import imagenet_utils
from keras.applications.inception_v3 import preprocess_input
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
# define a dictionary that maps model names to their classes inside Keras
MODELS = {
"vgg16": VGG16,
"vgg19": VGG19,
"inception": InceptionV3,
"xception": Xception, # TensorFlow ONLY
"resnet": ResNet50,
}
def main():
"""Classify images with a pre-trained neural network.
Raises:
AssertionError: The --model command line argument should be a key in the `MODELS` dictionary
"""
# construct the argument parse and parse the arguments
args = argparse.ArgumentParser()
args.add_argument("-i", "--image", required=True, help="path to the input image")
args.add_argument("-model", "--model", type=str, default="vgg16", help="name of pre-trained network to use")
args = vars(args.parse_args())
# ensure a valid model name was supplied via command line argument
if args["model"] not in MODELS.keys():
raise AssertionError("The --model command line argument should " "be a key in the `MODELS` dictionary")
# initialize the input image shape (224x224 pixels) along with the pre-processing function
# (this might need to be changed based on which model we use to classify our image)
input_shape = (224, 224)
preprocess = imagenet_utils.preprocess_input
# if we are using the InceptionV3 or Xception networks, then we need to set the input shape
# to (299x299) [rather than (224x224)] and use a different image processing function
if args["model"] in ("inception", "xception"):
input_shape = (299, 299)
preprocess = preprocess_input
# load the network weights from disk (NOTE: if this is the first time you are running this
# script for a given network, the weights will need to be downloaded first -- depending on
# which network you are using, the weights can be 90-575MB, so be patient; the weights
# will be cached and subsequent runs of this script will be *much* faster)
print("[INFO] loading {}...".format(args["model"]))
network = MODELS[args["model"]]
model = network(weights="imagenet")
# load the input image using the Keras helper utility while ensuring the image is resized
# to `input_shape`, the required input dimensions for the ImageNet pre-trained network
print("[INFO] loading and pre-processing image...")
image = load_img(args["image"], target_size=input_shape)
image = img_to_array(image)
# our input image is now represented as a NumPy array of shape
# (input_shape[0], input_shape[1], 3) however we need to expand the
# dimension by making the shape (1, input_shape[0], input_shape[1], 3)
# so we can pass it through the network. The 1 has to be specified
# so we can train in batches.
image = np.expand_dims(image, axis=0)
# pre-process the image using the appropriate function based on the
# model that has been loaded (i.e., mean subtraction, scaling, etc.)
image = preprocess(image)
# classify the image
print("[INFO] classifying image with '{}'...".format(args["model"]))
predictions = model.predict(image)
prediction = imagenet_utils.decode_predictions(predictions)
# loop over the predictions and display the rank-5 predictions + probabilities to our terminal
for (i, (_, label, prob)) in enumerate(prediction[0]):
print("{}. {}: {:.2f}%".format(i + 1, label, prob * 100))
# load the image via OpenCV, draw the top prediction on the image,
# and display the image to our screen
orig = cv2.imread(args["image"])
(_, label, prob) = prediction[0][0]
cv2.putText(orig, "Label: {}".format(label), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
cv2.imshow("Classification", orig)
cv2.waitKey(0)
if __name__ == "__main__":
main()
|
[
"keras.preprocessing.image.img_to_array",
"cv2.imread",
"argparse.ArgumentParser",
"cv2.imshow",
"cv2.waitKey",
"numpy.expand_dims",
"keras.applications.imagenet_utils.decode_predictions",
"keras.preprocessing.image.load_img"
] |
[((1752, 1777), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1775, 1777), False, 'import argparse\n'), ((3554, 3602), 'keras.preprocessing.image.load_img', 'load_img', (["args['image']"], {'target_size': 'input_shape'}), "(args['image'], target_size=input_shape)\n", (3562, 3602), False, 'from keras.preprocessing.image import load_img\n'), ((3615, 3634), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['image'], {}), '(image)\n', (3627, 3634), False, 'from keras.preprocessing.image import img_to_array\n'), ((3966, 3995), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': '(0)'}), '(image, axis=0)\n', (3980, 3995), True, 'import numpy as np\n'), ((4325, 4371), 'keras.applications.imagenet_utils.decode_predictions', 'imagenet_utils.decode_predictions', (['predictions'], {}), '(predictions)\n', (4358, 4371), False, 'from keras.applications import imagenet_utils\n'), ((4732, 4757), 'cv2.imread', 'cv2.imread', (["args['image']"], {}), "(args['image'])\n", (4742, 4757), False, 'import cv2\n'), ((4920, 4954), 'cv2.imshow', 'cv2.imshow', (['"""Classification"""', 'orig'], {}), "('Classification', orig)\n", (4930, 4954), False, 'import cv2\n'), ((4963, 4977), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (4974, 4977), False, 'import cv2\n')]
|
import numpy as np
from matplotlib import pyplot as plt
N = 30
y = np.random.rand(N)
plt.plot(y,'bo')
|
[
"matplotlib.pyplot.plot",
"numpy.random.rand"
] |
[((68, 85), 'numpy.random.rand', 'np.random.rand', (['N'], {}), '(N)\n', (82, 85), True, 'import numpy as np\n'), ((87, 104), 'matplotlib.pyplot.plot', 'plt.plot', (['y', '"""bo"""'], {}), "(y, 'bo')\n", (95, 104), True, 'from matplotlib import pyplot as plt\n')]
|
import tensorflow as tf
from robust_offline_contextual_bandits.named_results import NamedResults
import numpy as np
class NamedResultsTest(tf.test.TestCase):
def setUp(self):
np.random.seed(42)
def test_creation(self):
patient = NamedResults(np.random.normal(size=[10, 3]))
assert patient.num_evs() == 10
assert patient.num_reps() == 3
self.assertAllClose(patient.avg_evs(), [
0.335379, 0.35158, 0.625724, -0.128862, -1.132079, -0.42029,
-0.284893, -0.527665, -0.528151, -0.172211
])
self.assertAlmostEqual(patient.min_ev(), -1.132078602)
if __name__ == '__main__':
tf.test.main()
|
[
"numpy.random.normal",
"numpy.random.seed",
"tensorflow.test.main"
] |
[((663, 677), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (675, 677), True, 'import tensorflow as tf\n'), ((189, 207), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (203, 207), True, 'import numpy as np\n'), ((269, 299), 'numpy.random.normal', 'np.random.normal', ([], {'size': '[10, 3]'}), '(size=[10, 3])\n', (285, 299), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
import numpy as np
def plot_convolution(f, g):
fig, (ax1, ax2, ax3) = plt.subplots(3, 1)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
ax1.plot(f, color='blue', label='f')
ax1.legend()
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.plot(g, color='red', label='g')
ax2.legend()
filtered = np.convolve(f, g, "same") / sum(g)
ax3.set_yticklabels([])
ax3.set_xticklabels([])
ax3.plot(filtered, color='green', label='f * g')
ax3.legend()
plt.show()
def plot_convolution_step_by_step(f, g):
fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, 1)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
ax1.plot(f, color='blue', label='f')
ax1.plot(np.roll(g, -10000), color='red', label='g')
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.plot(f, color='blue', label='f')
ax2.plot(np.roll(g, -5000), color='red', label='g')
ax3.set_yticklabels([])
ax3.set_xticklabels([])
ax3.plot(f, color='blue', label='f')
ax3.plot(g, color='red', label='g')
ax4.set_yticklabels([])
ax4.set_xticklabels([])
ax4.plot(f, color='blue', label='f')
ax4.plot(np.roll(g, 5000), color='red', label='g')
ax5.set_yticklabels([])
ax5.set_xticklabels([])
ax5.plot(f, color='blue', label='f')
ax5.plot(np.roll(g, 10000), color='red', label='g')
plt.show()
signal = np.zeros(30000)
signal[10000:20000] = 1
kernel = np.zeros(30000)
kernel[10000:20000] = np.linspace(1, 0, 10000)
plot_convolution(signal, kernel)
plot_convolution_step_by_step(signal, kernel)
|
[
"numpy.convolve",
"numpy.roll",
"numpy.zeros",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] |
[((1427, 1442), 'numpy.zeros', 'np.zeros', (['(30000)'], {}), '(30000)\n', (1435, 1442), True, 'import numpy as np\n'), ((1477, 1492), 'numpy.zeros', 'np.zeros', (['(30000)'], {}), '(30000)\n', (1485, 1492), True, 'import numpy as np\n'), ((1515, 1539), 'numpy.linspace', 'np.linspace', (['(1)', '(0)', '(10000)'], {}), '(1, 0, 10000)\n', (1526, 1539), True, 'import numpy as np\n'), ((108, 126), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(1)'], {}), '(3, 1)\n', (120, 126), True, 'import matplotlib.pyplot as plt\n'), ((537, 547), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (545, 547), True, 'import matplotlib.pyplot as plt\n'), ((628, 646), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(1)'], {}), '(5, 1)\n', (640, 646), True, 'import matplotlib.pyplot as plt\n'), ((1405, 1415), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1413, 1415), True, 'import matplotlib.pyplot as plt\n'), ((371, 396), 'numpy.convolve', 'np.convolve', (['f', 'g', '"""same"""'], {}), "(f, g, 'same')\n", (382, 396), True, 'import numpy as np\n'), ((757, 775), 'numpy.roll', 'np.roll', (['g', '(-10000)'], {}), '(g, -10000)\n', (764, 775), True, 'import numpy as np\n'), ((912, 929), 'numpy.roll', 'np.roll', (['g', '(-5000)'], {}), '(g, -5000)\n', (919, 929), True, 'import numpy as np\n'), ((1204, 1220), 'numpy.roll', 'np.roll', (['g', '(5000)'], {}), '(g, 5000)\n', (1211, 1220), True, 'import numpy as np\n'), ((1357, 1374), 'numpy.roll', 'np.roll', (['g', '(10000)'], {}), '(g, 10000)\n', (1364, 1374), True, 'import numpy as np\n')]
|
from __future__ import print_function
from amd.rali.plugin.tf import RALIIterator
from amd.rali.pipeline import Pipeline
import amd.rali.ops as ops
import amd.rali.types as types
import sys
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
############################### HYPER PARAMETERS FOR TRAINING ###############################
learning_rate = 0.001
image_size = 28
# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
############################### HYPER PARAMETERS FOR TRAINING ###############################
def get_label_one_hot(label_ndArray):
one_hot_vector_list = []
for label in label_ndArray:
one_hot_vector = np.zeros(num_classes)
np.put(one_hot_vector, label - 1, 1)
one_hot_vector_list.append(one_hot_vector)
return one_hot_vector_list
# Create model
weights = {
'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([num_classes]))
}
def neural_net(x):
# Hidden fully connected layer with 256 neurons
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
# Hidden fully connected layer with 256 neurons
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
# Output fully connected layer with a neuron for each class
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
#helper function not used in training
def decode(tfrecord_serialized):
tfrecord_features = tf.parse_single_example(tfrecord_serialized, features={
'image/height': tf.FixedLenFeature([], tf.int64),
'image/width': tf.FixedLenFeature([], tf.int64),
'image/class/label': tf.FixedLenFeature([], tf.int64),
'image/raw': tf.FixedLenFeature([], tf.string),
}, name='features')
image = tf.decode_raw(tfrecord_features['image/raw'], tf.float32)
image.set_shape([784])
label = tf.cast(tfrecord_features['image/class/label'], tf.int32)
# image_batch, label_batch = tf.train.batch([image, label], batch_size=bs)
return image, label
#RALI pipeline
class HybridPipe(Pipeline):
def __init__(self, feature_key_map, tfrecordreader_type, batch_size, num_threads, device_id, data_dir, crop, rali_cpu = True):
super(HybridPipe, self).__init__(batch_size, num_threads, device_id, seed=12 + device_id,rali_cpu=rali_cpu)
self.input = ops.TFRecordReader(path=data_dir, index_path = "", reader_type=tfrecordreader_type, user_feature_key_map=feature_key_map,
features={
'image/encoded':tf.FixedLenFeature((), tf.string, ""),
'image/class/label':tf.FixedLenFeature([1], tf.int64, -1),
'image/filename':tf.FixedLenFeature((), tf.string, "")
},
)
rali_device = 'cpu' if rali_cpu else 'gpu'
decoder_device = 'cpu' if rali_cpu else 'mixed'
self.decode = ops.ImageDecoderRaw(user_feature_key_map=feature_key_map, device=decoder_device, output_type=types.RGB)
#self.res = ops.Resize(device=rali_device, resize_x=crop[0], resize_y=crop[1])
self.cmnp = ops.CropMirrorNormalize(device="cpu",
output_dtype=types.FLOAT,
output_layout=types.NCHW,
crop=(crop,crop),
image_type=types.GRAY,
mean=[0 ,0,0],
std=[255,255,255], mirror=0)
self.coin = ops.CoinFlip(probability=0.5)
print('rali "{0}" variant'.format(rali_device))
def define_graph(self):
inputs = self.input(name ="Reader")
images = inputs["image/encoded"]
labels = inputs["image/class/label"]
images = self.decode(images)
#rng = self.coin()
output = self.cmnp(images)
return [output, labels]
# compute accuracy
def compute_accuracy(predictions, labels):
correct_predictions = tf.equal(tf.argmax(predictions, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
return accuracy
def train_mnist_rali(data_path, _rali_cpu, batch_size):
# setup keep_prob
input_X = tf.placeholder('float32',shape = (batch_size,784))
labels = tf.placeholder('float32',shape = (batch_size,10))
logits = neural_net(input_X)
cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits), name="loss" )
optimizer = tf.train.AdamOptimizer().minimize(cost)
train_prediction = tf.nn.softmax(logits)
accuracy = compute_accuracy(train_prediction, labels)
#correct_label = tf.argmax(labels, 1)
num_epochs = 10
crop_size = 28
TFRecordReaderType = 0
featureKeyMap = {
'image/encoded':'image_raw',
'image/class/label':'label',
'image/filename':''
}
trainPipe = HybridPipe(feature_key_map=featureKeyMap, tfrecordreader_type=TFRecordReaderType, batch_size=batch_size, num_threads=1, device_id=0, data_dir=data_path+"/train", crop=crop_size, rali_cpu=_rali_cpu)
valPipe = HybridPipe(feature_key_map=featureKeyMap, tfrecordreader_type=TFRecordReaderType, batch_size=batch_size, num_threads=1, device_id=0, data_dir=data_path+"/val", crop=crop_size, rali_cpu=_rali_cpu)
trainPipe.build()
valPipe.build()
trainIterator = RALIIterator(trainPipe)
valIterator = RALIIterator(valPipe)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for epoch in range(num_epochs):
print('\n\n----------------------------Training Model for Epoch: ', epoch, "-----------------------------------------------")
epoch_loss = 0
train_accuracy = 0
for i, (image_train, label_train) in enumerate(trainIterator, 0):
image_train_res = image_train.reshape(batch_size, 784)
train_label_one_hot_list = get_label_one_hot(label_train)
_, c, tacc = sess.run([optimizer, cost, accuracy], feed_dict={input_X:image_train_res, labels: train_label_one_hot_list})
epoch_loss += c
train_accuracy += tacc
print('Epoch', epoch, 'completed out of',num_epochs,'loss:',epoch_loss, 'accuracy:',(train_accuracy*100)/i, 'count :', i)
#run evaluation for every epoch
mean_acc = 0
print("\n\n----------------------------Evaluating Model ---------------------------------------------------------------")
for j, (val_image_ndArray, val_label_ndArray) in enumerate(valIterator, 0):
#val_image_ndArray_transposed = np.transpose(val_image_ndArray, [0, 2, 3, 1])
val_image_ndArray_res = val_image_ndArray.reshape(batch_size, 784)
val_label_one_hot_list = get_label_one_hot(val_label_ndArray)
val_accuracy = sess.run(accuracy,
#[optimizer, accuracy, prediction, correct_label, correct_pred],
feed_dict={input_X: val_image_ndArray_res, labels: val_label_one_hot_list})
mean_acc += val_accuracy
#mean_loss = mean_loss + val_loss
#num_correct_predicate = 0
#for predicate in correct_predicate:
# if predicate == True:
# num_correct_predicate += 1
#print ("Step :: %s\tTarget :: %s\tPrediction :: %s\tCorrect Predictions :: %s/%s\tValidation Loss :: %.2f\tValidation Accuracy :: %.2f%%\t" % (j, val_target, val_prediction, num_correct_predicate, len(correct_predicate), val_loss, (val_accuracy * 100)))
mean_acc = (mean_acc * 100) / j
#mean_loss = (mean_loss * 100)/ j
print("\nSUMMARY:\nMean Accuracy :: %.2f%% count: %d" % (mean_acc, j))
def main():
if len(sys.argv) < 4:
print ('Please pass mnistTFRecord_dir cpu/gpu batch_size')
exit(0)
image_path = sys.argv[1]
if(sys.argv[2] == "cpu"):
_rali_cpu = True
else:
_rali_cpu = False
bs = int(sys.argv[3])
train_mnist_rali(image_path, _rali_cpu, bs)
if __name__ == '__main__':
main()
|
[
"tensorflow.compat.v1.disable_v2_behavior",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.compat.v1.FixedLenFeature",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.nn.relu",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.nn.softmax",
"tensorflow.compat.v1.argmax",
"tensorflow.compat.v1.decode_raw",
"tensorflow.compat.v1.cast",
"amd.rali.ops.ImageDecoderRaw",
"amd.rali.ops.CropMirrorNormalize",
"tensorflow.compat.v1.matmul",
"amd.rali.ops.CoinFlip",
"numpy.put",
"tensorflow.compat.v1.random_normal",
"numpy.zeros",
"tensorflow.compat.v1.nn.softmax_cross_entropy_with_logits",
"amd.rali.plugin.tf.RALIIterator",
"tensorflow.compat.v1.initialize_all_variables"
] |
[((225, 249), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (247, 249), True, 'import tensorflow.compat.v1 as tf\n'), ((1547, 1566), 'tensorflow.compat.v1.nn.relu', 'tf.nn.relu', (['layer_1'], {}), '(layer_1)\n', (1557, 1566), True, 'import tensorflow.compat.v1 as tf\n'), ((1645, 1664), 'tensorflow.compat.v1.nn.relu', 'tf.nn.relu', (['layer_2'], {}), '(layer_2)\n', (1655, 1664), True, 'import tensorflow.compat.v1 as tf\n'), ((2197, 2254), 'tensorflow.compat.v1.decode_raw', 'tf.decode_raw', (["tfrecord_features['image/raw']", 'tf.float32'], {}), "(tfrecord_features['image/raw'], tf.float32)\n", (2210, 2254), True, 'import tensorflow.compat.v1 as tf\n'), ((2288, 2345), 'tensorflow.compat.v1.cast', 'tf.cast', (["tfrecord_features['image/class/label']", 'tf.int32'], {}), "(tfrecord_features['image/class/label'], tf.int32)\n", (2295, 2345), True, 'import tensorflow.compat.v1 as tf\n'), ((4318, 4368), 'tensorflow.compat.v1.placeholder', 'tf.placeholder', (['"""float32"""'], {'shape': '(batch_size, 784)'}), "('float32', shape=(batch_size, 784))\n", (4332, 4368), True, 'import tensorflow.compat.v1 as tf\n'), ((4379, 4428), 'tensorflow.compat.v1.placeholder', 'tf.placeholder', (['"""float32"""'], {'shape': '(batch_size, 10)'}), "('float32', shape=(batch_size, 10))\n", (4393, 4428), True, 'import tensorflow.compat.v1 as tf\n'), ((4641, 4662), 'tensorflow.compat.v1.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (4654, 4662), True, 'import tensorflow.compat.v1 as tf\n'), ((5392, 5415), 'amd.rali.plugin.tf.RALIIterator', 'RALIIterator', (['trainPipe'], {}), '(trainPipe)\n', (5404, 5415), False, 'from amd.rali.plugin.tf import RALIIterator\n'), ((5431, 5452), 'amd.rali.plugin.tf.RALIIterator', 'RALIIterator', (['valPipe'], {}), '(valPipe)\n', (5443, 5452), False, 'from amd.rali.plugin.tf import RALIIterator\n'), ((831, 852), 'numpy.zeros', 'np.zeros', (['num_classes'], {}), '(num_classes)\n', (839, 852), True, 'import numpy as np\n'), ((855, 891), 'numpy.put', 'np.put', (['one_hot_vector', '(label - 1)', '(1)'], {}), '(one_hot_vector, label - 1, 1)\n', (861, 891), True, 'import numpy as np\n'), ((1012, 1053), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[num_input, n_hidden_1]'], {}), '([num_input, n_hidden_1])\n', (1028, 1053), True, 'import tensorflow.compat.v1 as tf\n'), ((1075, 1117), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[n_hidden_1, n_hidden_2]'], {}), '([n_hidden_1, n_hidden_2])\n', (1091, 1117), True, 'import tensorflow.compat.v1 as tf\n'), ((1140, 1183), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[n_hidden_2, num_classes]'], {}), '([n_hidden_2, num_classes])\n', (1156, 1183), True, 'import tensorflow.compat.v1 as tf\n'), ((1217, 1247), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[n_hidden_1]'], {}), '([n_hidden_1])\n', (1233, 1247), True, 'import tensorflow.compat.v1 as tf\n'), ((1269, 1299), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[n_hidden_2]'], {}), '([n_hidden_2])\n', (1285, 1299), True, 'import tensorflow.compat.v1 as tf\n'), ((1322, 1353), 'tensorflow.compat.v1.random_normal', 'tf.random_normal', (['[num_classes]'], {}), '([num_classes])\n', (1338, 1353), True, 'import tensorflow.compat.v1 as tf\n'), ((1444, 1471), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['x', "weights['h1']"], {}), "(x, weights['h1'])\n", (1453, 1471), True, 'import tensorflow.compat.v1 as tf\n'), ((1585, 1618), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['layer_1', "weights['h2']"], {}), "(layer_1, weights['h2'])\n", (1594, 1618), True, 'import tensorflow.compat.v1 as tf\n'), ((1739, 1773), 'tensorflow.compat.v1.matmul', 'tf.matmul', (['layer_2', "weights['out']"], {}), "(layer_2, weights['out'])\n", (1748, 1773), True, 'import tensorflow.compat.v1 as tf\n'), ((3221, 3329), 'amd.rali.ops.ImageDecoderRaw', 'ops.ImageDecoderRaw', ([], {'user_feature_key_map': 'feature_key_map', 'device': 'decoder_device', 'output_type': 'types.RGB'}), '(user_feature_key_map=feature_key_map, device=\n decoder_device, output_type=types.RGB)\n', (3240, 3329), True, 'import amd.rali.ops as ops\n'), ((3420, 3606), 'amd.rali.ops.CropMirrorNormalize', 'ops.CropMirrorNormalize', ([], {'device': '"""cpu"""', 'output_dtype': 'types.FLOAT', 'output_layout': 'types.NCHW', 'crop': '(crop, crop)', 'image_type': 'types.GRAY', 'mean': '[0, 0, 0]', 'std': '[255, 255, 255]', 'mirror': '(0)'}), "(device='cpu', output_dtype=types.FLOAT,\n output_layout=types.NCHW, crop=(crop, crop), image_type=types.GRAY,\n mean=[0, 0, 0], std=[255, 255, 255], mirror=0)\n", (3443, 3606), True, 'import amd.rali.ops as ops\n'), ((3675, 3704), 'amd.rali.ops.CoinFlip', 'ops.CoinFlip', ([], {'probability': '(0.5)'}), '(probability=0.5)\n', (3687, 3704), True, 'import amd.rali.ops as ops\n'), ((4095, 4120), 'tensorflow.compat.v1.argmax', 'tf.argmax', (['predictions', '(1)'], {}), '(predictions, 1)\n', (4104, 4120), True, 'import tensorflow.compat.v1 as tf\n'), ((4122, 4142), 'tensorflow.compat.v1.argmax', 'tf.argmax', (['labels', '(1)'], {}), '(labels, 1)\n', (4131, 4142), True, 'import tensorflow.compat.v1 as tf\n'), ((4171, 4211), 'tensorflow.compat.v1.cast', 'tf.cast', (['correct_predictions', 'tf.float32'], {}), '(correct_predictions, tf.float32)\n', (4178, 4211), True, 'import tensorflow.compat.v1 as tf\n'), ((4483, 4552), 'tensorflow.compat.v1.nn.softmax_cross_entropy_with_logits', 'tf.nn.softmax_cross_entropy_with_logits', ([], {'labels': 'labels', 'logits': 'logits'}), '(labels=labels, logits=logits)\n', (4522, 4552), True, 'import tensorflow.compat.v1 as tf\n'), ((5460, 5472), 'tensorflow.compat.v1.Session', 'tf.Session', ([], {}), '()\n', (5470, 5472), True, 'import tensorflow.compat.v1 as tf\n'), ((4581, 4605), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {}), '()\n', (4603, 4605), True, 'import tensorflow.compat.v1 as tf\n'), ((5493, 5522), 'tensorflow.compat.v1.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (5520, 5522), True, 'import tensorflow.compat.v1 as tf\n'), ((1975, 2007), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (1993, 2007), True, 'import tensorflow.compat.v1 as tf\n'), ((2026, 2058), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (2044, 2058), True, 'import tensorflow.compat.v1 as tf\n'), ((2083, 2115), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (2101, 2115), True, 'import tensorflow.compat.v1 as tf\n'), ((2132, 2165), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (2150, 2165), True, 'import tensorflow.compat.v1 as tf\n'), ((2909, 2946), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string', '""""""'], {}), "((), tf.string, '')\n", (2927, 2946), True, 'import tensorflow.compat.v1 as tf\n'), ((2979, 3016), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['[1]', 'tf.int64', '(-1)'], {}), '([1], tf.int64, -1)\n', (2997, 3016), True, 'import tensorflow.compat.v1 as tf\n'), ((3047, 3084), 'tensorflow.compat.v1.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string', '""""""'], {}), "((), tf.string, '')\n", (3065, 3084), True, 'import tensorflow.compat.v1 as tf\n')]
|
from constants import Constants
import numpy as np
# TODO finish implementing all regions of the atmosphere
class ISA(Constants):
def __init__(self, altitude=0):
""" Calculates International Standard Atmosphere properties for the specified geo-potential altitude
:param float altitude: Geo-potential Altitude in SI meter [m]
"""
if 0. <= altitude <= 84852. and isinstance(altitude, float):
self.altitude = altitude
else:
raise ValueError('Invalid altitude specified')
@property
def calculator(self):
h, R, T0, P0, rho0 = self.altitude, self.gas_constant, self.temperature_sl, self.pressure_sl, self.rho_sl
if h == 0:
Talt, Palt, rhoalt = T0, P0, rho0
elif 0 < h < 11000.:
a = -6.5e-3
Talt = T0 + (a * h)
Palt = P0 * (Talt / T0) ^ (-(self.g / (a * R)))
rhoalt = rho0 * ((Talt / T0) ^ (-((self.g / (a * R)) + 1)))
elif 11000 <= h < 25000:
a = -6.5e-3
Talt = 216.66
Palt = P0*(Talt/T0)**(-(self.g/(a*R)))
rhoalt = 0.36480*(np.exp(-1 * ((self.g*(h-11000.))/(R * T0))))
else:
Talt = None
Palt = None
rhoalt = None
return Talt, Palt, rhoalt
# function [T,Palt,rhoalt,a]=ISA(h)
# global Econst
# %Calculates the Temperature [K] using International Standard Atmosphere
# if(h>=0)&&(h<=11000);
# T=Econst.Temp0+(Econst.lambda*h);
# Palt=Econst.P0*(T/Econst.Temp0)^(-(Econst.g/(Econst.lambda*Econst.R)));
# rhoalt=Econst.rho0*((T/Econst.Temp0)^(-((Econst.g/(Econst.lambda*Econst.R))+1)));
# elseif(h>11000)&&(h<=25000);
# T=216.66;
# Palt=22700*((exp(1))^(-((Econst.g*(h-11000))/(Econst.R*T))));
# rhoalt=0.36480*((exp(1))^(-((Econst.g*(h-11000))/(Econst.R*T))));
# elseif(h>25000)&&(h<=47000);
# T=216.66+(1*((h-20000)/1000));
# Palt=5474.9*((216.65+(.001*(h-20000)))/216.65)^(-(Econst.g/(.001*Econst.R)));
# rhoalt=0.088035*((216.65+(.001*(h-20000)))/216.65)^(-((Econst.g/(.001*Econst.R))-1));
# elseif(h>32000)&&(h<=47000);
# T=228.65+(2.8*((h-32000)/1000));
# Palt=868.02*((228.65+(0.0028*(h-32000)))/228.65)^(-(Econst.g/(0.0028*Econst.R)));
# rhoalt=0.013225*((228.65+(0.0028*(h-32000)))/228.65)^(-((Econst.g/(0.0028*Econst.R))-1));
# elseif(h>47000)&&(h<=53000);
# T=270.65;
# Palt=110.91*((exp(1))^(-((Econst.g*(h-47000))/(Econst.R*270.65))));
# rhoalt=0.001428*((exp(1))^(-((Econst.g*(h-47000))/(Econst.R*270.65))));
# elseif(h>53000)&&(h<=79000);
# T=270.65+((-2.8)*((h-51000)/1000));
# Palt=66.939*((270.65+(-0.0028*(h-51000)))/270.65)^(-(Econst.g/(-0.0028*Econst.R)));
# rhoalt=0.000862*((270.65+(-0.0028*(h-51000)))/270.65)^(-((Econst.g/(-0.0028*Econst.R))-1));
# elseif(h>79000)&&(h<=90000);
# T=214.65+((-2.0)*((h-71000)/1000));
# Palt=3.9564*((214.65+(-0.002*(h-71000)))/214.65)^(-(Econst.g/(-0.002*Econst.R)));
# rhoalt=0.000064*((214.65+(-0.002*(h-71000)))/214.65)^(-((Econst.g/(-0.002*Econst.R))-1));
# end
# if(h<0)||(h>84852);
# disp('International Standard Atmosphere Calculations cannot be used for values above 84,852m')
# end
# if(h>=0)&&(h<=84852);
# a=sqrt(1.4*Econst.R*T);
# %FL=ceil(((h*1250)/381)/100);
# %disp(['Temperature at Flight Level ' num2str(FL) ' = ' num2str(T) 'K' ' = ' num2str(T-273.15) 'C'])
# %disp(['Pressure at Flight Level ' num2str(FL) ' = ' num2str(Palt/1000) 'kPa'])
# %disp(['Density at Flight Level ' num2str(FL) ' = ' num2str(rhoalt) ' [kg/m3]'])
# %disp(['Speed of Sound at Flight Level ' num2str(FL) ' = ' num2str(a) ' [m/s]'])
# end
# end
if __name__ == '__main__':
obj = ISA(11000.)
print(obj.altitude)
print(obj.temperature)
|
[
"numpy.exp"
] |
[((1141, 1189), 'numpy.exp', 'np.exp', (['(-1 * (self.g * (h - 11000.0) / (R * T0)))'], {}), '(-1 * (self.g * (h - 11000.0) / (R * T0)))\n', (1147, 1189), True, 'import numpy as np\n')]
|
import sys
import soundcard
import numpy
import pytest
skip_if_not_linux = pytest.mark.skipif(sys.platform != 'linux', reason='Only implemented for PulseAudio so far')
ones = numpy.ones(1024)
signal = numpy.concatenate([[ones], [-ones]]).T
def test_speakers():
for speaker in soundcard.all_speakers():
assert isinstance(speaker.name, str)
assert hasattr(speaker, 'id')
assert isinstance(speaker.channels, int)
assert speaker.channels > 0
def test_microphones():
for microphone in soundcard.all_microphones():
assert isinstance(microphone.name, str)
assert hasattr(microphone, 'id')
assert isinstance(microphone.channels, int)
assert microphone.channels > 0
def test_default_playback():
soundcard.default_speaker().play(signal, 44100, channels=2)
def test_default_record():
recording = soundcard.default_microphone().record(1024, 44100)
assert len(recording == 1024)
def test_default_blockless_record():
recording = soundcard.default_microphone().record(None, 44100)
@skip_if_not_linux
def test_name():
# The default is the application name, so when run from pytest,
# it’s “pytest” or “_jb_pytest_runner.py” or so.
assert 'pytest' in soundcard.get_name()
soundcard.set_name('testapp')
assert soundcard.get_name() == 'testapp'
@skip_if_not_linux
@pytest.mark.parametrize("argv,progname", [
(["./script.py"], "script.py"), # chmod +x script.py; ./script.py
(["path/to/script.py"], "script.py"), # python path/to/script.py or
# python -m path.to.script
(["module/__main__.py"], "module"), # python -m module
(["-m", "module.submodule"], "module.submodule"), # rare unresolved case
(["-c", "import soundcard; soundcard.foo()"], "import soundcard; soundcard.fo..."),
])
def test_infer_name(monkeypatch, argv, progname):
infer = soundcard.pulseaudio._PulseAudio._infer_program_name
monkeypatch.setattr(sys, "argv", argv)
assert infer() == progname
@pytest.fixture
def loopback_speaker():
import sys
if sys.platform == 'win32':
# must install https://www.vb-audio.com/Cable/index.htm
return soundcard.get_speaker('Cable')
elif sys.platform == 'darwin':
# must install soundflower
return soundcard.get_speaker('Soundflower64')
elif sys.platform == 'linux':
# pacmd load-module module-null-sink channels=6 rate=48000
return soundcard.get_speaker('Null')
else:
raise RuntimeError('Unknown platform {}'.format(sys.platform))
@pytest.fixture
def loopback_player(loopback_speaker):
with loopback_speaker.player(48000, channels=2, blocksize=512) as player:
yield player
@pytest.fixture
def loopback_microphone():
if sys.platform == 'win32':
# must install https://www.vb-audio.com/Cable/index.htm
return soundcard.get_microphone('Cable')
elif sys.platform == 'darwin':
# must install soundflower
return soundcard.get_microphone('Soundflower64')
elif sys.platform == 'linux':
return soundcard.get_microphone('Null', include_loopback=True)
else:
raise RuntimeError('Unknown platform {}'.format(sys.platform))
@pytest.fixture
def loopback_recorder(loopback_microphone):
with loopback_microphone.recorder(48000, channels=2, blocksize=512) as recorder:
yield recorder
def test_loopback_playback(loopback_player, loopback_recorder):
loopback_player.play(signal)
recording = loopback_recorder.record(1024*10)
assert recording.shape[1] == 2
left, right = recording.T
assert left.mean() > 0
assert right.mean() < 0
assert (left > 0.5).sum() == len(signal)
assert (right < -0.5).sum() == len(signal)
def test_loopback_reverse_recorder_channelmap(loopback_player, loopback_microphone):
with loopback_microphone.recorder(48000, channels=[1, 0], blocksize=512) as loopback_recorder:
loopback_player.play(signal)
recording = loopback_recorder.record(1024*12)
assert recording.shape[1] == 2
left, right = recording.T
assert right.mean() > 0
assert left.mean() < 0
assert (right > 0.5).sum() == len(signal)
assert (left < -0.5).sum() == len(signal)
def test_loopback_reverse_player_channelmap(loopback_speaker, loopback_recorder):
with loopback_speaker.player(48000, channels=[1, 0], blocksize=512) as loopback_player:
loopback_player.play(signal)
recording = loopback_recorder.record(1024*12)
assert recording.shape[1] == 2
left, right = recording.T
assert right.mean() > 0
assert left.mean() < 0
assert (right > 0.5).sum() == len(signal)
assert (left < -0.5).sum() == len(signal)
def test_loopback_mono_player_channelmap(loopback_speaker, loopback_recorder):
with loopback_speaker.player(48000, channels=[0], blocksize=512) as loopback_player:
loopback_player.play(signal[:,0])
recording = loopback_recorder.record(1024*12)
assert recording.shape[1] == 2
left, right = recording.T
assert left.mean() > 0
if sys.platform == 'linux':
# unmapped channels on linux are filled with the mean of other channels
assert right.mean() < left.mean()
else:
assert abs(right.mean()) < 0.01 # something like zero
assert (left > 0.5).sum() == len(signal)
def test_loopback_mono_recorder_channelmap(loopback_player, loopback_microphone):
with loopback_microphone.recorder(48000, channels=[0], blocksize=512) as loopback_recorder:
loopback_player.play(signal)
recording = loopback_recorder.record(1024*12)
assert len(recording.shape) == 1 or recording.shape[1] == 1
assert recording.mean() > 0
assert (recording > 0.5).sum() == len(signal)
def test_loopback_multichannel_channelmap(loopback_speaker, loopback_microphone):
with loopback_speaker.player(48000, channels=[2, 0], blocksize=512) as loopback_player:
with loopback_microphone.recorder(48000, channels=[2, 0], blocksize=512) as loopback_recorder:
loopback_player.play(signal)
recording = loopback_recorder.record(1024*12)
assert len(recording.shape) == 2
left, right = recording.T
assert left.mean() > 0
assert right.mean() < 0
assert (left > 0.5).sum() == len(signal)
assert (right < -0.5).sum() == len(signal)
|
[
"soundcard.get_microphone",
"soundcard.all_speakers",
"soundcard.get_name",
"soundcard.all_microphones",
"numpy.ones",
"soundcard.default_microphone",
"soundcard.default_speaker",
"soundcard.set_name",
"pytest.mark.parametrize",
"soundcard.get_speaker",
"numpy.concatenate",
"pytest.mark.skipif"
] |
[((76, 173), 'pytest.mark.skipif', 'pytest.mark.skipif', (["(sys.platform != 'linux')"], {'reason': '"""Only implemented for PulseAudio so far"""'}), "(sys.platform != 'linux', reason=\n 'Only implemented for PulseAudio so far')\n", (94, 173), False, 'import pytest\n'), ((177, 193), 'numpy.ones', 'numpy.ones', (['(1024)'], {}), '(1024)\n', (187, 193), False, 'import numpy\n'), ((1363, 1663), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""argv,progname"""', "[(['./script.py'], 'script.py'), (['path/to/script.py'], 'script.py'), ([\n 'module/__main__.py'], 'module'), (['-m', 'module.submodule'],\n 'module.submodule'), (['-c', 'import soundcard; soundcard.foo()'],\n 'import soundcard; soundcard.fo...')]"], {}), "('argv,progname', [(['./script.py'], 'script.py'), (\n ['path/to/script.py'], 'script.py'), (['module/__main__.py'], 'module'),\n (['-m', 'module.submodule'], 'module.submodule'), (['-c',\n 'import soundcard; soundcard.foo()'], 'import soundcard; soundcard.fo...')]\n )\n", (1386, 1663), False, 'import pytest\n'), ((203, 239), 'numpy.concatenate', 'numpy.concatenate', (['[[ones], [-ones]]'], {}), '([[ones], [-ones]])\n', (220, 239), False, 'import numpy\n'), ((283, 307), 'soundcard.all_speakers', 'soundcard.all_speakers', ([], {}), '()\n', (305, 307), False, 'import soundcard\n'), ((524, 551), 'soundcard.all_microphones', 'soundcard.all_microphones', ([], {}), '()\n', (549, 551), False, 'import soundcard\n'), ((1267, 1296), 'soundcard.set_name', 'soundcard.set_name', (['"""testapp"""'], {}), "('testapp')\n", (1285, 1296), False, 'import soundcard\n'), ((1242, 1262), 'soundcard.get_name', 'soundcard.get_name', ([], {}), '()\n', (1260, 1262), False, 'import soundcard\n'), ((1308, 1328), 'soundcard.get_name', 'soundcard.get_name', ([], {}), '()\n', (1326, 1328), False, 'import soundcard\n'), ((2205, 2235), 'soundcard.get_speaker', 'soundcard.get_speaker', (['"""Cable"""'], {}), "('Cable')\n", (2226, 2235), False, 'import soundcard\n'), ((2897, 2930), 'soundcard.get_microphone', 'soundcard.get_microphone', (['"""Cable"""'], {}), "('Cable')\n", (2921, 2930), False, 'import soundcard\n'), ((767, 794), 'soundcard.default_speaker', 'soundcard.default_speaker', ([], {}), '()\n', (792, 794), False, 'import soundcard\n'), ((871, 901), 'soundcard.default_microphone', 'soundcard.default_microphone', ([], {}), '()\n', (899, 901), False, 'import soundcard\n'), ((1010, 1040), 'soundcard.default_microphone', 'soundcard.default_microphone', ([], {}), '()\n', (1038, 1040), False, 'import soundcard\n'), ((2321, 2359), 'soundcard.get_speaker', 'soundcard.get_speaker', (['"""Soundflower64"""'], {}), "('Soundflower64')\n", (2342, 2359), False, 'import soundcard\n'), ((3016, 3057), 'soundcard.get_microphone', 'soundcard.get_microphone', (['"""Soundflower64"""'], {}), "('Soundflower64')\n", (3040, 3057), False, 'import soundcard\n'), ((2476, 2505), 'soundcard.get_speaker', 'soundcard.get_speaker', (['"""Null"""'], {}), "('Null')\n", (2497, 2505), False, 'import soundcard\n'), ((3107, 3162), 'soundcard.get_microphone', 'soundcard.get_microphone', (['"""Null"""'], {'include_loopback': '(True)'}), "('Null', include_loopback=True)\n", (3131, 3162), False, 'import soundcard\n')]
|
import os
from sys import argv, stdout
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import tensorflow as tf
import numpy as np
import scipy
import scipy.io
from itertools import product as prod
import time
from tensorflow.python.client import timeline
import cProfile
from sys import argv, stdout
from get_data import *
import pathlib
from noise_models_and_integration import *
from architecture import *
# from experiments import noise_1_paramas as noise_params
def variation_acc2_local_disturb(sess,
network,
x_,
keep_prob,
saver,
test_input,
test_target,
params):
eps = 10 ** (-params.eps_order)
# restoring saved model
saver.restore(sess, "weights/dim_{}/{}/gam_{}_alfa_{}.ckpt".format(params.model_dim, params.noise_name, params.gamma, params.alpha))
# initializoing resulting tensor, first two dimensions corresponds to coordinate which will be disturbed, on the last dimension, there will be added variation of outputs
results = np.zeros((n_ts, controls_nb, len(np.array(test_input))))
print(len(test_input))
print(np.shape(results))
iter = -1
for sample_nb in range(len(np.array(test_input))):
# taking sample NCP
origin_NCP = test_input[sample_nb]
# taking target superoperator corresponding to the NCP
origin_superoperator = test_target[sample_nb]
tf_result = False
# calculating nnDCP corresponding to input NCP
pred_DCP = get_prediction(sess, network, x_, keep_prob, np.reshape(origin_NCP, [1, params.n_ts, params.controls_nb]))
# calculating superoperator from nnDCP
sup_from_pred_DCP = integrate_lind(pred_DCP[0], tf_result, params)
print("sanity check")
acceptable_error = fidelity_err([origin_superoperator, sup_from_pred_DCP], params.dim, tf_result)
print("predicted DCP", acceptable_error)
print("---------------------------------")
############################################################################################################
#if sanity test is above assumed error then the experiment is performed
if acceptable_error <= params.accept_err:
iter += 1
# iteration over all coordinates
for (t, c) in prod(range(params.n_ts), range(params.controls_nb)):
new_NCP = origin_NCP
if new_NCP[t, c] < (1 - eps):
new_NCP[t, c] += eps
else:
new_NCP[t, c] -= eps
sup_from_new_NCP = integrate_lind(new_NCP, tf_result, params)
new_DCP = get_prediction(sess, network, x_, keep_prob,
np.reshape(new_NCP, [1, n_ts, controls_nb]))
sup_form_new_DCP = integrate_lind(new_DCP[0], tf_result, params)
error = fidelity_err([sup_from_new_NCP, sup_form_new_DCP], params.dim, tf_result)
#print(error)
# if predicted nnDCP gives wrong superopertaor, then we add not variation of output, but some label
if error <= params.accept_err:
results[t, c, iter] = np.linalg.norm(pred_DCP - new_DCP)
else:
results[t, c, iter] = -1
print(iter)
print(np.shape(results))
return results
def experiment_loc_disturb(params):
###########################################
# PLACEHOLDERS
###########################################
# input placeholder
x_ = tf.placeholder(tf.float32, [None, params.n_ts, params.controls_nb])
# output placeholder
y_ = tf.placeholder(tf.complex128, [None, params.supeop_size, params.supeop_size])
# dropout placeholder
keep_prob = tf.placeholder(tf.float32)
# creating the graph
network = my_lstm(x_, keep_prob, params)
# instance for saving the model
saver = tf.train.Saver()
# loading the data
(_, _, test_input, test_target) = get_data(params.train_set_size, params.test_set_size, params.model_dim)
# maintaining the memory
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
# essential function which executes the experiment
result = variation_acc2_local_disturb(sess,
network,
x_,
keep_prob,
saver,
test_input,
test_target,
params)
sess.close()
tf.reset_default_graph()
return result
def train_and_predict(params, file_name):
###########################################
# PLACEHOLDERS
###########################################
# input placeholder
x_ = tf.placeholder(tf.float32, [None, params.n_ts, params.controls_nb])
# output placeholder
y_ = tf.placeholder(tf.complex128, [None, params.supeop_size, params.supeop_size])
# dropout placeholder
keep_prob = tf.placeholder(tf.float32)
# creating the graph
network = my_lstm(x_, keep_prob, params)
# instance for saving the model
saver = tf.train.Saver()
# loading the data
(train_input, train_target, test_input, test_target) = get_data(params.train_set_size,
params.test_set_size,
params.model_dim,
params.data_type)
# maintaining the memory
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
# training the network
(acc,train_table,test_table) = fit(sess,
network,
x_,
y_,
keep_prob,
train_input,
train_target,
test_input,
test_target,
params)
# making prediction by trained model
pred = get_prediction(sess, network, x_, keep_prob, test_input)
# saving trained model
saver.save(sess, "weights/weights_from_{}.ckpt".format(file_name))
sess.close()
tf.reset_default_graph()
return (pred,acc,train_table,test_table)
# ---------------------------------------------------------------------------
def main(testing_effectiveness,argv_number):
config_path = "configurations/"
file_name = 'config{}.txt'.format(argv_number)
file = open(config_path+file_name, "r")
parameters = dict_to_ntuple(eval(file.read()), "parameters")
print(parameters.activ_fn)
pathlib.Path("weights/dim_{}/{}".format(parameters.model_dim, parameters.noise_name)).mkdir(parents=True, exist_ok=True)
if testing_effectiveness:
pathlib.Path("results/prediction/dim_{}".format(parameters.model_dim)).mkdir(parents=True, exist_ok=True)
# main functionality
if os.path.isfile("results/eff_fid_lstm/experiment_{}".format(file_name[0:-4])+".npz"):
statistic = list(np.load("results/eff_fid_lstm/experiment_{}".format(file_name[0:-4])+".npz")["arr_0"][()])
else:
statistic = []
for i in range(5):
pred, acc, train_table, test_table = train_and_predict(parameters,file_name)
# statistic.append(acc)
statistic.append(pred)
# save the results
print(acc)
# np.savez("results/eff_fid_lstm/experiment_{}".format(file_name[0:-4]), statistic)
np.savez("results/prediction/experiment_{}".format(file_name[0:-4]), statistic)
else:
# main functionality
data = experiment_loc_disturb(n_ts,
gamma,
alpha,
evo_time,
supeop_size,
controls_nb,
train_set_size,
test_set_size,
size_of_lrs,
noise_name,
model_dim,
eps,
accept_err)
pathlib.Path("results/NN_as_approx/dim_{}".format(model_dim)).mkdir(parents=True, exist_ok=True)
np.savez("results/NN_as_approx/experiment_{}".format(file_name[0:-4]), data)
file.close()
if __name__ == "__main__":
# prepare dirs for the output files
# Note: change the below value if you have already trained the network
# train_model = True
if len(argv) == 2:
argv_number = int(argv[1])
else:
argv_number = 63
main(True,argv_number )
|
[
"tensorflow.reset_default_graph",
"numpy.reshape",
"tensorflow.placeholder",
"tensorflow.train.Saver",
"tensorflow.Session",
"numpy.array",
"numpy.linalg.norm",
"tensorflow.ConfigProto",
"numpy.shape"
] |
[((3720, 3787), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, params.n_ts, params.controls_nb]'], {}), '(tf.float32, [None, params.n_ts, params.controls_nb])\n', (3734, 3787), True, 'import tensorflow as tf\n'), ((3822, 3899), 'tensorflow.placeholder', 'tf.placeholder', (['tf.complex128', '[None, params.supeop_size, params.supeop_size]'], {}), '(tf.complex128, [None, params.supeop_size, params.supeop_size])\n', (3836, 3899), True, 'import tensorflow as tf\n'), ((3942, 3968), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (3956, 3968), True, 'import tensorflow as tf\n'), ((4090, 4106), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (4104, 4106), True, 'import tensorflow as tf\n'), ((4284, 4300), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (4298, 4300), True, 'import tensorflow as tf\n'), ((4902, 4926), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (4924, 4926), True, 'import tensorflow as tf\n'), ((5138, 5205), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, params.n_ts, params.controls_nb]'], {}), '(tf.float32, [None, params.n_ts, params.controls_nb])\n', (5152, 5205), True, 'import tensorflow as tf\n'), ((5240, 5317), 'tensorflow.placeholder', 'tf.placeholder', (['tf.complex128', '[None, params.supeop_size, params.supeop_size]'], {}), '(tf.complex128, [None, params.supeop_size, params.supeop_size])\n', (5254, 5317), True, 'import tensorflow as tf\n'), ((5360, 5386), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (5374, 5386), True, 'import tensorflow as tf\n'), ((5508, 5524), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (5522, 5524), True, 'import tensorflow as tf\n'), ((5944, 5960), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (5958, 5960), True, 'import tensorflow as tf\n'), ((6628, 6652), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (6650, 6652), True, 'import tensorflow as tf\n'), ((1284, 1301), 'numpy.shape', 'np.shape', (['results'], {}), '(results)\n', (1292, 1301), True, 'import numpy as np\n'), ((3496, 3513), 'numpy.shape', 'np.shape', (['results'], {}), '(results)\n', (3504, 3513), True, 'import numpy as np\n'), ((4353, 4378), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (4363, 4378), True, 'import tensorflow as tf\n'), ((6013, 6038), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (6023, 6038), True, 'import tensorflow as tf\n'), ((1349, 1369), 'numpy.array', 'np.array', (['test_input'], {}), '(test_input)\n', (1357, 1369), True, 'import numpy as np\n'), ((1709, 1769), 'numpy.reshape', 'np.reshape', (['origin_NCP', '[1, params.n_ts, params.controls_nb]'], {}), '(origin_NCP, [1, params.n_ts, params.controls_nb])\n', (1719, 1769), True, 'import numpy as np\n'), ((1222, 1242), 'numpy.array', 'np.array', (['test_input'], {}), '(test_input)\n', (1230, 1242), True, 'import numpy as np\n'), ((2902, 2945), 'numpy.reshape', 'np.reshape', (['new_NCP', '[1, n_ts, controls_nb]'], {}), '(new_NCP, [1, n_ts, controls_nb])\n', (2912, 2945), True, 'import numpy as np\n'), ((3362, 3396), 'numpy.linalg.norm', 'np.linalg.norm', (['(pred_DCP - new_DCP)'], {}), '(pred_DCP - new_DCP)\n', (3376, 3396), True, 'import numpy as np\n')]
|
from typing import Dict, List, Any
import numpy
from overrides import overrides
from ..instance import TextInstance, IndexedInstance
from ...data_indexer import DataIndexer
class TaggingInstance(TextInstance):
"""
A ``TaggingInstance`` represents a passage of text and a tag sequence over that text.
There are some sticky issues with tokenization and how exactly the label is specified. For
example, if your label is a sequence of tags, that assumes a particular tokenization, which
interacts in a funny way with our tokenization code. This is a general superclass containing
common functionality for most simple sequence tagging tasks. The specifics of reading in data
from a file and converting that data into properly-indexed tag sequences is left to subclasses.
"""
def __init__(self, text: str, label: Any, index: int=None):
super(TaggingInstance, self).__init__(label, index)
self.text = text
def __str__(self):
return "TaggedSequenceInstance(" + self.text + ", " + str(self.label) + ")"
@overrides
def words(self) -> Dict[str, List[str]]:
words = self._words_from_text(self.text)
words['tags'] = self.tags_in_label()
return words
def tags_in_label(self):
"""
Returns all of the tag words in this instance, so that we can convert them into indices.
This is called in ``self.words()``. Not necessary if you have some pre-indexed labeling
scheme.
"""
raise NotImplementedError
def _index_label(self, label: Any, data_indexer: DataIndexer) -> List[int]:
"""
Index the labels. Since we don't know what form the label takes, we leave it to subclasses
to implement this method. If you need to convert tag names into indices, use the namespace
'tags' in the ``DataIndexer``.
"""
raise NotImplementedError
def to_indexed_instance(self, data_indexer: DataIndexer):
text_indices = self._index_text(self.text, data_indexer)
label_indices = self._index_label(self.label, data_indexer)
assert len(text_indices) == len(label_indices), "Tokenization is off somehow"
return IndexedTaggingInstance(text_indices, label_indices, self.index)
class IndexedTaggingInstance(IndexedInstance):
def __init__(self, text_indices: List[int], label: List[int], index: int=None):
super(IndexedTaggingInstance, self).__init__(label, index)
self.text_indices = text_indices
@classmethod
@overrides
def empty_instance(cls):
return TaggingInstance([], label=None, index=None)
@overrides
def get_lengths(self) -> Dict[str, int]:
return self._get_word_sequence_lengths(self.text_indices)
@overrides
def pad(self, max_lengths: Dict[str, int]):
self.text_indices = self.pad_word_sequence(self.text_indices, max_lengths,
truncate_from_right=False)
self.label = self.pad_sequence_to_length(self.label,
desired_length=max_lengths['num_sentence_words'],
default_value=lambda: self.label[0],
truncate_from_right=False)
@overrides
def as_training_data(self):
text_array = numpy.asarray(self.text_indices, dtype='int32')
label_array = numpy.asarray(self.label, dtype='int32')
return text_array, label_array
|
[
"numpy.asarray"
] |
[((3384, 3431), 'numpy.asarray', 'numpy.asarray', (['self.text_indices'], {'dtype': '"""int32"""'}), "(self.text_indices, dtype='int32')\n", (3397, 3431), False, 'import numpy\n'), ((3454, 3494), 'numpy.asarray', 'numpy.asarray', (['self.label'], {'dtype': '"""int32"""'}), "(self.label, dtype='int32')\n", (3467, 3494), False, 'import numpy\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 23 19:53:22 2021
@author: <NAME> (<EMAIL>) at USTC
This script refers to some theories and codes of Obspy/MoPaD/Introduction to Seismology (Yongge Wan):
1) The MoPaD program (https://github.com/geophysics/MoPaD);
2) str_dip_rake to mt;
3) The conversion between str_dip_rake and A/N vector;
4) The conversion between A/N vector and P/T/N vector;
5) mt to P/T/N vector;
6) P/T/N vector to P/T/N vector's stirke and dip;
7) project station to beachball;
8) Hudson plot
9) Decompose of mt: isotropic + deviatoric = isotropic + DC + CLVD;
10) Describe_fault_plane with two str_dip_rake.
Modify history:
1) May 23 19:53:22 2021 || Fu Yin at USTC || The initial release.
2) ...
"""
import numpy as np
import math
from math import pi
from math import sin,cos,tan,atan2,atan,sqrt,acos
#%%######################################################
# (2) str_dip_rake to mt
#########################################################
def str_dip_rake2MT(strike,dip,rake):
"""
Input: fault plane' strike dip and rake in degrees.
strike : [0, 360)
dip : [0, 90]
rake : [-180, 180)
Output: a moment tensor object in NED system.
"""
strike = strike/180*pi
dip = dip/180*pi
rake = rake/180*pi
M0 = 1
Mxx = -M0*( sin(dip) * cos(rake) * sin(2*strike) + sin(2*dip) * sin(rake) * sin(strike)**2 )
Myy = M0*( sin(dip) * cos(rake) * sin(2*strike) - sin(2*dip) * sin(rake) * cos(strike)**2 )
Mzz = M0*( sin(2*dip) * sin(rake) )
Mxy = M0*( sin(dip) * cos(rake) * cos(2*strike) + 1/2* sin(2*dip) * sin(rake) * sin(2*strike) )
Mxz = -M0*( cos(dip) * cos(rake) * cos(strike) + cos(2*dip) * sin(rake) * sin(strike) )
Myz = -M0*( cos(dip) * cos(rake) * sin(strike) - cos(2*dip) * sin(rake) * cos(strike) )
A = MTensor([Mxx, Myy, Mzz, Mxy, Mxz, Myz])
return A
#%%###################################################################
# (3) The conversion between str_dip_rake and A/N vector
######################################################################
# str_dip_rake to A/N vector
def str_dip_rake2AN(strike,dip,rake):
"""
Input: fault plane' strike dip and rake in degrees.
strike : [0, 360)
dip : [0, 90]
rake : [-180, 180)
Output: slip vector(A) and fault plane's normal vector(N) in NED system.
"""
strike = strike/180*pi
dip = dip/180*pi
rake = rake/180*pi
A=np.array([ cos(rake)*cos(strike) + sin(rake)*cos(dip)*sin(strike),
cos(rake)*sin(strike) - sin(rake)*cos(dip)*cos(strike),
-sin(rake)*sin(dip)] )
N=np.array([ -sin(strike)*sin(dip),
cos(strike)*sin(dip),
-cos(dip)] )
return A,N
# A/N vector to str_dip_rake
def AN2str_dip_rake(A,N):
"""
Input: slip vector(A) and fault plane's normal vector(N) in NED system.
Output: fault plane' strike dip and rake.
strike : [0, 360)
dip : [0, 90]
rake : [-180, 180)
"""
if abs(N[2]+1) < 0.00001: # nz=-1: the fault plane is horizontal
strike = atan2(A[1],A[0]) # The direction of slip is also the strike, because the fault plane is horizontal
dip = 0.0
else:
strike = atan2(-N[0],N[1])
if abs(N[2]-0) < 0.00001: # nz=-1: the fault plane is vertical
dip = pi/2
elif abs(sin(strike)) > abs(cos(strike)):
dip = atan( (N[0]/sin(strike)) / N[2] )
else:
dip = atan( (-N[1]/cos(strike)) / N[2] )
cos_rake = A[0]*cos(strike) + A[1]*sin(strike)
if abs(A[2]-0) > 0.0000001: # az!=0: consider the effect of dip
if abs(dip-0) > 0.000001:
rake = atan2(-A[2]/sin(dip),cos_rake)
else:
rake = atan2(-100000000.0*A[2],cos_rake)
else: # az=0: don't consider the effect of dip
if cos_rake > 1:
cos_rake = 1
if cos_rake < -1:
cos_rake = -1
rake = acos(cos_rake)
if dip < 0:
dip = -dip
strike = strike+pi # strike need to be in the opposite direction
if strike >= 2*pi:
strike = strike-2*pi
if strike < 0:
strike = strike+2*pi
strike = strike*180/pi
dip = dip*180/pi
rake = rake*180/pi
A = str_dip_rake(strike,dip,rake)
return A
#%%###################################################################
# (4) The conversion between A/N vector and P/T/N vector
######################################################################
# Calculate the T-axis, P-axis and N-axis according to the slip vector (A) and fault plane direction vector (N)
def AN2TPN(A,N):
"""
Input: slip vector(A) and fault plane's normal vector(N) in NED system.
Output: Tension-axis vector(T), Pressure-axis vector(P) and Null-axis
vector(Null) in NED system.
"""
T=sqrt(2)/2*(A+N)
P=sqrt(2)/2*(A-N)
Null=np.cross(P,T)
return T,P,Null
# Calculate the slip vector (A) and fault plane direction vector (N) according to the T-axis and P-axis
def TP2AN(T,P):
"""
Input: Tension-axis vector(T) and Pressure-axis vector(P) in NED system.
Output: slip vector(A) and fault plane's normal vector(N) in NED system.
"""
A=sqrt(2)/2*(T+P)
N=sqrt(2)/2*(T-P)
return A,N
#%%#######################################################
# (5) mt(in NED system) to P/T/N vector
##########################################################
def MT2TPN(MT_raw):
"""
Input: moment tensor in NED system.
Output: Tension-axis vector(T), Pressure-axis vector(P) and Null-axis
vector(Null) in NED system.
"""
M = MT_raw.mt
eigen_val, eigen_vec = np.linalg.eig(M)
# The TNP axis should be arranged in order of eigenvalues from largest to smallest
eigen_vec_ord_axis = np.real( np.take(eigen_vec, np.argsort(-eigen_val), 1) )
T_axis = eigen_vec_ord_axis[:, 0]
N_axis = eigen_vec_ord_axis[:, 1]
P_axis = eigen_vec_ord_axis[:, 2]
return T_axis, P_axis, N_axis
#%%##############################################################
# (6) P/T/N vector to P/T/N vector's stirke and dip
#################################################################
def vector2str_dip(vector):
"""
Input: a principal axis vector, such as eigenvectors P/T/N of the moment tensor
object in NED system.
Output: a principal axis' strike and dip.
strike : [0, 360)
dip : [0, 90]
"""
x=vector[0]
y=vector[1]
z=vector[2]
strike = atan2(y,x)*180/pi
r = sqrt(x**2+y**2)
dip = atan2(z,r)*180/pi
if dip < 0.0:
dip = -dip
strike = strike-180
if strike < 0:
strike = strike+360
if strike > 360:
strike = strike-360
A = Axis_str_dip(strike,dip)
return A
#%%##############################################################
# (7) project station to beachball
#################################################################
# According to the strike(azimuth) and takeoff Angle (or dip, for the PTN
# axis, you need to make your own Angle transformation pi/2-TKO=dip)
# projected onto the beachball
def project_beachball(AZM, TKO, R=1, menthod='schmidt'):
"""
Input in NED system:
AZM means azimuth (equal to strike) in degrees.
TKO means takeoff angle ( pi/2-TKO=dip equal to dip) in degrees.
R means beachball radius that you want to plot.
note: Takeoff Angle is the angle with the vertical direction,
DIP is the angle with the horizontal plane.
Output:
X and Y coordinates in E and N direction respectively, and
the lower left corner of the circle is the origin.
"""
AZM = AZM/180*pi
TKO = TKO/180*pi
# Schmidt (Lambert, equal-area) default
if menthod=='schmidt':
r = math.sqrt(2)*sin(TKO/2)
# Wulff projection (Stereographic, equal-angle) not recommmended
elif menthod=='wulff':
r = tan(TKO/2)
else:
raise ValueError('projection error!')
X = R*r*sin(AZM)+R
Y = R*r*cos(AZM)+R
return X,Y
#%%#########################################
# (9) Hudson plot
############################################
# Hudson, J.A., <NAME>, and R.M.Rogers (1989), "Source type plot for inversion of the moment tensor",\
# J. Geophys. Res., 94, 765?74
def M2kT_space(MT):
# 1. full-moment
M = MT
# M = np.array([Mxx, Mxy, Mxz, Mxy, Myy, Myz, Mxz, Myz, Mzz]).reshape(3, 3)
# 2.isotropic part
m_iso = 1./3 * np.trace(M)
M_iso = np.diag(np.array( [m_iso,m_iso,m_iso] ))
# 3.deviatoric part
M_devi = M - M_iso
# 4.eigenvalues and -vectors of M
devi_eigen_val, devi_eigen_vec = np.linalg.eig(M_devi)
# 5.eigenvalues in ascending order:
devi_eigen_val_ord = np.real( np.take(devi_eigen_val, np.argsort(-devi_eigen_val)) ) # descend order
if ( abs(m_iso) + max( abs(devi_eigen_val_ord[0]),abs(devi_eigen_val_ord[2]) ) ) == 0 :
raise TypeError("MomentTensor cannot be translated into [k,T] space.")
else:
k = m_iso / ( abs(m_iso) + max(abs(devi_eigen_val_ord[0]), abs(devi_eigen_val_ord[2])) )
if max(abs(devi_eigen_val_ord[0]), abs(devi_eigen_val_ord[2])) == 0:
T = 0
else:
T = 2*devi_eigen_val_ord[1] / max(abs(devi_eigen_val_ord[0]), abs(devi_eigen_val_ord[2]))
return k,T
def kT2UV_space(k,T):
tau = T*(1-abs(k))
if ( (tau>0) & (k<0) ) | ( (tau<0) & (k>0) ):
# 2nd and 4th quadrants
U = tau
V = k
elif ( tau < (4*k) ) & ( (tau>=0) & (k>=0) ):
# First quadrant, Region A
U = tau/(1-tau/2)
V = k/(1-tau/2)
elif ( tau >= (4*k) ) & ( (tau>=0) & (k>=0) ):
# First quadrant, Region B
U = tau/(1-2*k)
V = k/(1-2*k)
elif ( tau >= (4*k) ) & ( (tau<=0) & (k<=0) ):
# Third quadrant, Region A
U = tau/(1+tau/2)
V = k/(1+tau/2)
elif ( tau < (4*k) ) & ( (tau<=0) & (k<=0) ):
# Third quadrant, Region B
U = tau/(1+2*k)
V = k/(1+2*k)
else:
raise TypeError("def: kT2UV_space(k,T)")
return U,V
def Hudson_plot(ax, ms=2, marker_ms='o', color_ms='k', alpha_ms=0.5, alpha_text=0.7, fontsize=6):
######################
## 1. Fill and draw the border
ax.fill_between(x=[-1,0],y1=[0,0],y2=[0,1],color='k', alpha=0.05) # fill the second quadrant
ax.fill_between(x=[0,1],y1=[0,0],y2=[-1,0],color='k', alpha=0.05) # fill the fourth quadrant
ax.plot([0, 4/3, 0, -4/3, 0], [1, 1/3, -1, -1/3, 1],
linestyle='-', color='k', lw=1, alpha=0.6)
ax.plot([-1, 1], [0, 0], linestyle='-', color='k', lw=1, alpha=0.6)
ax.plot([0, 0], [-1, 1], linestyle='-', color='k', lw=1, alpha=0.6)
######################
## 2. Draw the inner dotted line
U_vector = [];V_vector = []
for i in np.linspace(-1, 1, num=100):
k = i
T = 0.5
U,V = kT2UV_space(k=k, T=T)
U_vector.append(U)
V_vector.append(V)
ax.plot(U_vector, V_vector, linestyle='--', color='k', lw=1, alpha=0.6)
U_vector = [];V_vector = []
for i in np.linspace(-1, 1, num=100):
k = i
T = -0.5
U,V = kT2UV_space(k=k, T=T)
U_vector.append(U)
V_vector.append(V)
ax.plot(U_vector, V_vector, linestyle='--', color='k', lw=1, alpha=0.6)
U_vector = [];V_vector = []
for i in np.linspace(-1, 1, num=100):
k = 0.5
T = i
U,V = kT2UV_space(k=k, T=T)
U_vector.append(U)
V_vector.append(V)
ax.plot(U_vector, V_vector, linestyle='--', color='k', lw=1, alpha=0.6)
U_vector = [];V_vector = []
for i in np.linspace(-1, 1, num=100):
k = -0.5
T = i
U,V = kT2UV_space(k=k, T=T)
U_vector.append(U)
V_vector.append(V)
ax.plot(U_vector, V_vector, linestyle='--', color='k', lw=1, alpha=0.6)
######################
## 3. Draw marker points
# ms=2
# marker_ms = 'o'
# color_ms = 'k'
# alpha_ms = 0.5
# alpha_text = 0.7
# fontsize = 7
U,V = kT2UV_space(k=1, T=1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'ISO+ (Explosion)',horizontalalignment='center', verticalalignment='bottom',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=-1, T=1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'ISO- (Implosion)',horizontalalignment='center', verticalalignment='top',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=0, T=1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'CLVD (-)',horizontalalignment='left', verticalalignment='top',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=-5/9, T=1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'Anticrack',horizontalalignment='left', verticalalignment='top',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=0, T=-1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'CLVD (+)',horizontalalignment='right', verticalalignment='bottom',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=5/9, T=-1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'Tensile Crack',horizontalalignment='right', verticalalignment='bottom',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=0, T=0)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'DC',horizontalalignment='center', verticalalignment='bottom',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=1/3, T=-1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'LVD (+)',horizontalalignment='right', verticalalignment='bottom',\
fontsize=fontsize, color='k',alpha=alpha_text)
U,V = kT2UV_space(k=-1/3, T=1)
ax.plot(U,V, marker='o', color=color_ms, ms=ms, alpha=alpha_ms)
ax.text(U,V,'LVD (-)',horizontalalignment='left', verticalalignment='top',\
fontsize=fontsize, color='k',alpha=alpha_text)
######################
## 4. Set the axes
ax.set_xlim(-4/3-0.1, 4/3+0.1)
ax.set_ylim(-1-0.1, 1+0.1)
ax.set_aspect("equal")
ax.set_axis_off()
#%%###########################################################
# (10) Describe_fault_plane with two str_dip_rake.
##############################################################
def describe_fault_plane(fm):
"""
Input: moment tensor object in NED system.
Output: [strike_1, dip_1, rake_1] and [strike_2, dip_2, rake_2]
"""
MT = MTensor(fm)
T_axis, P_axis, N_axis = MT2TPN(MT)
A,N = TP2AN(T_axis,P_axis)
a = AN2str_dip_rake(A,N)
strike_1 = a.strike
dip_1 = a.dip
rake_1 = a.rake
b = AN2str_dip_rake(N,A)
strike_2 = b.strike
dip_2 = b.dip
rake_2 = b.rake
return np.array([[strike_1,dip_1,rake_1],[strike_2, dip_2, rake_2]])
#%%################################
# (11) object.
###################################
class MTensor(object):
"""
Adapted from obspy.A moment tensor in NED system.
>>> a = MTensor([1, 1, 0, 0, 0, -1]) # MTensor(Mxx, Myy, Mzz, Mxy, Mxz, Myz)
>>> b = MTensor(np.array([[1, 0, 0], [0, 1, -1], [0, -1, 0]]))
>>> c = MTensor([100,50,30])
>>> a.mt
array([[ 1, 0, 0],
[ 0, 1, -1],
[ 0, -1, 0]])
>>> b.yz
-1
"""
def __init__(self, a):
if len(a) == 3 and isinstance(a, list):
# strike dip rake
MT = str_dip_rake2MT(a[0],a[1],a[2])
self.mt = MT.mt
elif len(a) == 6:
# six independent components
self.mt = np.array([[a[0], a[3], a[4]],
[a[3], a[1], a[5]],
[a[4], a[5], a[2]]])
elif isinstance(a, np.ndarray) and a.shape == (3, 3):
# full matrix
self.mt = a
else:
raise TypeError("Wrong size of input parameter.")
@property
def mt_normalized(self):
return self.mt / np.linalg.norm(self.mt)
@property
def xx(self):
return self.mt[0][0]
@property
def xy(self):
return self.mt[0][1]
@property
def xz(self):
return self.mt[0][2]
@property
def yz(self):
return self.mt[1][2]
@property
def yy(self):
return self.mt[1][1]
@property
def zz(self):
return self.mt[2][2]
class str_dip_rake(object):
"""
Describing the faultplanes of the Double Couple
Strike dip and rake values are in degrees.
strike : [0, 360)
dip : [0, 90]
rake : [-180, 180)
>>> a = str_dip_rake(20, 50, 10)
>>> a.strike
20
>>> a.dip
50
>>> a.rake
10
"""
def __init__(self, strike=0, dip=0,rake=0):
self.strike = strike
self.dip = dip
self.rake = rake
class Axis_str_dip(object):
"""
A principal axis' strike and dip.
Used in P/T/N's axis
Strike and dip values are in degrees.
strike : [0, 360)
dip : [0, 90]
>>> a = Axis_str_dip(20, 50)
>>> a.strike
20
>>> a.dip
50
"""
def __init__(self, strike=0, dip=0):
self.strike = strike
self.dip = dip
#%%###########################################################################
# (9) Decompose of mt: isotropic + deviatoric = isotropic + DC + CLVD
##############################################################################
class Decompose(object):
"""
Creates a Decompose object on the basis of a provided MomentTensor object.
For example:
m = str_dip_rake2MT(120,50,70)
AA = Decompose(m)
AA.decomposition_iso_DC_CLVD()
AA.M_DC_percentage ->
"""
def __init__(self, MT_raw):
self.M = MT_raw.mt
self.M_iso = None
self.M_devi = None
self.M_DC = None
self.M_CLVD = None
self.M0 = None
self.Mw = None
self.M_iso_percentage = None
self.M_DC_percentage = None
self.M_CLVD_percentage = None
self.eigen_val = None
self.eigen_vec = None
self.F = None
def decomposition_iso_DC_CLVD(self):
"""
Input: moment tensor in NED system.
Output: Tension-axis vector(T), Pressure-axis vector(P) and Null-axis
vector(Null) in NED system.
Decomposition according Aki & Richards and Jost & Herrmann into
isotropic + deviatoric
= isotropic + DC + CLVD
parts of the input moment tensor.
results are given as attributes, callable via the get_* function:
DC, CLVD, DC_percentage, seismic_moment, moment_magnitude
"""
# 1. full-moment
M = self.M
# 2.isotropic part
m_iso = 1./3 * np.trace(M)
M_iso = np.diag(np.array( [m_iso,m_iso,m_iso] ))
m0_iso = abs(m_iso)
# 3.deviatoric part
M_devi = M - M_iso
# 4.eigenvalues and -vectors of M
eigen_val, eigen_vec = np.linalg.eig(M)
# 5.eigenvalues in ascending order:
eigen_val_ord = np.real( np.take(eigen_val, np.argsort(abs(eigen_val))) )
eigen_vec_ord = np.real( np.take(eigen_vec, np.argsort(abs(eigen_val)), 1) )
# 6.named according to Jost & Herrmann:
# a1 = eigen_vec_ord[:, 0]
a2 = eigen_vec_ord[:, 1]
a3 = eigen_vec_ord[:, 2]
F = -(eigen_val_ord[0]-m_iso) / (eigen_val_ord[2]-m_iso)
# 7.decompose
M_DC = (eigen_val_ord[2]-m_iso) * (1 - 2 * F) * (np.outer(a3, a3) - np.outer(a2, a2))
M_CLVD = M_devi - M_DC
# 8.according to Bowers & Hudson:
M0 = max(abs(eigen_val_ord)) # Seismic moment (in Nm)
Mw = np.log10(M0 * 1.0e7) / 1.5 - 16.1/1.5 # moment_magnitude unit is Mw
M_iso_percentage = int(round(m0_iso / M0 * 100, 6))
M_DC_percentage = int(round((1 - 2 * abs(F)) *
(1 - M_iso_percentage / 100.) * 100, 6))
M_CLVD_percentage = 100-M_iso_percentage-M_DC_percentage
self.M_iso = M_iso
self.M_devi = M_devi
self.M_DC = M_DC
self.M_CLVD = M_CLVD
self.M0 = M0
self.Mw = Mw
self.M_iso_percentage = M_iso_percentage
self.M_DC_percentage = M_DC_percentage
self.M_CLVD_percentage = M_CLVD_percentage
self.eigen_val = eigen_val
self.eigen_vec = eigen_vec
self.F = F
def help(self):
print("Incluing function:\n\
self.M\n\
self.M_iso\n\
self.M_devi\n\
self.M_DC\n\
self.M_CLVD\n\
self.M0\n\
self.Mw\n\
self.M_iso_percentage\n\
self.M_DC_percentage\n\
self.M_CLVD_percentage\n\
self.eigen_val\n\
self.eigen_vec\n\
self.F")
def print_self(self):
print("self.M:",self.M,"\n")
print("self.M_iso:",self.M_iso,"\n")
print("self.M_devi:",self.M_devi,"\n")
print("self.M_DC:",self.M_DC,"\n")
print("self.M_CLVD:",self.M_CLVD,"\n")
print("self.M0:",self.M0,"\n")
print("self.Mw:",self.Mw,"\n")
print("self.M_iso_percentage:",self.M_iso_percentage,"\n")
print("self.M_DC_percentage:",self.M_DC_percentage,"\n")
print("self.M_CLVD_percentage:",self.M_CLVD_percentage,"\n")
print("self.eigen_val:",self.eigen_val,"\n")
print("self.eigen_vec:",self.eigen_vec,"\n")
print("self.F:",self.F,"\n")
|
[
"numpy.trace",
"numpy.log10",
"numpy.linalg.eig",
"numpy.cross",
"math.acos",
"math.tan",
"math.sqrt",
"math.cos",
"numpy.array",
"numpy.linspace",
"numpy.argsort",
"numpy.outer",
"math.atan2",
"numpy.linalg.norm",
"math.sin"
] |
[((5395, 5409), 'numpy.cross', 'np.cross', (['P', 'T'], {}), '(P, T)\n', (5403, 5409), True, 'import numpy as np\n'), ((6191, 6207), 'numpy.linalg.eig', 'np.linalg.eig', (['M'], {}), '(M)\n', (6204, 6207), True, 'import numpy as np\n'), ((7085, 7106), 'math.sqrt', 'sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (7089, 7106), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((9273, 9294), 'numpy.linalg.eig', 'np.linalg.eig', (['M_devi'], {}), '(M_devi)\n', (9286, 9294), True, 'import numpy as np\n'), ((11444, 11471), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(100)'}), '(-1, 1, num=100)\n', (11455, 11471), True, 'import numpy as np\n'), ((11715, 11742), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(100)'}), '(-1, 1, num=100)\n', (11726, 11742), True, 'import numpy as np\n'), ((11987, 12014), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(100)'}), '(-1, 1, num=100)\n', (11998, 12014), True, 'import numpy as np\n'), ((12258, 12285), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)'], {'num': '(100)'}), '(-1, 1, num=100)\n', (12269, 12285), True, 'import numpy as np\n'), ((15703, 15767), 'numpy.array', 'np.array', (['[[strike_1, dip_1, rake_1], [strike_2, dip_2, rake_2]]'], {}), '([[strike_1, dip_1, rake_1], [strike_2, dip_2, rake_2]])\n', (15711, 15767), True, 'import numpy as np\n'), ((3321, 3338), 'math.atan2', 'atan2', (['A[1]', 'A[0]'], {}), '(A[1], A[0])\n', (3326, 3338), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3511, 3529), 'math.atan2', 'atan2', (['(-N[0])', 'N[1]'], {}), '(-N[0], N[1])\n', (3516, 3529), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((4396, 4410), 'math.acos', 'acos', (['cos_rake'], {}), '(cos_rake)\n', (4400, 4410), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((9084, 9095), 'numpy.trace', 'np.trace', (['M'], {}), '(M)\n', (9092, 9095), True, 'import numpy as np\n'), ((9116, 9147), 'numpy.array', 'np.array', (['[m_iso, m_iso, m_iso]'], {}), '([m_iso, m_iso, m_iso])\n', (9124, 9147), True, 'import numpy as np\n'), ((19984, 20000), 'numpy.linalg.eig', 'np.linalg.eig', (['M'], {}), '(M)\n', (19997, 20000), True, 'import numpy as np\n'), ((1620, 1632), 'math.sin', 'sin', (['(2 * dip)'], {}), '(2 * dip)\n', (1623, 1632), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1633, 1642), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1636, 1642), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3859, 3870), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (3862, 3870), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3878, 3889), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (3881, 3889), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((4124, 4160), 'math.atan2', 'atan2', (['(-100000000.0 * A[2])', 'cos_rake'], {}), '(-100000000.0 * A[2], cos_rake)\n', (4129, 4160), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((5348, 5355), 'math.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (5352, 5355), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((5370, 5377), 'math.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (5374, 5377), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((5728, 5735), 'math.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (5732, 5735), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((5750, 5757), 'math.sqrt', 'sqrt', (['(2)'], {}), '(2)\n', (5754, 5757), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((6348, 6370), 'numpy.argsort', 'np.argsort', (['(-eigen_val)'], {}), '(-eigen_val)\n', (6358, 6370), True, 'import numpy as np\n'), ((7058, 7069), 'math.atan2', 'atan2', (['y', 'x'], {}), '(y, x)\n', (7063, 7069), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((7111, 7122), 'math.atan2', 'atan2', (['z', 'r'], {}), '(z, r)\n', (7116, 7122), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((8378, 8390), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (8387, 8390), False, 'import math\n'), ((8391, 8403), 'math.sin', 'sin', (['(TKO / 2)'], {}), '(TKO / 2)\n', (8394, 8403), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((8510, 8522), 'math.tan', 'tan', (['(TKO / 2)'], {}), '(TKO / 2)\n', (8513, 8522), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((8590, 8598), 'math.sin', 'sin', (['AZM'], {}), '(AZM)\n', (8593, 8598), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((8613, 8621), 'math.cos', 'cos', (['AZM'], {}), '(AZM)\n', (8616, 8621), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((9394, 9421), 'numpy.argsort', 'np.argsort', (['(-devi_eigen_val)'], {}), '(-devi_eigen_val)\n', (9404, 9421), True, 'import numpy as np\n'), ((16964, 16987), 'numpy.linalg.norm', 'np.linalg.norm', (['self.mt'], {}), '(self.mt)\n', (16978, 16987), True, 'import numpy as np\n'), ((19757, 19768), 'numpy.trace', 'np.trace', (['M'], {}), '(M)\n', (19765, 19768), True, 'import numpy as np\n'), ((19793, 19824), 'numpy.array', 'np.array', (['[m_iso, m_iso, m_iso]'], {}), '([m_iso, m_iso, m_iso])\n', (19801, 19824), True, 'import numpy as np\n'), ((1449, 1464), 'math.sin', 'sin', (['(2 * strike)'], {}), '(2 * strike)\n', (1452, 1464), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1546, 1561), 'math.sin', 'sin', (['(2 * strike)'], {}), '(2 * strike)\n', (1549, 1561), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1684, 1699), 'math.cos', 'cos', (['(2 * strike)'], {}), '(2 * strike)\n', (1687, 1699), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1730, 1745), 'math.sin', 'sin', (['(2 * strike)'], {}), '(2 * strike)\n', (1733, 1745), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1785, 1796), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (1788, 1796), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1824, 1835), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (1827, 1835), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1877, 1888), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (1880, 1888), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1916, 1927), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (1919, 1927), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2758, 2766), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (2761, 2766), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2801, 2809), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (2804, 2809), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2829, 2840), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (2832, 2840), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2841, 2849), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (2844, 2849), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2869, 2877), 'math.cos', 'cos', (['dip'], {}), '(dip)\n', (2872, 2877), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((16564, 16634), 'numpy.array', 'np.array', (['[[a[0], a[3], a[4]], [a[3], a[1], a[5]], [a[4], a[5], a[2]]]'], {}), '([[a[0], a[3], a[4]], [a[3], a[1], a[5]], [a[4], a[5], a[2]]])\n', (16572, 16634), True, 'import numpy as np\n'), ((20508, 20524), 'numpy.outer', 'np.outer', (['a3', 'a3'], {}), '(a3, a3)\n', (20516, 20524), True, 'import numpy as np\n'), ((20527, 20543), 'numpy.outer', 'np.outer', (['a2', 'a2'], {}), '(a2, a2)\n', (20535, 20543), True, 'import numpy as np\n'), ((20737, 20762), 'numpy.log10', 'np.log10', (['(M0 * 10000000.0)'], {}), '(M0 * 10000000.0)\n', (20745, 20762), True, 'import numpy as np\n'), ((1426, 1434), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (1429, 1434), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1437, 1446), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (1440, 1446), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1465, 1477), 'math.sin', 'sin', (['(2 * dip)'], {}), '(2 * dip)\n', (1468, 1477), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1478, 1487), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1481, 1487), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1490, 1501), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (1493, 1501), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1523, 1531), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (1526, 1531), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1534, 1543), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (1537, 1543), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1562, 1574), 'math.sin', 'sin', (['(2 * dip)'], {}), '(2 * dip)\n', (1565, 1574), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1575, 1584), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1578, 1584), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1587, 1598), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (1590, 1598), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1661, 1669), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (1664, 1669), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1672, 1681), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (1675, 1681), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1718, 1727), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1721, 1727), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1762, 1770), 'math.cos', 'cos', (['dip'], {}), '(dip)\n', (1765, 1770), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1773, 1782), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (1776, 1782), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1799, 1811), 'math.cos', 'cos', (['(2 * dip)'], {}), '(2 * dip)\n', (1802, 1811), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1812, 1821), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1815, 1821), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1854, 1862), 'math.cos', 'cos', (['dip'], {}), '(dip)\n', (1857, 1862), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1865, 1874), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (1868, 1874), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1891, 1903), 'math.cos', 'cos', (['(2 * dip)'], {}), '(2 * dip)\n', (1894, 1903), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1904, 1913), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (1907, 1913), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2599, 2608), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (2602, 2608), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2609, 2620), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (2612, 2620), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2642, 2653), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (2645, 2653), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2673, 2682), 'math.cos', 'cos', (['rake'], {}), '(rake)\n', (2676, 2682), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2683, 2694), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (2686, 2694), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2716, 2727), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (2719, 2727), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2748, 2757), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (2751, 2757), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2789, 2800), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (2792, 2800), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3686, 3697), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (3689, 3697), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3705, 3716), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (3708, 3716), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((4072, 4080), 'math.sin', 'sin', (['dip'], {}), '(dip)\n', (4075, 4080), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((1705, 1717), 'math.sin', 'sin', (['(2 * dip)'], {}), '(2 * dip)\n', (1708, 1717), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2623, 2632), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (2626, 2632), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2633, 2641), 'math.cos', 'cos', (['dip'], {}), '(dip)\n', (2636, 2641), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2697, 2706), 'math.sin', 'sin', (['rake'], {}), '(rake)\n', (2700, 2706), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((2707, 2715), 'math.cos', 'cos', (['dip'], {}), '(dip)\n', (2710, 2715), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3749, 3760), 'math.sin', 'sin', (['strike'], {}), '(strike)\n', (3752, 3760), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n'), ((3816, 3827), 'math.cos', 'cos', (['strike'], {}), '(strike)\n', (3819, 3827), False, 'from math import sin, cos, tan, atan2, atan, sqrt, acos\n')]
|
import matplotlib
import numpy as np
import time
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
VOC_BBOX_LABEL_NAMES = (
'fly',
'bike',
'bird',
'boat',
'pin',
'bus',
'c',
'cat',
'chair',
'cow',
'table',
'dog',
'horse',
'moto',
'p',
'plant',
'shep',
'sofa',
'train',
'tv',
)
def vis_img(img, ax=None):
"""Visualize a color image.
Args:
img (~numpy.ndarray): An array of shape :math:`(3, height, width)`.
This is in RGB format and the range of its value is
:math:`[0, 255]`.
ax (matplotlib.axes.Axis): The visualization is displayed on this
axis. If this is :obj:`None` (default), a new axis is created.
Returns:
~matploblib.axes.Axes:
Returns the Axes object with the plot for further tweaking.
"""
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# CHW ==> HWC
img = img.transpose((1, 2, 0))
ax.imshow(img.astype(np.uint8))
return ax
def vis_bbox(img, bbox, label=None, score=None, ax=None):
"""
Visualize bounding boxes inside image.
:param img:
:param bbox:
:param label:
:param score:
:param ax:
:return:
"""
label_names = list(VOC_BBOX_LABEL_NAMES) + ['bg']
if label is not None and not len(bbox) == len(label):
raise ValueError('The length of label must be same as that of bbox')
if score is not None and not len(bbox) == len(score):
raise ValueError('The length of score must be same as that of bbox')
# Returns newly instantiated matplotlib.axes.Axes object if ax is None
ax = vis_img(img, ax=ax)
# If there is no bounding box to display, visualize the image and exit.
if len(bbox) == 0:
return ax
for i, bb in enumerate(bbox):
xy = (bb[1], bb[0])
height = bb[2] - bb[0]
width = bb[3] - bb[1]
ax.add_patch(plt.Rectangle(
xy, width, height, fill=False, edgecolor='red', linewidth=2))
caption = list()
if label is not None and label_names is not None:
lb = label[i]
if not (-1 <= lb < len(label_names)):
raise ValueError('No corresponding name is given')
caption.append(label_names[lb])
if score is not None:
sc = score[i]
caption.append('{:.2f}'.format(sc))
if len(caption) > 0:
ax.text(bb[1], bb[0],
':'.join(caption),
style='italic',
color='white',
bbox={'facecolor': (0.8, 0.2, 0.2), 'alpha': 0.9, 'pad': 1.5})
return ax
def fig2data(fig):
"""
brief Convert a Matplotlib figure to a 4D numpy array with RGBA
channels and return it
@param fig: a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw()
# Get the RGBA buffer from the figure
w, h = fig.canvas.get_width_height()
buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
buf.shape = (w, h, 4)
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll(buf, 3, axis=2)
return buf.reshape((h, w, 4))
def fig4vis(fig):
"""
convert figure to ndarray
"""
ax = fig.get_figure()
img_data = fig2data(ax).astype(np.int32)
plt.close()
# HWC ==> CHW
return img_data[:, :, :3].transpose((2, 0, 1)) / 255.
def visdom_bbox(*args, **kwargs):
fig = vis_bbox(*args, **kwargs)
data = fig4vis(fig)
return data
|
[
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.roll",
"matplotlib.pyplot.Rectangle"
] |
[((3262, 3285), 'numpy.roll', 'np.roll', (['buf', '(3)'], {'axis': '(2)'}), '(buf, 3, axis=2)\n', (3269, 3285), True, 'import numpy as np\n'), ((3462, 3473), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3471, 3473), True, 'import matplotlib.pyplot as plt\n'), ((915, 927), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (925, 927), True, 'import matplotlib.pyplot as plt\n'), ((1977, 2051), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['xy', 'width', 'height'], {'fill': '(False)', 'edgecolor': '"""red"""', 'linewidth': '(2)'}), "(xy, width, height, fill=False, edgecolor='red', linewidth=2)\n", (1990, 2051), True, 'import matplotlib.pyplot as plt\n')]
|
import julia
import numpy as np
import os.path as osp
import gym
from brl_gym.envs.mujoco import box_pusher
env = box_pusher.BoxPusher()
rlopt = "/home/gilwoo/School_Workspace/rlopt"
j = julia.Julia()
j.include(osp.join(rlopt, "_init.jl"))
j.include(osp.join(rlopt, "src/pg/Baseline.jl"))
j.include(osp.join(rlopt, "src/ExpSim.jl"))
polo = "/tmp/pusher_polo_opt_1"
baseline = j.Baseline.loadbaseline(osp.join(polo, "baseline.jld2"))
datafile = j.ExpSim.load(osp.join(polo, "data.jld2"))
# Replay the datafile
state = np.squeeze(datafile["state"]).transpose()
ctrl = np.squeeze(datafile["ctrl"]).transpose()
obs = np.squeeze(datafile["obs"]).transpose()
# a = [x for x in a.split(";")]
# data = []
# for x in a:
# data += [[float(y) for y in x.split(" ") if y != " " and y != ""]]
# data = np.array(data)
# value = j.Baseline.predict(baseline, data.tolist())
# print("Value", value)
o = env.reset()
# env.set_state_ctrl(state[1,:35], state[1,35:], ctrl[1])
#o, r, d, _ = env.step(ctrl[0])
# new_state = env.sim.get_state()
# import IPython; IPython.embed(); import sys; sys.exit(0)
#copy_env = humanoid_pushing.HumanoidPushingEnv()
#copy_env.reset()
print(state.shape)
states = []
observations = []
rewards = []
values = []
for i in range(state.shape[0]):
env.set_state(state[i,:5], state[i,5:])
# states += [(env.sim.get_state().qpos, env.sim.get_state().qvel)]
o, r, d, _ = env.step(ctrl[i])
# observations += [o]
# rewards += [r]
values += [j.Baseline.predict(baseline, o.reshape(-1,1).tolist())]
env.render()
import IPython; IPython.embed()
|
[
"brl_gym.envs.mujoco.box_pusher.BoxPusher",
"os.path.join",
"julia.Julia",
"IPython.embed",
"numpy.squeeze"
] |
[((114, 136), 'brl_gym.envs.mujoco.box_pusher.BoxPusher', 'box_pusher.BoxPusher', ([], {}), '()\n', (134, 136), False, 'from brl_gym.envs.mujoco import box_pusher\n'), ((188, 201), 'julia.Julia', 'julia.Julia', ([], {}), '()\n', (199, 201), False, 'import julia\n'), ((1570, 1585), 'IPython.embed', 'IPython.embed', ([], {}), '()\n', (1583, 1585), False, 'import IPython\n'), ((213, 240), 'os.path.join', 'osp.join', (['rlopt', '"""_init.jl"""'], {}), "(rlopt, '_init.jl')\n", (221, 240), True, 'import os.path as osp\n'), ((252, 289), 'os.path.join', 'osp.join', (['rlopt', '"""src/pg/Baseline.jl"""'], {}), "(rlopt, 'src/pg/Baseline.jl')\n", (260, 289), True, 'import os.path as osp\n'), ((301, 333), 'os.path.join', 'osp.join', (['rlopt', '"""src/ExpSim.jl"""'], {}), "(rlopt, 'src/ExpSim.jl')\n", (309, 333), True, 'import os.path as osp\n'), ((402, 433), 'os.path.join', 'osp.join', (['polo', '"""baseline.jld2"""'], {}), "(polo, 'baseline.jld2')\n", (410, 433), True, 'import os.path as osp\n'), ((460, 487), 'os.path.join', 'osp.join', (['polo', '"""data.jld2"""'], {}), "(polo, 'data.jld2')\n", (468, 487), True, 'import os.path as osp\n'), ((520, 549), 'numpy.squeeze', 'np.squeeze', (["datafile['state']"], {}), "(datafile['state'])\n", (530, 549), True, 'import numpy as np\n'), ((569, 597), 'numpy.squeeze', 'np.squeeze', (["datafile['ctrl']"], {}), "(datafile['ctrl'])\n", (579, 597), True, 'import numpy as np\n'), ((616, 643), 'numpy.squeeze', 'np.squeeze', (["datafile['obs']"], {}), "(datafile['obs'])\n", (626, 643), True, 'import numpy as np\n')]
|
import numpy as np
from scipy.optimize import fmin
from scipy.stats import kurtosis
from scipy.special import lambertw
"""
The algorithm is based on [1]. The implementation is based on [2].
[1]: <NAME>, 2013 (https://arxiv.org/pdf/1010.2265.pdf)
[2]: <NAME>, 2015 (https://github.com/gregversteeg/gaussianize)
"""
def estimate_parameters(x):
return np.array([igmm(x_i) for x_i in x.T])
def transform(x, parameters):
return np.array([
lambertw_tau(x_i, tau_i) for x_i, tau_i in zip(x.T, parameters)
]).T
def inverse_transform(y, parameters):
return np.array([
inverse(y_i, tau_i) for y_i, tau_i in zip(y.T, parameters)
]).T
def lambertw_delta(z, delta):
"""Lambertw delta function as defined in (9)."""
if delta < 1e-6:
return z
return np.sign(z) * np.sqrt(np.real(lambertw(delta * z ** 2)) / delta)
def lambertw_tau(y, tau):
"""Lambertw tau function as defined in (8)."""
return tau[0] + tau[1] * lambertw_delta((y - tau[0]) / tau[1], tau[2])
def inverse(x, tau):
"""Inverse distribution transform as defined in (6)."""
u = (x - tau[0]) / tau[1]
return tau[0] + tau[1] * (u * np.exp(u * u * (tau[2] * 0.5)))
def igmm(y, tol=1.22e-4, max_iter=100):
if np.std(y) < 1e-4:
return np.mean(y), np.std(y).clip(1e-4), 0
delta0 = delta_init(y)
tau1 = (np.median(y), np.std(y) * (1. - 2. * delta0) ** 0.75, delta0)
for k in range(max_iter):
tau0 = tau1
z = (y - tau1[0]) / tau1[1]
delta1 = delta_gmm(z)
x = tau0[0] + tau1[1] * lambertw_delta(z, delta1)
mu1, sigma1 = np.mean(x), np.std(x)
tau1 = (mu1, sigma1, delta1)
if np.linalg.norm(np.array(tau1) - np.array(tau0)) < tol:
break
else:
if k == max_iter - 1:
print(f'Warning: No convergence after {max_iter} iterations.')
return tau1
def delta_gmm(z):
delta0 = delta_init(z)
def func(q):
u = lambertw_delta(z, np.exp(q))
if not np.all(np.isfinite(u)):
return 0.
else:
k = kurtosis(u, fisher=True, bias=False)**2
if not np.isfinite(k) or k > 1e10:
return 1e10
else:
return k
res = fmin(func, np.log(delta0), disp=0)
return np.around(np.exp(res[-1]), 6)
def delta_init(z):
gamma = kurtosis(z, fisher=False, bias=False)
with np.errstate(all='ignore'):
delta0 = np.clip(1. / 66 * (np.sqrt(66 * gamma - 162.) - 6.), 0.01, 0.48)
if not np.isfinite(delta0):
delta0 = 0.01
return delta0
|
[
"numpy.mean",
"numpy.median",
"numpy.sqrt",
"scipy.special.lambertw",
"scipy.stats.kurtosis",
"numpy.log",
"numpy.exp",
"numpy.errstate",
"numpy.array",
"numpy.isfinite",
"numpy.sign",
"numpy.std"
] |
[((2216, 2253), 'scipy.stats.kurtosis', 'kurtosis', (['z'], {'fisher': '(False)', 'bias': '(False)'}), '(z, fisher=False, bias=False)\n', (2224, 2253), False, 'from scipy.stats import kurtosis\n'), ((779, 789), 'numpy.sign', 'np.sign', (['z'], {}), '(z)\n', (786, 789), True, 'import numpy as np\n'), ((1214, 1223), 'numpy.std', 'np.std', (['y'], {}), '(y)\n', (1220, 1223), True, 'import numpy as np\n'), ((1314, 1326), 'numpy.median', 'np.median', (['y'], {}), '(y)\n', (1323, 1326), True, 'import numpy as np\n'), ((2122, 2136), 'numpy.log', 'np.log', (['delta0'], {}), '(delta0)\n', (2128, 2136), True, 'import numpy as np\n'), ((2165, 2180), 'numpy.exp', 'np.exp', (['res[-1]'], {}), '(res[-1])\n', (2171, 2180), True, 'import numpy as np\n'), ((2261, 2286), 'numpy.errstate', 'np.errstate', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (2272, 2286), True, 'import numpy as np\n'), ((2375, 2394), 'numpy.isfinite', 'np.isfinite', (['delta0'], {}), '(delta0)\n', (2386, 2394), True, 'import numpy as np\n'), ((1243, 1253), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (1250, 1253), True, 'import numpy as np\n'), ((1328, 1337), 'numpy.std', 'np.std', (['y'], {}), '(y)\n', (1334, 1337), True, 'import numpy as np\n'), ((1550, 1560), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (1557, 1560), True, 'import numpy as np\n'), ((1562, 1571), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (1568, 1571), True, 'import numpy as np\n'), ((1890, 1899), 'numpy.exp', 'np.exp', (['q'], {}), '(q)\n', (1896, 1899), True, 'import numpy as np\n'), ((1135, 1165), 'numpy.exp', 'np.exp', (['(u * u * (tau[2] * 0.5))'], {}), '(u * u * (tau[2] * 0.5))\n', (1141, 1165), True, 'import numpy as np\n'), ((1919, 1933), 'numpy.isfinite', 'np.isfinite', (['u'], {}), '(u)\n', (1930, 1933), True, 'import numpy as np\n'), ((1972, 2008), 'scipy.stats.kurtosis', 'kurtosis', (['u'], {'fisher': '(True)', 'bias': '(False)'}), '(u, fisher=True, bias=False)\n', (1980, 2008), False, 'from scipy.stats import kurtosis\n'), ((808, 832), 'scipy.special.lambertw', 'lambertw', (['(delta * z ** 2)'], {}), '(delta * z ** 2)\n', (816, 832), False, 'from scipy.special import lambertw\n'), ((1255, 1264), 'numpy.std', 'np.std', (['y'], {}), '(y)\n', (1261, 1264), True, 'import numpy as np\n'), ((1628, 1642), 'numpy.array', 'np.array', (['tau1'], {}), '(tau1)\n', (1636, 1642), True, 'import numpy as np\n'), ((1645, 1659), 'numpy.array', 'np.array', (['tau0'], {}), '(tau0)\n', (1653, 1659), True, 'import numpy as np\n'), ((2025, 2039), 'numpy.isfinite', 'np.isfinite', (['k'], {}), '(k)\n', (2036, 2039), True, 'import numpy as np\n'), ((2320, 2347), 'numpy.sqrt', 'np.sqrt', (['(66 * gamma - 162.0)'], {}), '(66 * gamma - 162.0)\n', (2327, 2347), True, 'import numpy as np\n')]
|
import unittest
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from punk.feature_selection import PCAFeatures
from punk.feature_selection import RFFeatures
class TestPCA(unittest.TestCase):
def setUp(self):
iris = datasets.load_iris()
sc = StandardScaler()
self.X = sc.fit_transform(iris.data)
def test_pca(self):
rankings = PCAFeatures()
importances = rankings.produce(self.X)
self.assertTrue(
np.array_equal(
importances, np.array([2, 3, 0, 1])) )
class TestRFC(unittest.TestCase):
def setUp(self):
df_wine = pd.read_csv('https://raw.githubusercontent.com/rasbt/'
'python-machine-learning-book/master/code/datasets/wine/wine.data',
header=None)
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
self.X, _, self.y, _ = train_test_split(X, y, test_size=0.3, random_state=0)
def test_rfc(self):
rf = RFFeatures(problem_type="classification", cv=3,
scoring="accuracy", verbose=0, n_jobs=1)
indices = rf.produce((self.X, self.y))
self.assertTrue( np.all(np.isfinite( rf.feature_importances )) )
importances = np.array([9, 12, 6, 11, 0, 10, 5, 3, 1, 8, 4, 7, 2])
self.assertTrue( np.array_equal(indices, importances) )
class TestRFR(unittest.TestCase):
def setUp(self):
boston = datasets.load_boston()
self.X, self.y = boston.data, boston.target
def test_rfr(self):
rf = RFFeatures(problem_type="regression", cv=3,
scoring="r2", verbose=0, n_jobs=1)
indices = rf.produce((self.X, self.y))
self.assertTrue( np.all(np.isfinite( rf.feature_importances )) )
importances = np.array([5, 12, 7, 0, 4, 10, 9, 6, 11, 2, 8, 1, 3])
self.assertTrue( np.array_equal(indices, importances) )
if __name__ == '__main__':
unittest.main()
|
[
"sklearn.datasets.load_iris",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_boston",
"punk.feature_selection.PCAFeatures",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"numpy.array_equal",
"numpy.isfinite",
"unittest.main",
"punk.feature_selection.RFFeatures"
] |
[((2232, 2247), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2245, 2247), False, 'import unittest\n'), ((409, 429), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (427, 429), False, 'from sklearn import datasets\n'), ((444, 460), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (458, 460), False, 'from sklearn.preprocessing import StandardScaler\n'), ((630, 643), 'punk.feature_selection.PCAFeatures', 'PCAFeatures', ([], {}), '()\n', (641, 643), False, 'from punk.feature_selection import PCAFeatures\n'), ((875, 1017), 'pandas.read_csv', 'pd.read_csv', (['"""https://raw.githubusercontent.com/rasbt/python-machine-learning-book/master/code/datasets/wine/wine.data"""'], {'header': 'None'}), "(\n 'https://raw.githubusercontent.com/rasbt/python-machine-learning-book/master/code/datasets/wine/wine.data'\n , header=None)\n", (886, 1017), True, 'import pandas as pd\n'), ((1176, 1229), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(0)'}), '(X, y, test_size=0.3, random_state=0)\n', (1192, 1229), False, 'from sklearn.model_selection import train_test_split\n'), ((1269, 1362), 'punk.feature_selection.RFFeatures', 'RFFeatures', ([], {'problem_type': '"""classification"""', 'cv': '(3)', 'scoring': '"""accuracy"""', 'verbose': '(0)', 'n_jobs': '(1)'}), "(problem_type='classification', cv=3, scoring='accuracy', verbose\n =0, n_jobs=1)\n", (1279, 1362), False, 'from punk.feature_selection import RFFeatures\n'), ((1528, 1580), 'numpy.array', 'np.array', (['[9, 12, 6, 11, 0, 10, 5, 3, 1, 8, 4, 7, 2]'], {}), '([9, 12, 6, 11, 0, 10, 5, 3, 1, 8, 4, 7, 2])\n', (1536, 1580), True, 'import numpy as np\n'), ((1719, 1741), 'sklearn.datasets.load_boston', 'datasets.load_boston', ([], {}), '()\n', (1739, 1741), False, 'from sklearn import datasets\n'), ((1832, 1910), 'punk.feature_selection.RFFeatures', 'RFFeatures', ([], {'problem_type': '"""regression"""', 'cv': '(3)', 'scoring': '"""r2"""', 'verbose': '(0)', 'n_jobs': '(1)'}), "(problem_type='regression', cv=3, scoring='r2', verbose=0, n_jobs=1)\n", (1842, 1910), False, 'from punk.feature_selection import RFFeatures\n'), ((2083, 2135), 'numpy.array', 'np.array', (['[5, 12, 7, 0, 4, 10, 9, 6, 11, 2, 8, 1, 3]'], {}), '([5, 12, 7, 0, 4, 10, 9, 6, 11, 2, 8, 1, 3])\n', (2091, 2135), True, 'import numpy as np\n'), ((1606, 1642), 'numpy.array_equal', 'np.array_equal', (['indices', 'importances'], {}), '(indices, importances)\n', (1620, 1642), True, 'import numpy as np\n'), ((2161, 2197), 'numpy.array_equal', 'np.array_equal', (['indices', 'importances'], {}), '(indices, importances)\n', (2175, 2197), True, 'import numpy as np\n'), ((775, 797), 'numpy.array', 'np.array', (['[2, 3, 0, 1]'], {}), '([2, 3, 0, 1])\n', (783, 797), True, 'import numpy as np\n'), ((1465, 1500), 'numpy.isfinite', 'np.isfinite', (['rf.feature_importances'], {}), '(rf.feature_importances)\n', (1476, 1500), True, 'import numpy as np\n'), ((2020, 2055), 'numpy.isfinite', 'np.isfinite', (['rf.feature_importances'], {}), '(rf.feature_importances)\n', (2031, 2055), True, 'import numpy as np\n')]
|
from unittest import TestCase
from tests.assertions import CustomAssertions
import scipy.sparse
import numpy as np
import tests.rabi as rabi
import floq
class TestSetBlock(TestCase):
def setUp(self):
self.dim_block = 5
self.n_block = 3
self.a, self.b, self.c, self.d, self.e, self.f, self.g, self.h, self.i \
= [j*np.ones([self.dim_block, self.dim_block]) for j in range(9)]
matrix = np.bmat([[self.a, self.b, self.c],
[self.d, self.e, self.f],
[self.g, self.h, self.i]])
self.original = np.array(matrix)
total_size = self.dim_block*self.n_block
self.copy = np.zeros([total_size,total_size])
def test_set(self):
# Try to recreate self.original with the new function
floq.evolution._add_block(self.a, self.copy, self.dim_block, self.n_block, 0, 0)
floq.evolution._add_block(self.b, self.copy, self.dim_block, self.n_block, 0, 1)
floq.evolution._add_block(self.c, self.copy, self.dim_block, self.n_block, 0, 2)
floq.evolution._add_block(self.d, self.copy, self.dim_block, self.n_block, 1, 0)
floq.evolution._add_block(self.e, self.copy, self.dim_block, self.n_block, 1, 1)
floq.evolution._add_block(self.f, self.copy, self.dim_block, self.n_block, 1, 2)
floq.evolution._add_block(self.g, self.copy, self.dim_block, self.n_block, 2, 0)
floq.evolution._add_block(self.h, self.copy, self.dim_block, self.n_block, 2, 1)
floq.evolution._add_block(self.i, self.copy, self.dim_block, self.n_block, 2, 2)
self.assertTrue(np.array_equal(self.copy,self.original))
class TestAssembleK(CustomAssertions):
def setUp(self):
self.n_zones = 5
self.frequency = 1
dim=2
a = -1.*np.ones([dim, dim])
b = np.zeros([dim, dim])
c = np.ones([dim, dim])
z = np.zeros([dim, dim])
i = np.identity(dim)
self.goalk = np.array(
np.bmat(
[[b-2*i, a, z, z, z],
[c, b-i, a, z, z],
[z, c, b, a, z],
[z, z, c, b+i, a],
[z, z, z, c, b+2*i]]))
self.hf = floq.system._canonicalise_operator(np.array([a, b, c]))
def test_dense(self):
builtk = floq.evolution.assemble_k(self.hf, self.n_zones, self.frequency)
self.assertArrayEqual(builtk, self.goalk)
def test_sparse(self):
builtk = floq.evolution.assemble_k_sparse(self.hf, self.n_zones,
self.frequency)
self.assertTrue(scipy.sparse.issparse(builtk))
self.assertArrayEqual(builtk.toarray(), self.goalk)
class TestDenseToSparse(CustomAssertions):
def test_conversion(self):
goal = floq.types.ColumnSparseMatrix(np.array([1, 2]),
np.array([1, 0, 1]),
np.array([2, 1, 3]))
built = floq.evolution._dense_to_sparse(np.arange(4).reshape(2, 2))
self.assertColumnSparseMatrixEqual(built, goal)
class TestAssembledK(CustomAssertions):
def setUp(self):
self.n_zones = 5
dim=2
a = -1.*np.ones([dim, dim])
b = np.zeros([dim, dim])
c = np.ones([dim, dim])
z = np.zeros([dim, dim])
i = np.identity(dim)
dk1 = np.array(
np.bmat(
[[b, a, z, z, z],
[c, b, a, z, z],
[z, c, b, a, z],
[z, z, c, b, a],
[z, z, z, c, b]]))
dk2 = np.array(
np.bmat(
[[b, b, z, z, z],
[a, b, b, z, z],
[z, a, b, b, z],
[z, z, a, b, b],
[z, z, z, a, b]]))
self.goaldk = [floq.evolution._dense_to_sparse(x) for x in [dk1, dk2]]
self.dhf = [floq.system._canonicalise_operator(np.array([a, b, c])),
floq.system._canonicalise_operator(np.array([b, b, a]))]
def test_build(self):
builtdk = floq.evolution.assemble_dk(self.dhf, self.n_zones)
for i, bdk in enumerate(builtdk):
self.assertColumnSparseMatrixEqual(bdk, self.goaldk[i])
class TestFindEigensystem(CustomAssertions):
def setUp(self):
self.target_vals = np.array([-0.235, 0.753])
# random matrix with known eigenvalues:
# {-1.735, -0.747, -0.235, 0.753, 1.265, 2.253}
k = np.array([[-0.0846814, -0.0015136 - 0.33735j, -0.210771 + 0.372223j,
0.488512 - 0.769537j, -0.406266 + 0.315634j, -0.334452 +
0.251584j], [-0.0015136 + 0.33735j,
0.809781, -0.416533 - 0.432041j, -0.571074 -
0.669052j, -0.665971 + 0.387569j, -0.297409 -
0.0028969j], [-0.210771 - 0.372223j, -0.416533 +
0.432041j, -0.0085791, 0.110085 + 0.255156j,
0.958938 - 0.17233j, -0.91924 + 0.126004j], [0.488512 +
0.769537j, -0.571074 + 0.669052j,
0.110085 - 0.255156j, -0.371663,
0.279778 + 0.477653j, -0.496302 + 1.04898j], [-0.406266 -
0.315634j, -0.665971 - 0.387569j, 0.958938 + 0.17233j,
0.279778 - 0.477653j, -0.731623,
0.525248 + 0.0443422j], [-0.334452 - 0.251584j, -0.297409 +
0.0028969j, -0.91924 - 0.126004j, -0.496302 - 1.04898j,
0.525248 - 0.0443422j, 1.94077]], dtype='complex128')
e1 = np.array([[0.0321771 - 0.52299j, 0.336377 + 0.258732j],
[0.371002 + 0.0071587j, 0.237385 + 0.205185j],
[0.525321 + 0.j, 0.0964822 + 0.154715j]])
e2 = np.array([[0.593829 + 0.j, -0.105998 - 0.394563j],
[-0.0737891 - 0.419478j, 0.323414 + 0.350387j],
[-0.05506 - 0.169033j, -0.0165495 + 0.199498j]])
self.target_vecs = np.array([e1, e2])
omega = 2.1
dim = 2
self.vals, self.vecs = floq.evolution.diagonalise(k, dim, omega, 3)
def test_finds_vals(self):
self.assertArrayEqual(self.vals, self.target_vals)
def test_finds_vecs(self):
self.assertArrayEqual(self.vecs, self.target_vecs, decimals=3)
def test_casts_as_complex128(self):
self.assertEqual(self.vecs.dtype, 'complex128')
class TestFindDuplicates(CustomAssertions):
def test_duplicates(self):
a = np.round(np.array([1, 2.001, 2.003, 1.999, 3]), decimals=2)
res = tuple(floq.evolution._find_duplicates(a))
self.assertEqual(len(res), 1)
self.assertArrayEqual([1, 2, 3], res[0])
def test_empty_if_no_dup(self):
a = np.round(np.array([1, 2.001, 4.003, 8.999, 10]), decimals=2)
res = tuple(floq.evolution._find_duplicates(a))
self.assertEqual(res, ())
def test_multiple_duplicates(self):
a = np.array([1., 1., 2., 2., 3., 4., 4.])
res = tuple(floq.evolution._find_duplicates(a))
self.assertEqual(len(res), 3)
self.assertArrayEqual([[0, 1], [2, 3], [5, 6]], res)
|
[
"numpy.identity",
"numpy.ones",
"numpy.arange",
"floq.evolution._dense_to_sparse",
"floq.evolution._add_block",
"floq.evolution.assemble_k",
"floq.evolution.assemble_dk",
"numpy.array",
"numpy.zeros",
"floq.evolution._find_duplicates",
"numpy.array_equal",
"floq.evolution.assemble_k_sparse",
"numpy.bmat",
"floq.evolution.diagonalise"
] |
[((435, 527), 'numpy.bmat', 'np.bmat', (['[[self.a, self.b, self.c], [self.d, self.e, self.f], [self.g, self.h, self.i]]'], {}), '([[self.a, self.b, self.c], [self.d, self.e, self.f], [self.g, self.\n h, self.i]])\n', (442, 527), True, 'import numpy as np\n'), ((597, 613), 'numpy.array', 'np.array', (['matrix'], {}), '(matrix)\n', (605, 613), True, 'import numpy as np\n'), ((684, 718), 'numpy.zeros', 'np.zeros', (['[total_size, total_size]'], {}), '([total_size, total_size])\n', (692, 718), True, 'import numpy as np\n'), ((813, 898), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.a', 'self.copy', 'self.dim_block', 'self.n_block', '(0)', '(0)'], {}), '(self.a, self.copy, self.dim_block, self.n_block, 0, 0\n )\n', (838, 898), False, 'import floq\n'), ((902, 987), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.b', 'self.copy', 'self.dim_block', 'self.n_block', '(0)', '(1)'], {}), '(self.b, self.copy, self.dim_block, self.n_block, 0, 1\n )\n', (927, 987), False, 'import floq\n'), ((991, 1076), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.c', 'self.copy', 'self.dim_block', 'self.n_block', '(0)', '(2)'], {}), '(self.c, self.copy, self.dim_block, self.n_block, 0, 2\n )\n', (1016, 1076), False, 'import floq\n'), ((1080, 1165), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.d', 'self.copy', 'self.dim_block', 'self.n_block', '(1)', '(0)'], {}), '(self.d, self.copy, self.dim_block, self.n_block, 1, 0\n )\n', (1105, 1165), False, 'import floq\n'), ((1169, 1254), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.e', 'self.copy', 'self.dim_block', 'self.n_block', '(1)', '(1)'], {}), '(self.e, self.copy, self.dim_block, self.n_block, 1, 1\n )\n', (1194, 1254), False, 'import floq\n'), ((1258, 1343), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.f', 'self.copy', 'self.dim_block', 'self.n_block', '(1)', '(2)'], {}), '(self.f, self.copy, self.dim_block, self.n_block, 1, 2\n )\n', (1283, 1343), False, 'import floq\n'), ((1347, 1432), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.g', 'self.copy', 'self.dim_block', 'self.n_block', '(2)', '(0)'], {}), '(self.g, self.copy, self.dim_block, self.n_block, 2, 0\n )\n', (1372, 1432), False, 'import floq\n'), ((1436, 1521), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.h', 'self.copy', 'self.dim_block', 'self.n_block', '(2)', '(1)'], {}), '(self.h, self.copy, self.dim_block, self.n_block, 2, 1\n )\n', (1461, 1521), False, 'import floq\n'), ((1525, 1610), 'floq.evolution._add_block', 'floq.evolution._add_block', (['self.i', 'self.copy', 'self.dim_block', 'self.n_block', '(2)', '(2)'], {}), '(self.i, self.copy, self.dim_block, self.n_block, 2, 2\n )\n', (1550, 1610), False, 'import floq\n'), ((1847, 1867), 'numpy.zeros', 'np.zeros', (['[dim, dim]'], {}), '([dim, dim])\n', (1855, 1867), True, 'import numpy as np\n'), ((1880, 1899), 'numpy.ones', 'np.ones', (['[dim, dim]'], {}), '([dim, dim])\n', (1887, 1899), True, 'import numpy as np\n'), ((1912, 1932), 'numpy.zeros', 'np.zeros', (['[dim, dim]'], {}), '([dim, dim])\n', (1920, 1932), True, 'import numpy as np\n'), ((1945, 1961), 'numpy.identity', 'np.identity', (['dim'], {}), '(dim)\n', (1956, 1961), True, 'import numpy as np\n'), ((2317, 2381), 'floq.evolution.assemble_k', 'floq.evolution.assemble_k', (['self.hf', 'self.n_zones', 'self.frequency'], {}), '(self.hf, self.n_zones, self.frequency)\n', (2342, 2381), False, 'import floq\n'), ((2477, 2548), 'floq.evolution.assemble_k_sparse', 'floq.evolution.assemble_k_sparse', (['self.hf', 'self.n_zones', 'self.frequency'], {}), '(self.hf, self.n_zones, self.frequency)\n', (2509, 2548), False, 'import floq\n'), ((3266, 3286), 'numpy.zeros', 'np.zeros', (['[dim, dim]'], {}), '([dim, dim])\n', (3274, 3286), True, 'import numpy as np\n'), ((3299, 3318), 'numpy.ones', 'np.ones', (['[dim, dim]'], {}), '([dim, dim])\n', (3306, 3318), True, 'import numpy as np\n'), ((3331, 3351), 'numpy.zeros', 'np.zeros', (['[dim, dim]'], {}), '([dim, dim])\n', (3339, 3351), True, 'import numpy as np\n'), ((3364, 3380), 'numpy.identity', 'np.identity', (['dim'], {}), '(dim)\n', (3375, 3380), True, 'import numpy as np\n'), ((4095, 4145), 'floq.evolution.assemble_dk', 'floq.evolution.assemble_dk', (['self.dhf', 'self.n_zones'], {}), '(self.dhf, self.n_zones)\n', (4121, 4145), False, 'import floq\n'), ((4350, 4375), 'numpy.array', 'np.array', (['[-0.235, 0.753]'], {}), '([-0.235, 0.753])\n', (4358, 4375), True, 'import numpy as np\n'), ((4492, 5330), 'numpy.array', 'np.array', (['[[-0.0846814, -0.0015136 - 0.33735j, -0.210771 + 0.372223j, 0.488512 - \n 0.769537j, -0.406266 + 0.315634j, -0.334452 + 0.251584j], [-0.0015136 +\n 0.33735j, 0.809781, -0.416533 - 0.432041j, -0.571074 - 0.669052j, -\n 0.665971 + 0.387569j, -0.297409 - 0.0028969j], [-0.210771 - 0.372223j, \n -0.416533 + 0.432041j, -0.0085791, 0.110085 + 0.255156j, 0.958938 - \n 0.17233j, -0.91924 + 0.126004j], [0.488512 + 0.769537j, -0.571074 + \n 0.669052j, 0.110085 - 0.255156j, -0.371663, 0.279778 + 0.477653j, -\n 0.496302 + 1.04898j], [-0.406266 - 0.315634j, -0.665971 - 0.387569j, \n 0.958938 + 0.17233j, 0.279778 - 0.477653j, -0.731623, 0.525248 + \n 0.0443422j], [-0.334452 - 0.251584j, -0.297409 + 0.0028969j, -0.91924 -\n 0.126004j, -0.496302 - 1.04898j, 0.525248 - 0.0443422j, 1.94077]]'], {'dtype': '"""complex128"""'}), "([[-0.0846814, -0.0015136 - 0.33735j, -0.210771 + 0.372223j, \n 0.488512 - 0.769537j, -0.406266 + 0.315634j, -0.334452 + 0.251584j], [-\n 0.0015136 + 0.33735j, 0.809781, -0.416533 - 0.432041j, -0.571074 - \n 0.669052j, -0.665971 + 0.387569j, -0.297409 - 0.0028969j], [-0.210771 -\n 0.372223j, -0.416533 + 0.432041j, -0.0085791, 0.110085 + 0.255156j, \n 0.958938 - 0.17233j, -0.91924 + 0.126004j], [0.488512 + 0.769537j, -\n 0.571074 + 0.669052j, 0.110085 - 0.255156j, -0.371663, 0.279778 + \n 0.477653j, -0.496302 + 1.04898j], [-0.406266 - 0.315634j, -0.665971 - \n 0.387569j, 0.958938 + 0.17233j, 0.279778 - 0.477653j, -0.731623, \n 0.525248 + 0.0443422j], [-0.334452 - 0.251584j, -0.297409 + 0.0028969j,\n -0.91924 - 0.126004j, -0.496302 - 1.04898j, 0.525248 - 0.0443422j, \n 1.94077]], dtype='complex128')\n", (4500, 5330), True, 'import numpy as np\n'), ((5644, 5799), 'numpy.array', 'np.array', (['[[0.0321771 - 0.52299j, 0.336377 + 0.258732j], [0.371002 + 0.0071587j, \n 0.237385 + 0.205185j], [0.525321 + 0.0j, 0.0964822 + 0.154715j]]'], {}), '([[0.0321771 - 0.52299j, 0.336377 + 0.258732j], [0.371002 + \n 0.0071587j, 0.237385 + 0.205185j], [0.525321 + 0.0j, 0.0964822 + \n 0.154715j]])\n', (5652, 5799), True, 'import numpy as np\n'), ((5848, 6000), 'numpy.array', 'np.array', (['[[0.593829 + 0.0j, -0.105998 - 0.394563j], [-0.0737891 - 0.419478j, \n 0.323414 + 0.350387j], [-0.05506 - 0.169033j, -0.0165495 + 0.199498j]]'], {}), '([[0.593829 + 0.0j, -0.105998 - 0.394563j], [-0.0737891 - 0.419478j,\n 0.323414 + 0.350387j], [-0.05506 - 0.169033j, -0.0165495 + 0.199498j]])\n', (5856, 6000), True, 'import numpy as np\n'), ((6069, 6087), 'numpy.array', 'np.array', (['[e1, e2]'], {}), '([e1, e2])\n', (6077, 6087), True, 'import numpy as np\n'), ((6156, 6200), 'floq.evolution.diagonalise', 'floq.evolution.diagonalise', (['k', 'dim', 'omega', '(3)'], {}), '(k, dim, omega, 3)\n', (6182, 6200), False, 'import floq\n'), ((7036, 7081), 'numpy.array', 'np.array', (['[1.0, 1.0, 2.0, 2.0, 3.0, 4.0, 4.0]'], {}), '([1.0, 1.0, 2.0, 2.0, 3.0, 4.0, 4.0])\n', (7044, 7081), True, 'import numpy as np\n'), ((1630, 1670), 'numpy.array_equal', 'np.array_equal', (['self.copy', 'self.original'], {}), '(self.copy, self.original)\n', (1644, 1670), True, 'import numpy as np\n'), ((1815, 1834), 'numpy.ones', 'np.ones', (['[dim, dim]'], {}), '([dim, dim])\n', (1822, 1834), True, 'import numpy as np\n'), ((2006, 2128), 'numpy.bmat', 'np.bmat', (['[[b - 2 * i, a, z, z, z], [c, b - i, a, z, z], [z, c, b, a, z], [z, z, c, b +\n i, a], [z, z, z, c, b + 2 * i]]'], {}), '([[b - 2 * i, a, z, z, z], [c, b - i, a, z, z], [z, c, b, a, z], [z,\n z, c, b + i, a], [z, z, z, c, b + 2 * i]])\n', (2013, 2128), True, 'import numpy as np\n'), ((2252, 2271), 'numpy.array', 'np.array', (['[a, b, c]'], {}), '([a, b, c])\n', (2260, 2271), True, 'import numpy as np\n'), ((2834, 2850), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (2842, 2850), True, 'import numpy as np\n'), ((2897, 2916), 'numpy.array', 'np.array', (['[1, 0, 1]'], {}), '([1, 0, 1])\n', (2905, 2916), True, 'import numpy as np\n'), ((2963, 2982), 'numpy.array', 'np.array', (['[2, 1, 3]'], {}), '([2, 1, 3])\n', (2971, 2982), True, 'import numpy as np\n'), ((3234, 3253), 'numpy.ones', 'np.ones', (['[dim, dim]'], {}), '([dim, dim])\n', (3241, 3253), True, 'import numpy as np\n'), ((3418, 3516), 'numpy.bmat', 'np.bmat', (['[[b, a, z, z, z], [c, b, a, z, z], [z, c, b, a, z], [z, z, c, b, a], [z, z,\n z, c, b]]'], {}), '([[b, a, z, z, z], [c, b, a, z, z], [z, c, b, a, z], [z, z, c, b, a],\n [z, z, z, c, b]])\n', (3425, 3516), True, 'import numpy as np\n'), ((3635, 3733), 'numpy.bmat', 'np.bmat', (['[[b, b, z, z, z], [a, b, b, z, z], [z, a, b, b, z], [z, z, a, b, b], [z, z,\n z, a, b]]'], {}), '([[b, b, z, z, z], [a, b, b, z, z], [z, a, b, b, z], [z, z, a, b, b],\n [z, z, z, a, b]])\n', (3642, 3733), True, 'import numpy as np\n'), ((3840, 3874), 'floq.evolution._dense_to_sparse', 'floq.evolution._dense_to_sparse', (['x'], {}), '(x)\n', (3871, 3874), False, 'import floq\n'), ((6589, 6626), 'numpy.array', 'np.array', (['[1, 2.001, 2.003, 1.999, 3]'], {}), '([1, 2.001, 2.003, 1.999, 3])\n', (6597, 6626), True, 'import numpy as np\n'), ((6660, 6694), 'floq.evolution._find_duplicates', 'floq.evolution._find_duplicates', (['a'], {}), '(a)\n', (6691, 6694), False, 'import floq\n'), ((6841, 6879), 'numpy.array', 'np.array', (['[1, 2.001, 4.003, 8.999, 10]'], {}), '([1, 2.001, 4.003, 8.999, 10])\n', (6849, 6879), True, 'import numpy as np\n'), ((6913, 6947), 'floq.evolution._find_duplicates', 'floq.evolution._find_duplicates', (['a'], {}), '(a)\n', (6944, 6947), False, 'import floq\n'), ((7095, 7129), 'floq.evolution._find_duplicates', 'floq.evolution._find_duplicates', (['a'], {}), '(a)\n', (7126, 7129), False, 'import floq\n'), ((356, 397), 'numpy.ones', 'np.ones', (['[self.dim_block, self.dim_block]'], {}), '([self.dim_block, self.dim_block])\n', (363, 397), True, 'import numpy as np\n'), ((3951, 3970), 'numpy.array', 'np.array', (['[a, b, c]'], {}), '([a, b, c])\n', (3959, 3970), True, 'import numpy as np\n'), ((4028, 4047), 'numpy.array', 'np.array', (['[b, b, a]'], {}), '([b, b, a])\n', (4036, 4047), True, 'import numpy as np\n'), ((3032, 3044), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (3041, 3044), True, 'import numpy as np\n')]
|
text = """
ala ma kota
a kot ma ale
"""
# ------------------------------------------------------------------------------
# TODO as class
chars = list(sorted(set(text))) # stabilne indeksy
len_chars = len(chars)+1
c_to_i = {c:i+1 for i,c in enumerate(chars)}
i_to_c = {i+1:c for i,c in enumerate(chars)}
def text_to_i(text):
return [c_to_i.get(c,0) for c in text]
def text_to_hot(text):
out = [[0]*len_chars for _ in text]
i_list = text_to_i(text)
for n,i in enumerate(i_list):
out[n][i] = 1
return out
# ------------------------------------------------------------------------------
import numpy as np
INPUT = 4
sentences = [text[i:i+INPUT+1] for i in range(len(text)-INPUT-1)]
x = np.zeros((len(sentences),INPUT,len_chars),dtype='b')
y = np.zeros((len(sentences),len_chars),dtype='b')
for i,text in enumerate(sentences):
x[i]=text_to_hot(text[:-1])
y[i]=text_to_hot(text[-1:])[0]
print(x)
print(y)
# ------------------------------------------------------------------------------
from keras.models import Sequential,load_model
from keras.layers import Dense,LSTM
from keras.optimizers import RMSprop
if 0:
model = Sequential()
model.add(LSTM(4, input_shape=(INPUT,len_chars)))
#model.add(LSTM(4, batch_input_shape=(3,INPUT,len_chars), stateful=True))
model.add(Dense(len_chars,activation='softmax'))
optimizer=RMSprop(learning_rate=0.1)
model.compile(optimizer,loss='categorical_crossentropy')
model.fit(x,y,batch_size=3,epochs=20)
model.save('lstm_my.h5')
else:
model = load_model('lstm_my.h5')
# ------------------------------------------------------------------------------
def sample(p_list, t=1.0):
if not t: return np.argmax(p_list)
p_list = p_list.astype('float64') # bez tego suma norm_p moze byc > 1
log_p = np.log(p_list) / t
exp_p = np.exp(log_p)
norm_p = exp_p / np.sum(exp_p)
results = np.random.multinomial(1, norm_p, 1)
return np.argmax(results)
# ------------------------------------------------------------------------------
if 0:
px = np.array([text_to_hot('kot')])
py = model.predict(px)
pi=sample(py,0)
pc=i_to_c[pi]
print(px)
print(py)
print(i_to_c)
print(pi)
print(pc)
# ------------------------------------------------------------------------------
# TODO function
text = 'ala '
out = text[:]
for j in range(20):
x = np.array([text_to_hot(text)])
py = model.predict(x)[0]
pc=i_to_c[sample(py,1.0)]
out = out + pc
text = out[-INPUT:]
print(out)
|
[
"keras.models.load_model",
"numpy.log",
"numpy.argmax",
"numpy.random.multinomial",
"numpy.exp",
"keras.models.Sequential",
"keras.layers.LSTM",
"numpy.sum",
"keras.layers.Dense",
"keras.optimizers.RMSprop"
] |
[((1137, 1149), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1147, 1149), False, 'from keras.models import Sequential, load_model\n'), ((1338, 1364), 'keras.optimizers.RMSprop', 'RMSprop', ([], {'learning_rate': '(0.1)'}), '(learning_rate=0.1)\n', (1345, 1364), False, 'from keras.optimizers import RMSprop\n'), ((1503, 1527), 'keras.models.load_model', 'load_model', (['"""lstm_my.h5"""'], {}), "('lstm_my.h5')\n", (1513, 1527), False, 'from keras.models import Sequential, load_model\n'), ((1782, 1795), 'numpy.exp', 'np.exp', (['log_p'], {}), '(log_p)\n', (1788, 1795), True, 'import numpy as np\n'), ((1839, 1874), 'numpy.random.multinomial', 'np.random.multinomial', (['(1)', 'norm_p', '(1)'], {}), '(1, norm_p, 1)\n', (1860, 1874), True, 'import numpy as np\n'), ((1883, 1901), 'numpy.argmax', 'np.argmax', (['results'], {}), '(results)\n', (1892, 1901), True, 'import numpy as np\n'), ((1161, 1200), 'keras.layers.LSTM', 'LSTM', (['(4)'], {'input_shape': '(INPUT, len_chars)'}), '(4, input_shape=(INPUT, len_chars))\n', (1165, 1200), False, 'from keras.layers import Dense, LSTM\n'), ((1287, 1325), 'keras.layers.Dense', 'Dense', (['len_chars'], {'activation': '"""softmax"""'}), "(len_chars, activation='softmax')\n", (1292, 1325), False, 'from keras.layers import Dense, LSTM\n'), ((1656, 1673), 'numpy.argmax', 'np.argmax', (['p_list'], {}), '(p_list)\n', (1665, 1673), True, 'import numpy as np\n'), ((1754, 1768), 'numpy.log', 'np.log', (['p_list'], {}), '(p_list)\n', (1760, 1768), True, 'import numpy as np\n'), ((1814, 1827), 'numpy.sum', 'np.sum', (['exp_p'], {}), '(exp_p)\n', (1820, 1827), True, 'import numpy as np\n')]
|
import os
import os.path as osp
import sys
import numpy as np
from sklearn.svm import LinearSVC
from tqdm import tqdm
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
import torch.utils.data as data
from dataset.modelnet40 import LatentCapsulesModelNet40, LatentVectorsModelNet40
from utils.utils import create_save_folder, initialize_main
def main():
args, logdir = initialize_main()
# save_results folder
save_folder = create_save_folder(logdir, args["save_folder"])["save_folder"]
# datasets
args["train_root"] = os.path.join(logdir, args["train_root"])
args["test_root"] = os.path.join(logdir, args["test_root"])
# train loader
if args["train_root"].endswith(".npz"):
train_set = LatentVectorsModelNet40(args["train_root"]) # root is a npz file
elif args["train_root"].endswith(".h5"):
train_set = LatentCapsulesModelNet40(args["train_root"])
else:
raise Exception("Unknown dataset.")
train_loader = data.DataLoader(
train_set,
batch_size=args["batch_size"],
pin_memory=args["pin_memory"],
num_workers=args["num_workers"],
shuffle=args["shuffle"],
)
# test loader
if args["test_root"].endswith(".npz"):
test_set = LatentVectorsModelNet40(args["test_root"]) # root is a npz file
elif args["test_root"].endswith(".h5"):
test_set = LatentCapsulesModelNet40(args["test_root"])
else:
raise Exception("Unknown dataset.")
test_loader = data.DataLoader(
test_set,
batch_size=args["batch_size"],
pin_memory=args["pin_memory"],
num_workers=args["num_workers"],
shuffle=False,
)
# classifier
clf = LinearSVC()
# main
train_feature = np.zeros((1, args["input_size"]))
train_label = np.zeros((1, 1))
test_feature = np.zeros((1, args["input_size"]))
test_label = np.zeros((1, 1))
for batch_id, (latents, labels) in tqdm(enumerate(train_loader)):
train_label = np.concatenate((train_label, labels.numpy()), axis=None)
train_label = train_label.astype(int)
train_feature = np.concatenate((train_feature, latents.numpy()), axis=0)
if batch_id % 10 == 0:
print("add train batch: ", batch_id)
for batch_id, (latents, labels) in tqdm(enumerate(test_loader)):
test_label = np.concatenate((test_label, labels.numpy()), axis=None)
test_label = test_label.astype(int)
test_feature = np.concatenate((test_feature, latents.numpy()), axis=0)
if batch_id % 10 == 0:
print("add test batch: ", batch_id)
train_feature = train_feature[1:, :]
train_label = train_label[1:]
test_feature = test_feature[1:, :]
test_label = test_label[1:]
print("training the linear SVM.......")
clf.fit(train_feature, train_label)
confidence = clf.score(test_feature, test_label)
print("Accuracy: {} %".format(confidence * 100))
with open(os.path.join(save_folder, "accuracy.txt"), "a") as fp:
fp.write(str(confidence) + "\n")
if __name__ == "__main__":
main()
|
[
"sklearn.svm.LinearSVC",
"os.path.join",
"dataset.modelnet40.LatentCapsulesModelNet40",
"numpy.zeros",
"dataset.modelnet40.LatentVectorsModelNet40",
"torch.utils.data.DataLoader",
"os.path.abspath",
"utils.utils.initialize_main",
"utils.utils.create_save_folder"
] |
[((392, 409), 'utils.utils.initialize_main', 'initialize_main', ([], {}), '()\n', (407, 409), False, 'from utils.utils import create_save_folder, initialize_main\n'), ((559, 599), 'os.path.join', 'os.path.join', (['logdir', "args['train_root']"], {}), "(logdir, args['train_root'])\n", (571, 599), False, 'import os\n'), ((624, 663), 'os.path.join', 'os.path.join', (['logdir', "args['test_root']"], {}), "(logdir, args['test_root'])\n", (636, 663), False, 'import os\n'), ((997, 1148), 'torch.utils.data.DataLoader', 'data.DataLoader', (['train_set'], {'batch_size': "args['batch_size']", 'pin_memory': "args['pin_memory']", 'num_workers': "args['num_workers']", 'shuffle': "args['shuffle']"}), "(train_set, batch_size=args['batch_size'], pin_memory=args[\n 'pin_memory'], num_workers=args['num_workers'], shuffle=args['shuffle'])\n", (1012, 1148), True, 'import torch.utils.data as data\n'), ((1516, 1656), 'torch.utils.data.DataLoader', 'data.DataLoader', (['test_set'], {'batch_size': "args['batch_size']", 'pin_memory': "args['pin_memory']", 'num_workers': "args['num_workers']", 'shuffle': '(False)'}), "(test_set, batch_size=args['batch_size'], pin_memory=args[\n 'pin_memory'], num_workers=args['num_workers'], shuffle=False)\n", (1531, 1656), True, 'import torch.utils.data as data\n'), ((1727, 1738), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {}), '()\n', (1736, 1738), False, 'from sklearn.svm import LinearSVC\n'), ((1771, 1804), 'numpy.zeros', 'np.zeros', (["(1, args['input_size'])"], {}), "((1, args['input_size']))\n", (1779, 1804), True, 'import numpy as np\n'), ((1823, 1839), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (1831, 1839), True, 'import numpy as np\n'), ((1859, 1892), 'numpy.zeros', 'np.zeros', (["(1, args['input_size'])"], {}), "((1, args['input_size']))\n", (1867, 1892), True, 'import numpy as np\n'), ((1910, 1926), 'numpy.zeros', 'np.zeros', (['(1, 1)'], {}), '((1, 1))\n', (1918, 1926), True, 'import numpy as np\n'), ((455, 502), 'utils.utils.create_save_folder', 'create_save_folder', (['logdir', "args['save_folder']"], {}), "(logdir, args['save_folder'])\n", (473, 502), False, 'from utils.utils import create_save_folder, initialize_main\n'), ((748, 791), 'dataset.modelnet40.LatentVectorsModelNet40', 'LatentVectorsModelNet40', (["args['train_root']"], {}), "(args['train_root'])\n", (771, 791), False, 'from dataset.modelnet40 import LatentCapsulesModelNet40, LatentVectorsModelNet40\n'), ((1272, 1314), 'dataset.modelnet40.LatentVectorsModelNet40', 'LatentVectorsModelNet40', (["args['test_root']"], {}), "(args['test_root'])\n", (1295, 1314), False, 'from dataset.modelnet40 import LatentCapsulesModelNet40, LatentVectorsModelNet40\n'), ((161, 182), 'os.path.abspath', 'osp.abspath', (['__file__'], {}), '(__file__)\n', (172, 182), True, 'import os.path as osp\n'), ((879, 923), 'dataset.modelnet40.LatentCapsulesModelNet40', 'LatentCapsulesModelNet40', (["args['train_root']"], {}), "(args['train_root'])\n", (903, 923), False, 'from dataset.modelnet40 import LatentCapsulesModelNet40, LatentVectorsModelNet40\n'), ((1400, 1443), 'dataset.modelnet40.LatentCapsulesModelNet40', 'LatentCapsulesModelNet40', (["args['test_root']"], {}), "(args['test_root'])\n", (1424, 1443), False, 'from dataset.modelnet40 import LatentCapsulesModelNet40, LatentVectorsModelNet40\n'), ((2985, 3026), 'os.path.join', 'os.path.join', (['save_folder', '"""accuracy.txt"""'], {}), "(save_folder, 'accuracy.txt')\n", (2997, 3026), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import Sequence
import numpy as np
class MatrixBase(object):
__metaclass__ = ABCMeta
_base_tags = set()
@abstractmethod
def __init__(self, backend, ioshape, iopacking, tags):
self.backend = backend
self.ioshape = ioshape
self.iopacking = iopacking
self.tags = self._base_tags | tags
@abstractmethod
def get(self):
return self._unpack(self._get())
@abstractproperty
def nbytes(self):
"""Size in bytes"""
pass
@property
def aos_shape(self):
return self.backend.aos_shape(self.ioshape, self.iopacking)
@property
def soa_shape(self):
return self.backend.soa_shape(self.ioshape, self.iopacking)
class Matrix(MatrixBase):
"""Matrix abstract base class
"""
_base_tags = {'dense'}
@abstractmethod
def set(self, buf):
pass
def rslice(self, p, q):
return self.backend.matrix_rslice(self, p, q)
class MatrixRSlice(object):
"""Slice of a matrix abstract base class"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, backend, mat, p, q):
self.backend = backend
self.parent = mat
if p < 0 or q > mat.nrow or q < p:
raise ValueError('Invalid row slice')
self.nrow = q - p
self.ncol = mat.ncol
self.tags = mat.tags | {'slice'}
@property
def nbytes(self):
return 0
class ConstMatrix(MatrixBase):
"""Constant matrix abstract base class"""
_base_tags = {'const', 'dense'}
class BlockDiagMatrix(MatrixBase):
_base_tags = {'const', 'blockdiag'}
def __init__(self, backend, initval, brange, iopacking, tags):
super(BlockDiagMatrix, self).__init__(backend, initval.shape,
iopacking, tags)
self.initval = initval
# Compact down to a Matrix and extract the blocks
mat = backend.compact_arr(initval, iopacking)
self.blocks = [mat[ri:rj,ci:cj] for ri, rj, ci, cj in brange]
self.ranges = brange
def get(self):
return self.initval
@property
def nbytes(self):
return 0
class MPIMatrix(Matrix):
"""MPI matrix abstract base class"""
pass
class MatrixBank(Sequence):
"""Matrix bank abstract base class"""
@abstractmethod
def __init__(self, backend, mats, initbank, tags):
self.backend = backend
self._mats = mats
self._curr_idx = initbank
self._curr_mat = self._mats[initbank]
# Process tags
if any(mats[0].tags != m.tags for m in mats[1:]):
raise ValueError('Banked matrices must share tags')
self.tags = tags | mats[0].tags
def __len__(self):
return len(self._mats)
def __getitem__(self, idx):
return self._mats[idx]
def __getattr__(self, attr):
return getattr(self._curr_mat, attr)
def rslice(self, p, q):
raise RuntimeError('Matrix banks can not be sliced')
@property
def active(self):
return self._curr_idx
@active.setter
def active(self, idx):
self._curr_idx = idx
self._curr_mat = self._mats[idx]
@property
def nbytes(self):
return sum(m.nbytes for m in self)
class View(object):
"""View abstract base class"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, backend, matmap, rcmap, stridemap, vlen, tags):
self.nrow = nrow = matmap.shape[0]
self.ncol = ncol = matmap.shape[1]
self.vlen = vlen
# Get the different matrices which we map onto
self._mats = list(np.unique(matmap))
# Extract the data type and item size from the first matrix
self.refdtype = self._mats[0].dtype
self.refitemsize = self._mats[0].itemsize
# For vector views a stridemap is required
if vlen != 1 and np.any(stridemap == 0):
raise ValueError('Vector views require a non-zero stride map')
# Check all of the shapes match up
if matmap.shape != rcmap.shape[:2] or\
matmap.shape != stridemap.shape:
raise TypeError('Invalid matrix shapes')
# Validate the matrices
for m in self._mats:
if not isinstance(m, backend.matrix_cls):
raise TypeError('Incompatible matrix type for view')
if m.dtype != self.refdtype:
raise TypeError('Mixed data types are not supported')
@abstractproperty
def nbytes(self):
pass
class MPIView(object):
@abstractmethod
def __init__(self, backend, matmap, rcmap, stridemap, vlen, tags):
self.nrow = nrow = matmap.shape[0]
self.ncol = ncol = matmap.shape[1]
self.vlen = vlen
# Create a normal view
self.view = backend.view(matmap, rcmap, stridemap, vlen, tags)
# Now create an MPI matrix so that the view contents may be packed
self.mpimat = backend.mpi_matrix((nrow, ncol, vlen), None, 'AoS',
tags=tags)
@property
def nbytes(self):
return self.view.nbytes + self.mpimat.nbytes
class Queue(object):
"""Kernel execution queue"""
__metaclass__ = ABCMeta
@abstractmethod
def __lshift__(self, iterable):
"""Appends the kernels in *iterable* to the queue
.. note::
This method does **not** execute the kernels, but rather just
schedules them. Queued kernels should be executed by
calling :meth:`pyfr.backends.base.Backend.runall`
"""
pass
@abstractmethod
def __mod__(self, iterable):
"""Synchronously executes the kernels in *iterable*
.. note::
In the (unusual) instance that the queue already has one or
more kernels queued these will run first.
"""
pass
|
[
"numpy.unique",
"numpy.any"
] |
[((3740, 3757), 'numpy.unique', 'np.unique', (['matmap'], {}), '(matmap)\n', (3749, 3757), True, 'import numpy as np\n'), ((3999, 4021), 'numpy.any', 'np.any', (['(stridemap == 0)'], {}), '(stridemap == 0)\n', (4005, 4021), True, 'import numpy as np\n')]
|
from __future__ import division
import argparse, logging, os, math, tqdm
import numpy as np
import mxnet as mx
from mxnet import gluon, nd, image
from mxnet.gluon.data.vision import transforms
import matplotlib.pyplot as plt
import gluoncv as gcv
from gluoncv import data
from gluoncv.data import mscoco
from gluoncv.model_zoo import get_model
from gluoncv.data.transforms.pose import get_final_preds
parser = argparse.ArgumentParser(description='Predict ImageNet classes from a given image')
parser.add_argument('--detector', type=str, default='yolo3_mobilenet1.0_coco',
help='name of the detection model to use')
parser.add_argument('--pose-model', type=str, default='simple_pose_resnet50_v1b',
help='name of the pose estimation model to use')
parser.add_argument('--input-pic', type=str, required=True,
help='path to the input picture')
opt = parser.parse_args()
def upscale_bbox_fn(bbox, img, scale=1.25):
new_bbox = []
x0 = bbox[0]
y0 = bbox[1]
x1 = bbox[2]
y1 = bbox[3]
w = (x1 - x0) / 2
h = (y1 - y0) / 2
center = [x0 + w, y0 + h]
new_x0 = max(center[0] - w * scale, 0)
new_y0 = max(center[1] - h * scale, 0)
new_x1 = min(center[0] + w * scale, img.shape[1])
new_y1 = min(center[1] + h * scale, img.shape[0])
new_bbox = [new_x0, new_y0, new_x1, new_y1]
return new_bbox
def crop_resize_normalize(img, bbox_list, output_size):
output_list = []
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
for bbox in bbox_list:
x0 = max(int(bbox[0]), 0)
y0 = max(int(bbox[1]), 0)
x1 = min(int(bbox[2]), int(img.shape[1]))
y1 = min(int(bbox[3]), int(img.shape[0]))
w = x1 - x0
h = y1 - y0
res_img = image.fixed_crop(nd.array(img), x0, y0, w, h, (output_size[1], output_size[0]))
res_img = transform_test(res_img)
output_list.append(res_img)
output_array = nd.stack(*output_list)
return output_array
def get_final_preds(batch_heatmaps, center, scale):
from gluoncv.data.transforms.pose import get_max_pred
coords, maxvals = get_max_pred(batch_heatmaps)
heatmap_height = batch_heatmaps.shape[2]
heatmap_width = batch_heatmaps.shape[3]
# post-processing
for n in range(coords.shape[0]):
for p in range(coords.shape[1]):
hm = batch_heatmaps[n][p]
px = int(nd.floor(coords[n][p][0] + 0.5).asscalar())
py = int(nd.floor(coords[n][p][1] + 0.5).asscalar())
if 1 < px < heatmap_width-1 and 1 < py < heatmap_height-1:
diff = nd.concat(hm[py][px+1] - hm[py][px-1],
hm[py+1][px] - hm[py-1][px],
dim=0)
coords[n][p] += nd.sign(diff) * .25
preds = nd.zeros_like(coords)
# Transform back
for i in range(coords.shape[0]):
w_ratio = coords[i][:, 0] / heatmap_width
h_ratio = coords[i][:, 1] / heatmap_height
preds[i][:, 0] = scale[i][0] * 2 * w_ratio + center[i][0] - scale[i][0]
preds[i][:, 1] = scale[i][1] * 2 * h_ratio + center[i][1] - scale[i][1]
return preds, maxvals
def heatmap_to_coord(heatmaps, bbox_list):
center_list = []
scale_list = []
for i, bbox in enumerate(bbox_list):
x0 = bbox[0]
y0 = bbox[1]
x1 = bbox[2]
y1 = bbox[3]
w = (x1 - x0) / 2
h = (y1 - y0) / 2
center_list.append(np.array([x0 + w, y0 + h]))
scale_list.append(np.array([w, h]))
coords, maxvals = get_final_preds(heatmaps, center_list, scale_list)
return coords, maxvals
def keypoint_detection(img_path, detector, pose_net):
# detector
x, img = data.transforms.presets.yolo.load_test(img_path, short=512)
class_IDs, scores, bounding_boxs = detector(x)
# input processing
L = class_IDs.shape[1]
thr = 0.5
upscale_bbox = []
for i in range(L):
if class_IDs[0][i].asscalar() != 0:
continue
if scores[0][i].asscalar() < thr:
continue
bbox = bounding_boxs[0][i]
upscale_bbox.append(upscale_bbox_fn(bbox.asnumpy().tolist(), img, scale=1.25))
pose_input = crop_resize_normalize(img, upscale_bbox, (256, 192))
# pose estimation
predicted_heatmap = pose_net(pose_input)
pred_coords, confidence = heatmap_to_coord(predicted_heatmap, upscale_bbox)
# Plot
confidence_thred = 0.2
joint_visible = confidence[:,:,0].asnumpy() > confidence_thred
joint_pairs = [[0,1], [1,3], [0,2], [2,4],
[5,6], [5,7], [7,9], [6,8], [8,10],
[5,11], [6,12], [11,12],
[11,13], [12,14], [13,15], [14,16]]
person_ind = class_IDs[0].asnumpy() == 0
ax = gcv.utils.viz.plot_bbox(img, bounding_boxs[0].asnumpy()[person_ind[:,0]],
scores[0].asnumpy()[person_ind[:,0]], thresh=0.5)
plt.xlim([0, img.shape[1]-1])
plt.ylim([0, img.shape[0]-1])
plt.gca().invert_yaxis()
for i in range(pred_coords.shape[0]):
pts = pred_coords[i].asnumpy()
colormap_index = np.linspace(0, 1, len(joint_pairs))
for cm_ind, jp in zip(colormap_index, joint_pairs):
if joint_visible[i, jp[0]] and joint_visible[i, jp[1]]:
plt.plot(pts[jp, 0], pts[jp, 1],
linewidth=5.0, alpha=0.7, color=plt.cm.cool(cm_ind))
plt.scatter(pts[jp, 0], pts[jp, 1], s=20)
plt.show()
if __name__ == '__main__':
detector = get_model(opt.detector, ctx=mx.cpu(), pretrained=True)
if opt.detector.startswith('ssd') or opt.detector.startswith('yolo'):
detector.reset_class(["person"], reuse_weights=['person'])
net = get_model(opt.pose_model, pretrained=True, ctx=mx.cpu())
keypoint_detection(opt.input_pic, detector, net)
|
[
"gluoncv.data.transforms.presets.yolo.load_test",
"mxnet.nd.sign",
"gluoncv.data.transforms.pose.get_final_preds",
"numpy.array",
"mxnet.nd.zeros_like",
"gluoncv.data.transforms.pose.get_max_pred",
"argparse.ArgumentParser",
"matplotlib.pyplot.scatter",
"mxnet.nd.array",
"matplotlib.pyplot.ylim",
"mxnet.nd.stack",
"matplotlib.pyplot.gca",
"mxnet.nd.floor",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"mxnet.gluon.data.vision.transforms.ToTensor",
"matplotlib.pyplot.cm.cool",
"mxnet.gluon.data.vision.transforms.Normalize",
"mxnet.cpu",
"mxnet.nd.concat"
] |
[((415, 502), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Predict ImageNet classes from a given image"""'}), "(description=\n 'Predict ImageNet classes from a given image')\n", (438, 502), False, 'import argparse, logging, os, math, tqdm\n'), ((2061, 2083), 'mxnet.nd.stack', 'nd.stack', (['*output_list'], {}), '(*output_list)\n', (2069, 2083), False, 'from mxnet import gluon, nd, image\n'), ((2241, 2269), 'gluoncv.data.transforms.pose.get_max_pred', 'get_max_pred', (['batch_heatmaps'], {}), '(batch_heatmaps)\n', (2253, 2269), False, 'from gluoncv.data.transforms.pose import get_max_pred\n'), ((2929, 2950), 'mxnet.nd.zeros_like', 'nd.zeros_like', (['coords'], {}), '(coords)\n', (2942, 2950), False, 'from mxnet import gluon, nd, image\n'), ((3682, 3732), 'gluoncv.data.transforms.pose.get_final_preds', 'get_final_preds', (['heatmaps', 'center_list', 'scale_list'], {}), '(heatmaps, center_list, scale_list)\n', (3697, 3732), False, 'from gluoncv.data.transforms.pose import get_final_preds\n'), ((3843, 3902), 'gluoncv.data.transforms.presets.yolo.load_test', 'data.transforms.presets.yolo.load_test', (['img_path'], {'short': '(512)'}), '(img_path, short=512)\n', (3881, 3902), False, 'from gluoncv import data\n'), ((5055, 5086), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, img.shape[1] - 1]'], {}), '([0, img.shape[1] - 1])\n', (5063, 5086), True, 'import matplotlib.pyplot as plt\n'), ((5089, 5120), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, img.shape[0] - 1]'], {}), '([0, img.shape[0] - 1])\n', (5097, 5120), True, 'import matplotlib.pyplot as plt\n'), ((5608, 5618), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5616, 5618), True, 'import matplotlib.pyplot as plt\n'), ((1526, 1547), 'mxnet.gluon.data.vision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1545, 1547), False, 'from mxnet.gluon.data.vision import transforms\n'), ((1557, 1623), 'mxnet.gluon.data.vision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (1577, 1623), False, 'from mxnet.gluon.data.vision import transforms\n'), ((1901, 1914), 'mxnet.nd.array', 'nd.array', (['img'], {}), '(img)\n', (1909, 1914), False, 'from mxnet import gluon, nd, image\n'), ((3587, 3613), 'numpy.array', 'np.array', (['[x0 + w, y0 + h]'], {}), '([x0 + w, y0 + h])\n', (3595, 3613), True, 'import numpy as np\n'), ((3641, 3657), 'numpy.array', 'np.array', (['[w, h]'], {}), '([w, h])\n', (3649, 3657), True, 'import numpy as np\n'), ((5123, 5132), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5130, 5132), True, 'import matplotlib.pyplot as plt\n'), ((5690, 5698), 'mxnet.cpu', 'mx.cpu', ([], {}), '()\n', (5696, 5698), True, 'import mxnet as mx\n'), ((5915, 5923), 'mxnet.cpu', 'mx.cpu', ([], {}), '()\n', (5921, 5923), True, 'import mxnet as mx\n'), ((2723, 2809), 'mxnet.nd.concat', 'nd.concat', (['(hm[py][px + 1] - hm[py][px - 1])', '(hm[py + 1][px] - hm[py - 1][px])'], {'dim': '(0)'}), '(hm[py][px + 1] - hm[py][px - 1], hm[py + 1][px] - hm[py - 1][px],\n dim=0)\n', (2732, 2809), False, 'from mxnet import gluon, nd, image\n'), ((5561, 5602), 'matplotlib.pyplot.scatter', 'plt.scatter', (['pts[jp, 0]', 'pts[jp, 1]'], {'s': '(20)'}), '(pts[jp, 0], pts[jp, 1], s=20)\n', (5572, 5602), True, 'import matplotlib.pyplot as plt\n'), ((2896, 2909), 'mxnet.nd.sign', 'nd.sign', (['diff'], {}), '(diff)\n', (2903, 2909), False, 'from mxnet import gluon, nd, image\n'), ((2520, 2551), 'mxnet.nd.floor', 'nd.floor', (['(coords[n][p][0] + 0.5)'], {}), '(coords[n][p][0] + 0.5)\n', (2528, 2551), False, 'from mxnet import gluon, nd, image\n'), ((2585, 2616), 'mxnet.nd.floor', 'nd.floor', (['(coords[n][p][1] + 0.5)'], {}), '(coords[n][p][1] + 0.5)\n', (2593, 2616), False, 'from mxnet import gluon, nd, image\n'), ((5524, 5543), 'matplotlib.pyplot.cm.cool', 'plt.cm.cool', (['cm_ind'], {}), '(cm_ind)\n', (5535, 5543), True, 'import matplotlib.pyplot as plt\n')]
|
import cv2
import numpy as np
import random as rd
import os
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Input
from tensorflow.keras.optimizers import Adadelta
from tensorflow.keras.callbacks import EarlyStopping,ModelCheckpoint
from tensorflow.keras.backend import image_data_format
from tensorflow.keras.layers import BatchNormalization
# ===========================
# SETTINGS
# ===========================
VALIDATION_SPLIT=0.2
BATCH_SIZE = 16
# ===========================
def get_input_shape(height, width, channels = 3):
if image_data_format() == 'channels_first':
return (channels, height, width)
else:
return (height, width, channels)
def get_convnet(height, width, labels):
img_input = Input(shape=get_input_shape(height,width))
x = img_input
for layer in range(1,5):
x = Conv2D(filters=32*layer, kernel_size=(3, 3), padding='same')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dense(labels,activation='softmax')(x)
return Model(img_input, x, name='calvonet')
def getTrain(input_image, gt, hspan, vspan, num_labels, max_samples_per_class):
X_train = []
Y_train = []
# Speed-up factor
factor = 10.
# Calculate the ratio per label
count = [0] * num_labels
for page in range(len(input_image)):
for i in range(num_labels):
count[i] += (gt[page] == i).sum()
samples_per_class = min(np.min(count), max_samples_per_class)
ratio = [0] * num_labels
for i in range(num_labels):
ratio[i] = factor * (samples_per_class/float(count[i]))
# Just for checking !
count_per_class = [0] * num_labels
# Get samples according to the ratio per label
for page in range(len(input_image)):
page_x = input_image[page]
page_y = gt[page]
[height, width] = page_y.shape
for row in range(vspan,height-vspan-1):
for col in range(hspan,width-hspan-1):
if rd.random() < 1./factor:
label = page_y[row][col]
if 0 <= label < num_labels: # Avoid possible noise in the GT or -1 (unknown pixel)
if rd.random() < ratio[label]: # Take samples according to its
sample = page_x[row-vspan:row+vspan+1,col-hspan:col+hspan+1]
# Categorical vector
y_label = [0]*num_labels
y_label[label] = 1
X_train.append(sample)
Y_train.append(y_label)
count_per_class[label] += 1
# Manage different ordering
if image_data_format() == 'channels_first':
X_train = np.asarray(X_train).reshape(len(X_train), 3, vspan*2 + 1, hspan*2 + 1)
else:
X_train = np.asarray(X_train).reshape(len(X_train), vspan*2 + 1, hspan*2 + 1, 3)
Y_train = np.asarray(Y_train).reshape(len(Y_train), num_labels)
print('Distribution of data per class: ' + str(count_per_class))
return [X_train, Y_train]
def train_model(input_image, gt, hspan, vspan, output_model_path, max_samples_per_class, epochs, num_labels = 4):
# -------------------------------------------------------------------------------------------------------------------
# Create training set
[X_train, Y_train] = getTrain([input_image], [gt],
hspan, vspan,
num_labels,
max_samples_per_class=max_samples_per_class)
print('Training created with ' + str(len(X_train)) + ' samples.')
# Training configuration
print('Training a new model')
model = get_convnet(
height=hspan * 2 + 1,
width=vspan * 2 + 1,
labels=num_labels
)
#model.summary()
# In Tensorflow 2, it is necessary to add '.h5' to the end of the filename to force saving
# in hdf5 format with a ModelCheckpoint. Rodan will not accept anything but the file's
# original filename, however, so we must rename it back after training.
new_output_path = os.path.join(output_model_path + '.h5')
callbacks_list = [
ModelCheckpoint(new_output_path, save_best_only=True, monitor='val_acc', verbose=1, mode='max'),
EarlyStopping(monitor='val_acc', patience=3, verbose=0, mode='max')
]
model.compile(loss='categorical_crossentropy',
optimizer=Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0),
metrics=["accuracy"])
# Training stage
model.fit(X_train, Y_train,
verbose=2,
batch_size=BATCH_SIZE,
validation_split=VALIDATION_SPLIT,
callbacks=callbacks_list,
epochs=epochs
)
# Rename the file back to what Rodan expects.
os.rename(new_output_path, output_model_path)
return 0
|
[
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.MaxPooling2D",
"os.rename",
"os.path.join",
"numpy.asarray",
"tensorflow.keras.optimizers.Adadelta",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.callbacks.EarlyStopping",
"random.random",
"tensorflow.keras.layers.Dense",
"numpy.min",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.backend.image_data_format",
"tensorflow.keras.callbacks.ModelCheckpoint"
] |
[((1236, 1272), 'tensorflow.keras.models.Model', 'Model', (['img_input', 'x'], {'name': '"""calvonet"""'}), "(img_input, x, name='calvonet')\n", (1241, 1272), False, 'from tensorflow.keras.models import Sequential, Model\n'), ((4349, 4388), 'os.path.join', 'os.path.join', (["(output_model_path + '.h5')"], {}), "(output_model_path + '.h5')\n", (4361, 4388), False, 'import os\n'), ((5094, 5139), 'os.rename', 'os.rename', (['new_output_path', 'output_model_path'], {}), '(new_output_path, output_model_path)\n', (5103, 5139), False, 'import os\n'), ((683, 702), 'tensorflow.keras.backend.image_data_format', 'image_data_format', ([], {}), '()\n', (700, 702), False, 'from tensorflow.keras.backend import image_data_format\n'), ((1166, 1175), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (1173, 1175), False, 'from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\n'), ((1187, 1222), 'tensorflow.keras.layers.Dense', 'Dense', (['labels'], {'activation': '"""softmax"""'}), "(labels, activation='softmax')\n", (1192, 1222), False, 'from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\n'), ((1649, 1662), 'numpy.min', 'np.min', (['count'], {}), '(count)\n', (1655, 1662), True, 'import numpy as np\n'), ((2899, 2918), 'tensorflow.keras.backend.image_data_format', 'image_data_format', ([], {}), '()\n', (2916, 2918), False, 'from tensorflow.keras.backend import image_data_format\n'), ((4425, 4524), 'tensorflow.keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['new_output_path'], {'save_best_only': '(True)', 'monitor': '"""val_acc"""', 'verbose': '(1)', 'mode': '"""max"""'}), "(new_output_path, save_best_only=True, monitor='val_acc',\n verbose=1, mode='max')\n", (4440, 4524), False, 'from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((4534, 4601), 'tensorflow.keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_acc"""', 'patience': '(3)', 'verbose': '(0)', 'mode': '"""max"""'}), "(monitor='val_acc', patience=3, verbose=0, mode='max')\n", (4547, 4601), False, 'from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((977, 1039), 'tensorflow.keras.layers.Conv2D', 'Conv2D', ([], {'filters': '(32 * layer)', 'kernel_size': '(3, 3)', 'padding': '"""same"""'}), "(filters=32 * layer, kernel_size=(3, 3), padding='same')\n", (983, 1039), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, Input\n'), ((1053, 1073), 'tensorflow.keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1071, 1073), False, 'from tensorflow.keras.layers import BatchNormalization\n'), ((1089, 1107), 'tensorflow.keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1099, 1107), False, 'from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\n'), ((1123, 1153), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (1135, 1153), False, 'from tensorflow.keras.layers import Conv2D, MaxPooling2D, Input\n'), ((3143, 3162), 'numpy.asarray', 'np.asarray', (['Y_train'], {}), '(Y_train)\n', (3153, 3162), True, 'import numpy as np\n'), ((4696, 4748), 'tensorflow.keras.optimizers.Adadelta', 'Adadelta', ([], {'lr': '(1.0)', 'rho': '(0.95)', 'epsilon': '(1e-08)', 'decay': '(0.0)'}), '(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0)\n', (4704, 4748), False, 'from tensorflow.keras.optimizers import Adadelta\n'), ((2958, 2977), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (2968, 2977), True, 'import numpy as np\n'), ((3057, 3076), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (3067, 3076), True, 'import numpy as np\n'), ((2195, 2206), 'random.random', 'rd.random', ([], {}), '()\n', (2204, 2206), True, 'import random as rd\n'), ((2398, 2409), 'random.random', 'rd.random', ([], {}), '()\n', (2407, 2409), True, 'import random as rd\n')]
|
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger()
logger.basicConfig = logging.basicConfig(level=logging.DEBUG)
import numpy as np
import matplotlib.pyplot as plt
import logictensornetworks_wrapper as ltnw
nr_samples=500
data=np.random.uniform([0,0],[1.,1.],(nr_samples,2)).astype(np.float32)
data_A=data[np.where(np.sum(np.square(data-[.5,.5]),axis=1)<.09)]
data_B=data[np.where(np.sum(np.square(data-[.5,.5]),axis=1)>=.09)]
ltnw.variable("?data",data)
ltnw.variable("?data_A",data_A)
ltnw.variable("?data_B",data_B)
ltnw.predicate("A",2)
ltnw.predicate("B",2)
ltnw.axiom("forall ?data_A: A(?data_A)")
ltnw.axiom("forall ?data_B: ~A(?data_B)")
ltnw.axiom("forall ?data_B: B(?data_B)")
ltnw.axiom("forall ?data_A: ~B(?data_A)")
ltnw.axiom("forall ?data: A(?data) -> ~B(?data)")
ltnw.axiom("forall ?data: B(?data) -> ~A(?data)")
ltnw.initialize_knowledgebase(initial_sat_level_threshold=.1)
sat_level=ltnw.train(track_sat_levels=1000,sat_level_epsilon=.99,max_epochs=20000)
result=ltnw.ask("A(?data)")
plt.figure(figsize=(10,8))
plt.subplot(2,2,1)
plt.title("A(x) - training")
plt.scatter(data[:,0],data[:,1],c=result.squeeze())
plt.colorbar()
plt.subplot(2,2,2)
result=ltnw.ask("B(?data)")
plt.title("B(x) - training")
plt.scatter(data[:,0],data[:,1],c=result.squeeze())
plt.colorbar()
data_test=np.random.uniform([0,0],[1.,1.],(nr_samples,2)).astype(np.float32)
ltnw.variable("?data_test",data_test)
result=ltnw.ask("A(?data_test)")
plt.subplot(2,2,3)
plt.title("A(x) - test")
plt.scatter(data_test[:,0],data_test[:,1],c=result.squeeze())
plt.colorbar()
result=ltnw.ask("B(?data_test)")
plt.subplot(2,2,4)
plt.title("B(x) -test")
plt.scatter(data_test[:,0],data_test[:,1],c=result.squeeze())
plt.colorbar()
plt.show()
ltnw.constant("a",[0.5,.5])
ltnw.constant("b",[0.75,.75])
print("a is in A: %s" % ltnw.ask("A(a)"))
print("b is in A: %s" % ltnw.ask("A(b)"))
print("a is in B: %s" % ltnw.ask("B(a)"))
print("b is in B: %s" % ltnw.ask("B(b)"))
|
[
"logging.getLogger",
"logging.basicConfig",
"logictensornetworks_wrapper.constant",
"logictensornetworks_wrapper.variable",
"matplotlib.pyplot.colorbar",
"logictensornetworks_wrapper.train",
"numpy.square",
"logictensornetworks_wrapper.predicate",
"logictensornetworks_wrapper.axiom",
"logictensornetworks_wrapper.initialize_knowledgebase",
"logictensornetworks_wrapper.ask",
"matplotlib.pyplot.figure",
"numpy.random.uniform",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] |
[((48, 67), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (65, 67), False, 'import logging\n'), ((89, 129), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (108, 129), False, 'import logging\n'), ((448, 476), 'logictensornetworks_wrapper.variable', 'ltnw.variable', (['"""?data"""', 'data'], {}), "('?data', data)\n", (461, 476), True, 'import logictensornetworks_wrapper as ltnw\n'), ((476, 508), 'logictensornetworks_wrapper.variable', 'ltnw.variable', (['"""?data_A"""', 'data_A'], {}), "('?data_A', data_A)\n", (489, 508), True, 'import logictensornetworks_wrapper as ltnw\n'), ((508, 540), 'logictensornetworks_wrapper.variable', 'ltnw.variable', (['"""?data_B"""', 'data_B'], {}), "('?data_B', data_B)\n", (521, 540), True, 'import logictensornetworks_wrapper as ltnw\n'), ((541, 563), 'logictensornetworks_wrapper.predicate', 'ltnw.predicate', (['"""A"""', '(2)'], {}), "('A', 2)\n", (555, 563), True, 'import logictensornetworks_wrapper as ltnw\n'), ((563, 585), 'logictensornetworks_wrapper.predicate', 'ltnw.predicate', (['"""B"""', '(2)'], {}), "('B', 2)\n", (577, 585), True, 'import logictensornetworks_wrapper as ltnw\n'), ((586, 626), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data_A: A(?data_A)"""'], {}), "('forall ?data_A: A(?data_A)')\n", (596, 626), True, 'import logictensornetworks_wrapper as ltnw\n'), ((627, 668), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data_B: ~A(?data_B)"""'], {}), "('forall ?data_B: ~A(?data_B)')\n", (637, 668), True, 'import logictensornetworks_wrapper as ltnw\n'), ((670, 710), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data_B: B(?data_B)"""'], {}), "('forall ?data_B: B(?data_B)')\n", (680, 710), True, 'import logictensornetworks_wrapper as ltnw\n'), ((711, 752), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data_A: ~B(?data_A)"""'], {}), "('forall ?data_A: ~B(?data_A)')\n", (721, 752), True, 'import logictensornetworks_wrapper as ltnw\n'), ((754, 803), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data: A(?data) -> ~B(?data)"""'], {}), "('forall ?data: A(?data) -> ~B(?data)')\n", (764, 803), True, 'import logictensornetworks_wrapper as ltnw\n'), ((804, 853), 'logictensornetworks_wrapper.axiom', 'ltnw.axiom', (['"""forall ?data: B(?data) -> ~A(?data)"""'], {}), "('forall ?data: B(?data) -> ~A(?data)')\n", (814, 853), True, 'import logictensornetworks_wrapper as ltnw\n'), ((855, 917), 'logictensornetworks_wrapper.initialize_knowledgebase', 'ltnw.initialize_knowledgebase', ([], {'initial_sat_level_threshold': '(0.1)'}), '(initial_sat_level_threshold=0.1)\n', (884, 917), True, 'import logictensornetworks_wrapper as ltnw\n'), ((927, 1002), 'logictensornetworks_wrapper.train', 'ltnw.train', ([], {'track_sat_levels': '(1000)', 'sat_level_epsilon': '(0.99)', 'max_epochs': '(20000)'}), '(track_sat_levels=1000, sat_level_epsilon=0.99, max_epochs=20000)\n', (937, 1002), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1008, 1028), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""A(?data)"""'], {}), "('A(?data)')\n", (1016, 1028), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1029, 1056), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 8)'}), '(figsize=(10, 8))\n', (1039, 1056), True, 'import matplotlib.pyplot as plt\n'), ((1056, 1076), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (1067, 1076), True, 'import matplotlib.pyplot as plt\n'), ((1075, 1103), 'matplotlib.pyplot.title', 'plt.title', (['"""A(x) - training"""'], {}), "('A(x) - training')\n", (1084, 1103), True, 'import matplotlib.pyplot as plt\n'), ((1156, 1170), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1168, 1170), True, 'import matplotlib.pyplot as plt\n'), ((1172, 1192), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (1183, 1192), True, 'import matplotlib.pyplot as plt\n'), ((1198, 1218), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""B(?data)"""'], {}), "('B(?data)')\n", (1206, 1218), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1219, 1247), 'matplotlib.pyplot.title', 'plt.title', (['"""B(x) - training"""'], {}), "('B(x) - training')\n", (1228, 1247), True, 'import matplotlib.pyplot as plt\n'), ((1300, 1314), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1312, 1314), True, 'import matplotlib.pyplot as plt\n'), ((1393, 1431), 'logictensornetworks_wrapper.variable', 'ltnw.variable', (['"""?data_test"""', 'data_test'], {}), "('?data_test', data_test)\n", (1406, 1431), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1438, 1463), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""A(?data_test)"""'], {}), "('A(?data_test)')\n", (1446, 1463), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1464, 1484), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (1475, 1484), True, 'import matplotlib.pyplot as plt\n'), ((1483, 1507), 'matplotlib.pyplot.title', 'plt.title', (['"""A(x) - test"""'], {}), "('A(x) - test')\n", (1492, 1507), True, 'import matplotlib.pyplot as plt\n'), ((1570, 1584), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1582, 1584), True, 'import matplotlib.pyplot as plt\n'), ((1593, 1618), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""B(?data_test)"""'], {}), "('B(?data_test)')\n", (1601, 1618), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1619, 1639), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (1630, 1639), True, 'import matplotlib.pyplot as plt\n'), ((1638, 1661), 'matplotlib.pyplot.title', 'plt.title', (['"""B(x) -test"""'], {}), "('B(x) -test')\n", (1647, 1661), True, 'import matplotlib.pyplot as plt\n'), ((1724, 1738), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1736, 1738), True, 'import matplotlib.pyplot as plt\n'), ((1740, 1750), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1748, 1750), True, 'import matplotlib.pyplot as plt\n'), ((1752, 1782), 'logictensornetworks_wrapper.constant', 'ltnw.constant', (['"""a"""', '[0.5, 0.5]'], {}), "('a', [0.5, 0.5])\n", (1765, 1782), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1780, 1812), 'logictensornetworks_wrapper.constant', 'ltnw.constant', (['"""b"""', '[0.75, 0.75]'], {}), "('b', [0.75, 0.75])\n", (1793, 1812), True, 'import logictensornetworks_wrapper as ltnw\n'), ((247, 301), 'numpy.random.uniform', 'np.random.uniform', (['[0, 0]', '[1.0, 1.0]', '(nr_samples, 2)'], {}), '([0, 0], [1.0, 1.0], (nr_samples, 2))\n', (264, 301), True, 'import numpy as np\n'), ((1326, 1380), 'numpy.random.uniform', 'np.random.uniform', (['[0, 0]', '[1.0, 1.0]', '(nr_samples, 2)'], {}), '([0, 0], [1.0, 1.0], (nr_samples, 2))\n', (1343, 1380), True, 'import numpy as np\n'), ((1834, 1850), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""A(a)"""'], {}), "('A(a)')\n", (1842, 1850), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1876, 1892), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""A(b)"""'], {}), "('A(b)')\n", (1884, 1892), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1918, 1934), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""B(a)"""'], {}), "('B(a)')\n", (1926, 1934), True, 'import logictensornetworks_wrapper as ltnw\n'), ((1960, 1976), 'logictensornetworks_wrapper.ask', 'ltnw.ask', (['"""B(b)"""'], {}), "('B(b)')\n", (1968, 1976), True, 'import logictensornetworks_wrapper as ltnw\n'), ((342, 370), 'numpy.square', 'np.square', (['(data - [0.5, 0.5])'], {}), '(data - [0.5, 0.5])\n', (351, 370), True, 'import numpy as np\n'), ((408, 436), 'numpy.square', 'np.square', (['(data - [0.5, 0.5])'], {}), '(data - [0.5, 0.5])\n', (417, 436), True, 'import numpy as np\n')]
|
"""
Module description:
"""
__version__ = '0.3.1'
__author__ = '<NAME>, <NAME>'
__email__ = '<EMAIL>, <EMAIL>'
import tensorflow as tf
import numpy as np
import random
class Sampler():
def __init__(self, indexed_ratings=None, m=None, num_users=None, num_items=None, transactions=None, batch_size=512, random_seed=42):
np.random.seed(random_seed)
random.seed(random_seed)
self._UIDICT = {u: list(set(indexed_ratings[u])) for u in indexed_ratings}
self._POS = list({(u, i, 1) for u, items in self._UIDICT.items() for i in items})
self._POS = random.sample(self._POS, len(self._POS))
self._M = m
self._NUM_USERS = num_users
self._NUM_ITEMS = num_items
self._transactions = transactions
self._batch_size = batch_size
def _full_generator(self):
r_int = np.random.randint
n_items = self._NUM_ITEMS
ui_dict = self._UIDICT
neg = set()
for u, i, _ in self._POS:
ui = ui_dict[u]
for _ in range(self._M):
j = r_int(n_items)
while j in ui:
j = r_int(n_items)
neg.add((u, j, 0))
samples = self._POS[:]
samples.extend(list(neg))
samples = random.sample(samples, len(samples))
# u, i, b = map(np.array, zip(*samples))
# yield u,i,b
for start in range(0, len(samples), self._batch_size):
u, i, b = map(np.array, zip(*samples[start:min(start + self._batch_size, len(samples))]))
yield u, i, b
def step(self, batch_size: int):
r_int = np.random.randint
n_items = self._NUM_ITEMS
ui_dict = self._UIDICT
pos = {(u, i, 1) for u, items in ui_dict.items() for i in items}
neg = set()
for u, i, _ in pos:
ui = ui_dict[u]
for _ in range(self._M):
j = r_int(n_items)
while j in ui:
j = r_int(n_items)
neg.add((u, j, 0))
samples = list(pos)
samples.extend(list(neg))
samples = random.sample(samples, len(samples))
for start in range(0, len(samples), batch_size):
u, i, b = map(np.array, zip(*samples[start:min(start + batch_size, len(samples))]))
yield u, i, b
def create_tf_dataset(self):
data = tf.data.Dataset.from_generator(generator=self._full_generator,
output_types=(np.int64, np.int64, np.int64),
)
# data = data.unbatch().batch(batch_size=self._batch_size)
data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
return data
|
[
"tensorflow.data.Dataset.from_generator",
"numpy.random.seed",
"random.seed"
] |
[((333, 360), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (347, 360), True, 'import numpy as np\n'), ((369, 393), 'random.seed', 'random.seed', (['random_seed'], {}), '(random_seed)\n', (380, 393), False, 'import random\n'), ((2386, 2498), 'tensorflow.data.Dataset.from_generator', 'tf.data.Dataset.from_generator', ([], {'generator': 'self._full_generator', 'output_types': '(np.int64, np.int64, np.int64)'}), '(generator=self._full_generator, output_types\n =(np.int64, np.int64, np.int64))\n', (2416, 2498), True, 'import tensorflow as tf\n')]
|
import os
import sys
import requests
import logging
import time
import json
import pandas as pd
import numpy as np
from concurrent.futures import ProcessPoolExecutor
from git import Git
class FPL_Gameweek:
""" Get the Gameweek state """
def __init__(self, logger, season_data):
"""
Args:
logger (logging.Logger): Logging pacakge
season_data (int): Season year
"""
self.season = season_data['season']
self.root = f'data/fpl_official/{self.season}-{self.season % 2000 + 1}/gameweek/'
if not os.path.exists(self.root):
os.makedirs(self.root)
self.current_gw, self.players = self.get_fpl_metadata()
self.players.to_csv(os.path.join(self.root, 'player_ids.csv'))
self.logger = logger
def get_fpl_metadata(self):
""" Request the FPL API
Returns:
(tuple): Next GW and player ids
"""
url = 'https://fantasy.premierleague.com/api/bootstrap-static/'
res = requests.get(url).json()
# Get current gameweek
current_gw = self.get_current_gw(res['events'])
if not os.path.exists(os.path.join(self.root, f'{current_gw}')):
os.mkdir(os.path.join(self.root, f'{current_gw}'))
# Get player ids
cols = ["id", "first_name", "second_name", "team"]
players = pd.DataFrame(res['elements'])[cols]
players = players.set_index("id")
return current_gw, players
def get_current_gw(self, events):
""" Get the next gameweek to be played in the EPL
Args:
events (json): FPL API response
Returns:
(int): Next gameweek
"""
for idx, gw in enumerate(events):
if gw['is_current']:
return idx + 1
def sample_ranks(self):
"""Sample every rank to get metadata"""
# Data management
transfer_strategy = self.players.copy()
transfer_strategy.loc[:, [
'Top_100_in', 'Top_1K_in', 'Top_10K_in', 'Top_50K_in',
'Top_100K_in', 'Top_250K_in', 'Top_500K_in', 'Top_100_out',
'Top_1K_out', 'Top_10K_out', 'Top_50K_out', 'Top_100K_out',
'Top_250K_out', 'Top_500K_out']] = 0
self.players.loc[:, [
'Top_100', 'Top_1K', 'Top_10K', 'Top_50K', 'Top_100K',
'Top_250K', 'Top_500K']] = 0
captain = self.players.copy()
chip_strategy = pd.DataFrame(index=[
'wildcard', 'freehit', 'bboost', '3xc'])
chip_strategy.loc[:, [
'Top_100', 'Top_1K', 'Top_10K', 'Top_50K',
'Top_100K', 'Top_250K', 'Top_500K']] = 0
hit_strategy = pd.DataFrame(index=['transfers'])
hit_strategy.loc[:, [
'Top_100', 'Top_1K', 'Top_10K', 'Top_50K',
'Top_100K', 'Top_250K', 'Top_500K']] = 0
# Sample ~10% of players teams
range_limits = [
('Top_100', 0, 100, 75),
('Top_1K', 100, 1000, 500),
('Top_10K', 1000, 10000, 2000),
('Top_50K', 10000, 50000, 4000),
('Top_100K', 50000, 100000, 5000),
('Top_250K', 100000, 250000, 15000),
('Top_500K', 250000, 500000, 25000)
]
for col, min_rank, max_rank, n_samples in range_limits:
self.logger.info(f"Starting to scrape {col} ranks")
fpl_ranks = np.random.randint(min_rank, max_rank, n_samples)
# Concurrent API Requests
with ProcessPoolExecutor(max_workers=8) as executor:
team_data = list(
executor.map(self.get_fpl_strategy, fpl_ranks))
for team, cap, chip, transfer in team_data:
# Ownership
for p in team:
self.players.loc[p, col] += 1
if cap is not None and len(cap):
captain.loc[cap[0], col] += 1
# Chip strategy
if chip is not None:
chip_strategy.loc[chip, col] += 1
# Transfer strategy
if transfer is not None and len(transfer):
transfer_in, transfer_out = transfer
for p_in, p_out in zip(transfer_in, transfer_out):
transfer_strategy.loc[p_in, col+'_in'] += 1
transfer_strategy.loc[p_out, col+'_out'] += 1
hit_strategy.loc['transfers', col] += len(transfer_in)
self.players.loc[:, col] = (
self.players.loc[:, col] / n_samples * 100)
captain.loc[:, col] = captain.loc[:, col] / n_samples * 100
chip_strategy.loc[:, col] = (
chip_strategy.loc[:, col] / n_samples * 100)
hit_strategy.loc[:, col] = hit_strategy.loc[:, col] / n_samples
transfer_strategy.loc[:, col+'_in'] = (
transfer_strategy.loc[:, col + '_in'] / n_samples * 100)
transfer_strategy.loc[:, col+'_out'] = (
transfer_strategy.loc[:, col + '_out'] / n_samples * 100)
self.players.to_csv(
os.path.join(self.root, f"{self.current_gw}/player_ownership.csv"))
captain.to_csv(
os.path.join(self.root, f"{self.current_gw}/captain.csv"))
chip_strategy.to_csv(
os.path.join(self.root, f"{self.current_gw}/chip_strategy.csv"))
hit_strategy.to_csv(
os.path.join(self.root, f"{self.current_gw}/hit_strategy.csv"))
transfer_strategy.to_csv(
os.path.join(self.root, f"{self.current_gw}/transfer_strategy.csv"))
def get_fpl_teamid(self, rank):
""" Get the FPL Team ID based on the rank
Args:
rank (int): Manager rank
Returns:
int: FPL Team ID
"""
# Scrape the correct page
page = rank // 50 + 1
place = rank % 50
url = f'https://fantasy.premierleague.com/api/leagues-classic/314/standings/?page_standings={page}'
res = requests.get(url)
return res.json()['standings']['results'][place]['entry']
def get_fpl_team(self, team_id):
""" Get the ids of player in a team
Args:
team_id (int): FPL Team ID
Returns:
(list): FPL Player IDs of the players selected
"""
res = requests.get(
f'https://fantasy.premierleague.com/api/entry/{team_id}/event/{self.current_gw}/picks/'
).json()
return (
[i['element'] for i in res['picks']],
[i['element'] for i in res['picks'] if i['multiplier'] > 1])
def get_fpl_strategy(self, rank):
""" Scrape FPL manager metadata
Args:
rank (int): FPL rank
Returns:
(tuple): strategy
"""
attempts = 3
while attempts:
try:
team_id = self.get_fpl_teamid(rank)
fpl_team, fpl_cap = self.get_fpl_team(team_id)
fpl_chips = self.get_fpl_chips(team_id)
fpl_transfers = self.get_fpl_transfers(team_id)
return fpl_team, fpl_cap, fpl_chips, fpl_transfers
except:
attempts -= 1
if not attempts:
self.logger.warning(
f"API Call to rank {rank} failed after 3 attempts.")
return [], [], [], []
self.logger.warning(
f'API Call failed, retrying in 3 seconds! Rank: {rank}')
time.sleep(3)
def get_fpl_chips(self, team_id):
""" Get the GW when a manager used a chip
Args:
team_id (int): Manager id
Returns:
(int): Gameweek
"""
res = requests.get(
f'https://fantasy.premierleague.com/api/entry/{team_id}/history/'
).json()['chips']
if res == []:
return None
if res[-1]['event'] == self.current_gw:
return res[-1]['name']
else:
return None
def get_fpl_transfers(self, team_id):
""" Get the transfer managers did
Args:
team_id (int): Manager id
Returns:
(tuple): FPL player ids
"""
res = requests.get(
f'https://fantasy.premierleague.com/api/entry/{team_id}/transfers'
).json()
transfer_in = []
transfer_out = []
for transfers in res:
if transfers['event'] == self.current_gw:
transfer_in.append(transfers['element_in'])
transfer_out.append(transfers['element_out'])
else:
return transfer_in, transfer_out
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(message)s")
logger: logging.Logger = logging.getLogger(__name__)
with open('info.json') as f:
season_data = json.load(f)
fplg = FPL_Gameweek(logger, season_data)
fplg.sample_ranks()
if len(sys.argv) > 1:
logger.info("Saving data ...")
Git()
else:
print("Local")
|
[
"logging.basicConfig",
"logging.getLogger",
"os.path.exists",
"pandas.DataFrame",
"os.makedirs",
"git.Git",
"os.path.join",
"requests.get",
"time.sleep",
"numpy.random.randint",
"concurrent.futures.ProcessPoolExecutor",
"json.load"
] |
[((8774, 8849), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(asctime)s - %(message)s"""'}), "(level=logging.INFO, format='%(asctime)s - %(message)s')\n", (8793, 8849), False, 'import logging\n'), ((8879, 8906), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (8896, 8906), False, 'import logging\n'), ((2466, 2526), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': "['wildcard', 'freehit', 'bboost', '3xc']"}), "(index=['wildcard', 'freehit', 'bboost', '3xc'])\n", (2478, 2526), True, 'import pandas as pd\n'), ((2702, 2735), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': "['transfers']"}), "(index=['transfers'])\n", (2714, 2735), True, 'import pandas as pd\n'), ((6042, 6059), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (6054, 6059), False, 'import requests\n'), ((8963, 8975), 'json.load', 'json.load', (['f'], {}), '(f)\n', (8972, 8975), False, 'import json\n'), ((9120, 9125), 'git.Git', 'Git', ([], {}), '()\n', (9123, 9125), False, 'from git import Git\n'), ((576, 601), 'os.path.exists', 'os.path.exists', (['self.root'], {}), '(self.root)\n', (590, 601), False, 'import os\n'), ((615, 637), 'os.makedirs', 'os.makedirs', (['self.root'], {}), '(self.root)\n', (626, 637), False, 'import os\n'), ((731, 772), 'os.path.join', 'os.path.join', (['self.root', '"""player_ids.csv"""'], {}), "(self.root, 'player_ids.csv')\n", (743, 772), False, 'import os\n'), ((1381, 1410), 'pandas.DataFrame', 'pd.DataFrame', (["res['elements']"], {}), "(res['elements'])\n", (1393, 1410), True, 'import pandas as pd\n'), ((3416, 3464), 'numpy.random.randint', 'np.random.randint', (['min_rank', 'max_rank', 'n_samples'], {}), '(min_rank, max_rank, n_samples)\n', (3433, 3464), True, 'import numpy as np\n'), ((5142, 5208), 'os.path.join', 'os.path.join', (['self.root', 'f"""{self.current_gw}/player_ownership.csv"""'], {}), "(self.root, f'{self.current_gw}/player_ownership.csv')\n", (5154, 5208), False, 'import os\n'), ((5246, 5303), 'os.path.join', 'os.path.join', (['self.root', 'f"""{self.current_gw}/captain.csv"""'], {}), "(self.root, f'{self.current_gw}/captain.csv')\n", (5258, 5303), False, 'import os\n'), ((5347, 5410), 'os.path.join', 'os.path.join', (['self.root', 'f"""{self.current_gw}/chip_strategy.csv"""'], {}), "(self.root, f'{self.current_gw}/chip_strategy.csv')\n", (5359, 5410), False, 'import os\n'), ((5453, 5515), 'os.path.join', 'os.path.join', (['self.root', 'f"""{self.current_gw}/hit_strategy.csv"""'], {}), "(self.root, f'{self.current_gw}/hit_strategy.csv')\n", (5465, 5515), False, 'import os\n'), ((5563, 5630), 'os.path.join', 'os.path.join', (['self.root', 'f"""{self.current_gw}/transfer_strategy.csv"""'], {}), "(self.root, f'{self.current_gw}/transfer_strategy.csv')\n", (5575, 5630), False, 'import os\n'), ((1029, 1046), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1041, 1046), False, 'import requests\n'), ((1172, 1212), 'os.path.join', 'os.path.join', (['self.root', 'f"""{current_gw}"""'], {}), "(self.root, f'{current_gw}')\n", (1184, 1212), False, 'import os\n'), ((1236, 1276), 'os.path.join', 'os.path.join', (['self.root', 'f"""{current_gw}"""'], {}), "(self.root, f'{current_gw}')\n", (1248, 1276), False, 'import os\n'), ((3521, 3555), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': '(8)'}), '(max_workers=8)\n', (3540, 3555), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((6365, 6476), 'requests.get', 'requests.get', (['f"""https://fantasy.premierleague.com/api/entry/{team_id}/event/{self.current_gw}/picks/"""'], {}), "(\n f'https://fantasy.premierleague.com/api/entry/{team_id}/event/{self.current_gw}/picks/'\n )\n", (6377, 6476), False, 'import requests\n'), ((8301, 8386), 'requests.get', 'requests.get', (['f"""https://fantasy.premierleague.com/api/entry/{team_id}/transfers"""'], {}), "(f'https://fantasy.premierleague.com/api/entry/{team_id}/transfers'\n )\n", (8313, 8386), False, 'import requests\n'), ((7565, 7578), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (7575, 7578), False, 'import time\n'), ((7793, 7872), 'requests.get', 'requests.get', (['f"""https://fantasy.premierleague.com/api/entry/{team_id}/history/"""'], {}), "(f'https://fantasy.premierleague.com/api/entry/{team_id}/history/')\n", (7805, 7872), False, 'import requests\n')]
|
from ..function.node import *
from ..function.tree import *
import numpy as np
def generate_tree(name='test'):
p_branch = .2
p_infertile = .1
p_channel = 1 - p_branch - p_infertile
decay = .25
branch_nodes = [Max, Sum, Mean, Min, Product, Median]
infertile_nodes = [Constant, Input, Uniform, Normal]
channel_node = [Square, Reciprocal, Sqrt, Exp, Sin, Cos, ArcTan, Abs, Sign]
max_node_count = 10
max_num_branches = 3
max_size_branch = 3
branch_disribution = np.random.randint
tree = FunctionTree(name=name)
stack = [tree.Output.name]
c_node = tree.Input.name
branch_count = 0
nodes_count = 0
while len(stack) > 0:
p_node = stack.pop(0)
if branch_count > max_num_branches:
p_infertile += p_branch/2
p_channel += p_branch/2
p_branch = 0
print(p_infertile, p_channel, p_branch)
elif nodes_count > max_node_count - branch_count*(max_size_branch/2 -1):
decay_amount = p_channel*decay
p_channel -= decay_amount
p_infertile += decay_amount
elif nodes_count > 2* max_node_count:
p_channel = 0
p_infertile = 1
new_node_type = np.random.choice(['branch', 'infertile', 'channel'], p=[p_branch, p_infertile, p_channel])
if new_node_type == 'branch':
new_node = np.random.choice(branch_nodes)
num_nodes = branch_disribution(2, max_size_branch+1)
branch_count += 1
elif new_node_type == 'infertile':
new_node = np.random.choice(infertile_nodes)
num_nodes = 1
else:
new_node = np.random.choice(channel_node)
num_nodes = 1
new_node = new_node(name=str(nodes_count))
print('Node to be added: ', new_node.latex, new_node.name)
try:
if new_node_type == 'infertile':
tree.insert(new_node, parent_item=p_node)
else:
tree.insert(new_node, parent_item=p_node, child_item=c_node)
print('Tree Map')
print(tree.tree_map)
nodes_count += num_nodes
if new_node_type != 'infertile':
for _ in range(num_nodes):
stack.append(new_node.name)
except:
stack.insert(0, p_node)
return tree
class FunctionGenerator:
"""Generator of FunctionTrees
# Arguments:
base_cohert_name: A String, used as the base of naming new Trees
Ex: A = FunctionGenerator(base_cohert_name = 'test')
next(A) --> FunctionTree Object with name 'test_1'
next(A) --> FunctionTree Object with name 'test_2'
...
max_nodes: An Integer, maximum number of nodes in a graph
max_branches: An Integer, maximum number of branch type function
nodes in a graph
node_type_probability: A dictionary, representing a discrete node distribution
Ex: {'channel': 1/3, 'infertile': 1/3, 'branch': 1/3}
node_probability: A numpy distribution,
channel_nodes: A dictionary with FunctionNodes, used as the key,
and "probability" of selecting that node when a channel node is needed
infertile_nodes: A dictionary with FunctionNodes, used as the key,
and "probability" of selecting that node when a infertile node is needed
branch_nodes: A dictionary with FunctionNodes, used as the key,
and "probability" of selecting that node when a branch node is needed
# Returns (When called)
FunctionTree,
Logic:
Breadth first creation!
Determine_number of nodes
Determine how many branch and infertile nodes
"""
pass
|
[
"numpy.random.choice"
] |
[((1244, 1338), 'numpy.random.choice', 'np.random.choice', (["['branch', 'infertile', 'channel']"], {'p': '[p_branch, p_infertile, p_channel]'}), "(['branch', 'infertile', 'channel'], p=[p_branch,\n p_infertile, p_channel])\n", (1260, 1338), True, 'import numpy as np\n'), ((1396, 1426), 'numpy.random.choice', 'np.random.choice', (['branch_nodes'], {}), '(branch_nodes)\n', (1412, 1426), True, 'import numpy as np\n'), ((1589, 1622), 'numpy.random.choice', 'np.random.choice', (['infertile_nodes'], {}), '(infertile_nodes)\n', (1605, 1622), True, 'import numpy as np\n'), ((1686, 1716), 'numpy.random.choice', 'np.random.choice', (['channel_node'], {}), '(channel_node)\n', (1702, 1716), True, 'import numpy as np\n')]
|
import numpy as np
import math
class virtual_factory(object):
def __init__(self, blade_specs , operation, gating_ct, non_gating_ct, options):
self.options = options
# Blade inputs
self.n_webs = blade_specs['n_webs']
# Financial parameters
self.wage = 20. # [$] Wage of an unskilled worker
self.beni = 30.4 # [%] Benefits on wage and salary
self.overhead = 30. # [%] Labor overhead
self.crr = 10. # [%] Capital recovery rate
self.wcp = 3. # [month] Working capital period - amount of time it takes to turn the net current assets and current liabilities into cash
self.p_life = 1 # [yr] Length of production run
self.rejr = 0.25 # [%] Part reject rate per process
# Productive lives
self.building_life = 30. # [yr] Building recovery life
self.eq_life = 10. # [yr] Equipment recovery life
self.tool_life = 4. # [yr] Productive tool life
# Factory parameters
self.n_blades = 1000 # [-] Number of blades that the factory aims at manufacturing
self.install_cost = 10. # [%] Installation costs
self.price_space = 800. # [$/m2] Price of building space
self.maintenance_cost = 4. # [%] Maintenance costs
self.electr = 0.08 # [$/kWh] Price of electricity
self.hours = 24. # [hr] Working hours per day
self.days = 250. # [day] Working days per year
self.avg_dt = 20. # [%] Average downtime for workers and equipment
# Compute cumulative rejection rate
self.cum_rejr = np.zeros(len(operation)) # [%]
self.cum_rejr[-1] = 1. - (1. - (self.rejr / 100.))
for i_op in range(1, len(operation)):
self.cum_rejr[-i_op-1] = 1. - (1. - (self.rejr / 100)) * (1. - self.cum_rejr[-i_op])
# Calculate the number of sets of lp and hp skin molds needed
if self.options['discrete']:
self.n_set_molds_skins = np.ceil(self.n_blades * sum(gating_ct) / (1 - self.cum_rejr[5 + self.n_webs]) / (self.hours * self.days)) # [-] Number of skin mold sets (low and high pressure)
else:
self.n_set_molds_skins = self.n_blades * sum(gating_ct) / (1 - self.cum_rejr[5 + self.n_webs]) / (self.hours * self.days) # [-] Number of skin mold sets (low and high pressure)
# Number of parallel processes
self.parallel_proc = np.ones(len(operation)) # [-]
if self.options['discrete']:
for i_op in range(0, len(operation)):
self.parallel_proc[i_op] = np.ceil(self.n_set_molds_skins * non_gating_ct[i_op] / sum(gating_ct) / (1 - self.cum_rejr[i_op]))
n_molds_root = 2 * self.n_set_molds_skins * non_gating_ct[1] / sum(gating_ct) / (1 - self.cum_rejr[1])
if n_molds_root < 1:
self.parallel_proc[2] = 0
else:
self.parallel_proc[1] = np.ceil(self.n_set_molds_skins * non_gating_ct[ 1] / sum(gating_ct) / (1 - self.cum_rejr[1]))
self.parallel_proc[2] = np.ceil(self.n_set_molds_skins * non_gating_ct[ 2] / sum(gating_ct) / (1 - self.cum_rejr[2]))
for i_web in range(self.n_webs):
self.parallel_proc[3 + i_web] = np.ceil(2 * self.n_set_molds_skins * non_gating_ct[3 + i_web] / sum(gating_ct) / (1 - self.cum_rejr[3 + i_web]))
else:
for i_op in range(0, len(operation)):
self.parallel_proc[i_op] = self.n_set_molds_skins * non_gating_ct[i_op] / sum(gating_ct) / (1 - self.cum_rejr[i_op])
n_molds_root = 2 * self.n_set_molds_skins * non_gating_ct[1] / sum(gating_ct) / (1 - self.cum_rejr[1])
if n_molds_root < 1:
self.parallel_proc[2] = 0
else:
self.parallel_proc[1] = self.n_set_molds_skins * non_gating_ct[ 1] / sum(gating_ct) / (1 - self.cum_rejr[1])
self.parallel_proc[2] = self.n_set_molds_skins * non_gating_ct[ 2] / sum(gating_ct) / (1 - self.cum_rejr[2])
for i_web in range(self.n_webs):
self.parallel_proc[3 + i_web] = 2 * self.n_set_molds_skins * non_gating_ct[3 + i_web] / sum(gating_ct) / (1 - self.cum_rejr[3 + i_web])
self.parallel_proc[5 + self.n_webs] = self.n_set_molds_skins
self.parallel_proc[6 + self.n_webs] = self.n_set_molds_skins
self.parallel_proc[7 + self.n_webs] = self.n_set_molds_skins
self.parallel_proc[8 + self.n_webs] = self.n_set_molds_skins
# Building space per operation
delta = 2. #[m] Distance between blades
self.floor_space = np.zeros(len(operation)) # [m2]
self.floor_space[0] = 3. * blade_specs['blade_length'] # [m2] Material cutting
self.floor_space[1] = self.parallel_proc[ 1] * (delta + blade_specs['root_D']) * (delta + blade_specs['root_preform_length']) # [m2] Infusion root preform lp
self.floor_space[2] = self.parallel_proc[ 2] * (delta + blade_specs['root_D']) * (delta + blade_specs['root_preform_length']) # [m2] Infusion root preform hp
for i_web in range(self.n_webs):
self.floor_space[3 + i_web] = self.parallel_proc[ 3 + i_web] * (delta + blade_specs['length_webs'][i_web]) * (delta + blade_specs['height_webs_start'][i_web]) # [m2] Infusion webs
self.floor_space[3 + self.n_webs] = self.parallel_proc[ 3 + self.n_webs] * (delta + blade_specs['length_sc_lp']) * (delta + blade_specs['width_sc_start_lp']) # [m2] Infusion spar caps
self.floor_space[4 + self.n_webs] = self.parallel_proc[ 4 + self.n_webs] * (delta + blade_specs['length_sc_hp']) * (delta + blade_specs['width_sc_start_hp']) # [m2] Infusion spar caps
self.floor_space[5 + self.n_webs] = self.parallel_proc[ 5 + self.n_webs] * (blade_specs['max_chord'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Infusion skin shell lp
self.floor_space[6 + self.n_webs] = self.parallel_proc[ 6 + self.n_webs] * (blade_specs['max_chord'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Infusion skin shell hp
self.floor_space[9 + self.n_webs] = self.parallel_proc[ 9 + self.n_webs] * (blade_specs['max_chord'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Trim
self.floor_space[10 + self.n_webs] = self.parallel_proc[10 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Overlay
self.floor_space[11 + self.n_webs] = self.parallel_proc[11 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Post cure
self.floor_space[12 + self.n_webs] = self.parallel_proc[12 + self.n_webs] * (blade_specs['max_chord'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Root cut and drill
self.floor_space[13 + self.n_webs] = self.parallel_proc[13 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Root hardware install
self.floor_space[14 + self.n_webs] = self.parallel_proc[14 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Surface preparation
self.floor_space[15 + self.n_webs] = self.parallel_proc[15 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Paint
self.floor_space[16 + self.n_webs] = self.parallel_proc[16 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Surface inspection and finish
self.floor_space[17 + self.n_webs] = self.parallel_proc[17 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Weight and balance
self.floor_space[18 + self.n_webs] = self.parallel_proc[18 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Inspection
self.floor_space[19 + self.n_webs] = self.parallel_proc[19 + self.n_webs] * (blade_specs['root_D'] + delta) * (blade_specs['blade_length'] + delta) # [m2] Shipping preparation
# Average power consumption during each operation
Cp = 1.01812 # [kJ/kg/K] Kalogiannakis et. al 2003
Tcure = 70 # [C]
Tamb = 22 # [C]
OvenCycle = 7 # [hr]
EtaOven = 0.5 # [-]
kJ_per_kg = Cp * (Tcure-Tamb) / (OvenCycle * 3600) / EtaOven
self.power_consumpt = self.floor_space * 250 / self.hours / self.days # [kW] 80000 btu / sq ft
self.power_consumpt[1] = self.power_consumpt[1] + self.parallel_proc[ 1] * blade_specs['mass_root_preform_lp'] * kJ_per_kg # [kW] Root preform lp
self.power_consumpt[2] = self.power_consumpt[2] + self.parallel_proc[ 2] * blade_specs['mass_root_preform_hp'] * kJ_per_kg # [kW] Root preform hp
for i_web in range(self.n_webs):
self.power_consumpt[3 + i_web] = self.power_consumpt[ 3 + i_web] + self.parallel_proc[3 + i_web] * blade_specs['mass_webs'][i_web] * kJ_per_kg # [kW] Root preform hp
self.power_consumpt[3 + self.n_webs] = self.power_consumpt[ 3 + self.n_webs] + self.parallel_proc[ 3 + self.n_webs] * blade_specs['mass_sc_lp'] * kJ_per_kg # [kW] Spar cap lp
self.power_consumpt[4 + self.n_webs] = self.power_consumpt[ 4 + self.n_webs] + self.parallel_proc[ 4 + self.n_webs] * blade_specs['mass_sc_hp'] * kJ_per_kg # [kW] Spar cap hp
self.power_consumpt[5 + self.n_webs] = self.power_consumpt[ 5 + self.n_webs] + self.parallel_proc[ 5 + self.n_webs] * (blade_specs['mass_shell_lp']) * kJ_per_kg # [kW] Shell lp
self.power_consumpt[6 + self.n_webs] = self.power_consumpt[ 6 + self.n_webs] + self.parallel_proc[ 6 + self.n_webs] * (blade_specs['mass_shell_hp']) * kJ_per_kg # [kW] Shell hp
self.power_consumpt[11 + self.n_webs] = self.power_consumpt[11 + self.n_webs] + self.parallel_proc[11 + self.n_webs] * blade_specs['blade_mass'] * kJ_per_kg # [kW] Post cure
# Tooling investment per station per operation (molds)
self.tooling_investment = np.zeros(len(operation)) # [$]
price_mold_sqm = 5000.
self.tooling_investment[1] = price_mold_sqm * self.parallel_proc[1] * blade_specs['area_lp_root'] # [$] Mold of the root preform - lp, cost assumed equal to 50000 $ per meter square of surface
self.tooling_investment[2] = price_mold_sqm * self.parallel_proc[2] * blade_specs['area_hp_root'] # [$] Mold of the root preform - hp, cost assumed equal to 50000 $ per meter square of surface
for i_web in range(self.n_webs):
self.tooling_investment[3 + i_web] = price_mold_sqm * self.parallel_proc[3 + i_web] * blade_specs['area_webs_w_flanges'][i_web] # [$] Mold of the webs, cost assumed equal to 10800 $ per meter square of surface
self.tooling_investment[3 + self.n_webs] = price_mold_sqm * self.parallel_proc[3 + self.n_webs] * blade_specs['area_sc_lp'] # [$] Mold of the low pressure spar cap, cost assumed equal to 10800 $ per meter square of surface
self.tooling_investment[4 + self.n_webs] = price_mold_sqm * self.parallel_proc[4 + self.n_webs] * blade_specs['area_sc_hp'] # [$] Mold of the high pressure spar cap, cost assumed equal to 10800 $ per meter square of surface
self.tooling_investment[5 + self.n_webs] = price_mold_sqm * self.parallel_proc[5 + self.n_webs] * blade_specs['area_lpskin_w_flanges'] # [$] Mold of the low pressure skin shell, assumed equal to 9400 $ per meter square of surface
self.tooling_investment[6 + self.n_webs] = price_mold_sqm * self.parallel_proc[6 + self.n_webs] * blade_specs['area_hpskin_w_flanges'] # [$] Mold of the low pressure skin shell, assumed equal to 9400 $ per meter square of surface
# Equipment investment per station per operation
self.equipm_investment = np.zeros(len(operation)) # [$]
self.equipm_investment[0] = 5000. * self.parallel_proc[ 0] * blade_specs['blade_length'] # [$] Equipment for material cutting is assumed at 5000 $ per meter of blade length
self.equipm_investment[1] = 15000. * self.parallel_proc[ 1] * blade_specs['root_D'] # [$] Equipment for root preform infusion is assumed at 15000 $ per meter of blade root diameter
self.equipm_investment[2] = 15000. * self.parallel_proc[ 2] * blade_specs['root_D'] # [$] Equipment for root preform infusion is assumed at 15000 $ per meter of blade root diameter
for i_web in range(self.n_webs):
self.equipm_investment[3 + i_web] = 1700. * self.parallel_proc[ 3 + i_web] * blade_specs['length_webs'][i_web] # [$] Equipment for webs infusion is assumed at 1700 $ per meter of web length
self.equipm_investment[3 + self.n_webs] = 1700. * self.parallel_proc[ 3 + self.n_webs] * blade_specs['length_sc_lp'] # [$] Equipment for spar caps infusion is assumed at 1700 $ per meter of spar cap length
self.equipm_investment[4 + self.n_webs] = 1700. * self.parallel_proc[ 4 + self.n_webs] * blade_specs['length_sc_hp'] # [$] Equipment for spar caps infusion is assumed at 1700 $ per meter of spar cap length
self.equipm_investment[5 + self.n_webs] = 1600. * self.parallel_proc[ 5 + self.n_webs] * blade_specs['skin_perimeter_wo_root']# [$] Equipment for skins infusion is assumed at 1600 $ per meter of skin perimeter
self.equipm_investment[6 + self.n_webs] = 1600. * self.parallel_proc[ 6 + self.n_webs] * blade_specs['skin_perimeter_wo_root']# [$] Equipment for skins infusion is assumed at 1600 $ per meter of skin perimeter
self.equipm_investment[7 + self.n_webs] = 6600. * self.parallel_proc[ 7 + self.n_webs] * sum(blade_specs['length_webs'])# [$] Equipment for assembly is assumed equal to 6600 $ per meter of total webs length
self.equipm_investment[9 + self.n_webs] = 25000. * self.parallel_proc[ 9 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for trim booth is assumed at 25000 $ per meter of blade length
self.equipm_investment[10 + self.n_webs] = 250. * self.parallel_proc[10 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for overlay is assumed at 250 $ per meter of blade length
self.equipm_investment[11 + self.n_webs] = 28500. * self.parallel_proc[11 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for post-cure is assumed at 28500 $ per meter of blade length
self.equipm_investment[12 + self.n_webs] = 390000. * self.parallel_proc[12 + self.n_webs] * blade_specs['root_D'] # [$] Equipment for root cut and drill is assumed at 390000 $ per meter of root diameter
self.equipm_investment[13 + self.n_webs] = 15500. * self.parallel_proc[13 + self.n_webs] * blade_specs['root_D'] # [$] Equipment for root hardware install is assumed at 15500 $ per meter of root diameter
self.equipm_investment[14 + self.n_webs] = 160. * self.parallel_proc[14 + self.n_webs] * (blade_specs['area_lpskin_wo_flanges'] + blade_specs['area_hpskin_wo_flanges']) # [$] Equipment for surface preparation is assumed at 160 $ per meter square of blade outer surface
self.equipm_investment[15 + self.n_webs] = 57000. * self.parallel_proc[15 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for paint booth is assumed at 57000 $ per meter of blade length
self.equipm_investment[16 + self.n_webs] = 800. * self.parallel_proc[16 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for surface inspection and finish is assumed at 800 $ per meter of blade length
self.equipm_investment[17 + self.n_webs] = 200000. * self.parallel_proc[17 + self.n_webs] # [$] Weight and Balance, assumed constant
self.equipm_investment[18 + self.n_webs] = 400. * self.parallel_proc[18 + self.n_webs] * blade_specs['blade_length'] # [$] Equipment for final inspection is assumed at 400 $ per meter of blade length
self.equipm_investment[19 + self.n_webs] = 8000. * self.parallel_proc[19 + self.n_webs] * blade_specs['root_D'] # [$] Equipment for shipping preparation is assumed at 8000 $ per meter of root diameter
def execute_direct_labor_cost(self ,operation, labor_hours):
if self.options['verbosity']:
verbosity = 1
else:
verbosity = 0
direct_labor_cost_per_blade = np.zeros(len(operation)) # [$]
direct_labor_cost_per_year = np.zeros(len(operation)) # [$]
if verbosity:
print('\n#################################\nDirect labor cost')
for i_op in range(0, len(operation)):
direct_labor_cost_per_blade[i_op] , direct_labor_cost_per_year[i_op] = compute_direct_labor_cost(self, labor_hours[i_op], operation[i_op], self.cum_rejr[i_op], verbosity)
total_direct_labor_cost_per_blade = sum(direct_labor_cost_per_blade)
total_direct_labor_cost_per_year = sum(direct_labor_cost_per_year)
total_labor_overhead_per_blade = total_direct_labor_cost_per_blade * (self.overhead / 100.)
return total_direct_labor_cost_per_blade , total_labor_overhead_per_blade
def execute_utility_cost(self, operation, ct):
if self.options['verbosity']:
verbosity = 1
else:
verbosity = 0
utility_cost_per_blade = np.zeros(len(operation)) # [$]
utility_cost_per_year = np.zeros(len(operation)) # [$]
if verbosity:
print('\n#################################\nUtility cost')
for i_op in range(0, len(operation)):
utility_cost_per_blade[i_op] , utility_cost_per_year[i_op] = compute_utility_cost(self, ct[i_op], self.power_consumpt[i_op], operation[i_op], self.cum_rejr[i_op], verbosity)
total_utility_cost_per_blade = sum(utility_cost_per_blade)
total_utility_labor_cost_per_year = sum(utility_cost_per_year)
return total_utility_cost_per_blade
def execute_fixed_cost(self, operation, ct, blade_variable_cost_w_overhead):
if self.options['verbosity']:
verbosity = 1
else:
verbosity = 0
building_cost_per_blade = np.zeros(len(operation)) # [$]
building_cost_per_year = np.zeros(len(operation)) # [$]
building_annuity = np.zeros(len(operation)) # [$]
tooling_cost_per_blade = np.zeros(len(operation)) # [$]
tooling_cost_per_year = np.zeros(len(operation)) # [$]
tooling_annuity = np.zeros(len(operation)) # [$]
equipment_cost_per_blade = np.zeros(len(operation)) # [$]
equipment_cost_per_year = np.zeros(len(operation)) # [$]
equipment_annuity = np.zeros(len(operation)) # [$]
maintenance_cost_per_blade = np.zeros(len(operation)) # [$]
maintenance_cost_per_year = np.zeros(len(operation)) # [$]
if self.options['verbosity']:
print('\n#################################\nFixed cost')
for i_op in range(0, len(operation)):
if verbosity:
print('\nBuilding:')
building_investment = self.floor_space[i_op] * self.price_space
investment_bu = building_investment * self.parallel_proc[i_op]
building_cost_per_blade[i_op], building_cost_per_year[i_op], building_annuity[i_op] = compute_cost_annuity(self, operation[i_op], investment_bu, self.building_life, verbosity)
if verbosity:
print('\nTooling:')
investment_to = self.tooling_investment[i_op] * self.parallel_proc[i_op]
tooling_cost_per_blade[i_op], tooling_cost_per_year[i_op], tooling_annuity[i_op] = compute_cost_annuity(self, operation[i_op], investment_to, self.tool_life, verbosity)
if verbosity:
print('\nEquipment:')
investment_eq = self.equipm_investment[i_op] * self.parallel_proc[i_op]
equipment_cost_per_blade[i_op], equipment_cost_per_year[i_op], equipment_annuity[i_op] = compute_cost_annuity(self, operation[i_op], investment_eq, self.eq_life, verbosity)
if verbosity:
print('\nMaintenance:')
maintenance_cost_per_blade[i_op], maintenance_cost_per_year[i_op] = compute_maintenance_cost(self, operation[i_op], investment_eq, investment_to, investment_bu, verbosity)
# Sums across operations
total_building_labor_cost_per_year = sum(building_cost_per_year)
total_building_cost_per_blade = sum(building_cost_per_blade)
total_tooling_labor_cost_per_year = sum(tooling_cost_per_year)
total_tooling_cost_per_blade = sum(tooling_cost_per_blade)
total_equipment_labor_cost_per_year = sum(equipment_cost_per_year)
total_equipment_cost_per_blade = sum(equipment_cost_per_blade)
total_maintenance_labor_cost_per_year = sum(maintenance_cost_per_year)
total_maintenance_cost_per_blade = sum(maintenance_cost_per_blade)
# Annuity
equipment_annuity_tot = sum(equipment_annuity)
tooling_annuity_tot = sum(tooling_annuity)
building_annuity_tot = sum(building_annuity)
working_annuity = np.pmt(self.crr /100. / 12. , self.wcp, -(self.wcp / 12. * (total_maintenance_labor_cost_per_year + blade_variable_cost_w_overhead * self.n_blades))) * 12.
annuity_tot_per_year = equipment_annuity_tot + tooling_annuity_tot + building_annuity_tot + working_annuity
cost_of_capital_per_year = annuity_tot_per_year - (blade_variable_cost_w_overhead * self.n_blades + total_equipment_labor_cost_per_year + total_tooling_labor_cost_per_year + total_building_labor_cost_per_year + total_maintenance_labor_cost_per_year)
cost_of_capital_per_blade = cost_of_capital_per_year / self.n_blades
return total_equipment_cost_per_blade, total_tooling_cost_per_blade, total_building_cost_per_blade, total_maintenance_cost_per_blade, cost_of_capital_per_blade
def compute_direct_labor_cost(self, labor_hours, operation, cum_rejr, verbosity):
cost_per_blade = (self.wage * (1. + self.beni / 100.) * labor_hours) / (1. - self.avg_dt / 100.)/(1. - cum_rejr)
cost_per_year = cost_per_blade * self.n_blades
if verbosity == 1:
print('Activity: ' + operation)
print('per blade: {:8.2f} $ \t \t --- \t \t per year: {:8.2f} $'.format(float(cost_per_blade),float(cost_per_year)))
return cost_per_blade , cost_per_year
def compute_utility_cost(self, ct, power_consumpt, operation, cum_rejr, verbosity):
cost_per_blade = (self.electr * power_consumpt * ct) / (1. - self.avg_dt / 100.)/(1. - cum_rejr)
cost_per_year = cost_per_blade * self.n_blades
if verbosity == 1:
print('Activity: ' + operation)
print('per blade: {:8.2f} $ \t \t --- \t \t per year: {:8.2f} $'.format(float(cost_per_blade),float(cost_per_year)))
return cost_per_blade , cost_per_year
def compute_cost_annuity(self, operation, investment, life, verbosity):
cost_per_year = investment / life
cost_per_blade = cost_per_year / self.n_blades
annuity = np.pmt(self.crr / 100. / 12. , life * 12., -investment) * 12.
if verbosity == 1:
print('Activity: ' + operation)
print('per blade: {:8.2f} $ \t \t --- \t \t per year: {:8.2f} $ \t \t --- \t \t annuity: {:8.2f} $'.format(float(cost_per_blade),float(cost_per_year),float(annuity)))
return cost_per_blade , cost_per_year, annuity
def compute_maintenance_cost(self, operation, investment_eq, investment_to, investment_bu, verbosity):
cost_per_year = self.maintenance_cost / 100. * (investment_eq + investment_to + investment_bu)
cost_per_blade = cost_per_year / self.n_blades
if verbosity == 1:
print('Activity: ' + operation)
print('per blade: {:8.2f} $ \t \t --- \t \t per year: {:8.2f} $'.format(float(cost_per_blade),float(cost_per_year)))
return cost_per_blade , cost_per_year
|
[
"numpy.pmt"
] |
[((26268, 26325), 'numpy.pmt', 'np.pmt', (['(self.crr / 100.0 / 12.0)', '(life * 12.0)', '(-investment)'], {}), '(self.crr / 100.0 / 12.0, life * 12.0, -investment)\n', (26274, 26325), True, 'import numpy as np\n'), ((24092, 24253), 'numpy.pmt', 'np.pmt', (['(self.crr / 100.0 / 12.0)', 'self.wcp', '(-(self.wcp / 12.0 * (total_maintenance_labor_cost_per_year + \n blade_variable_cost_w_overhead * self.n_blades)))'], {}), '(self.crr / 100.0 / 12.0, self.wcp, -(self.wcp / 12.0 * (\n total_maintenance_labor_cost_per_year + blade_variable_cost_w_overhead *\n self.n_blades)))\n', (24098, 24253), True, 'import numpy as np\n')]
|
import numpy as np
import pickle as pkl
from envs.babyai.oracle.teacher import Teacher
class XYCorrections(Teacher):
def __init__(self, *args, **kwargs):
super(XYCorrections, self).__init__(*args, **kwargs)
self.next_state_coords = self.empty_feedback()
def empty_feedback(self):
"""
Return a tensor corresponding to no feedback.
"""
return np.zeros(8) - 1
def random_feedback(self):
"""
Return a tensor corresponding to no feedback.
"""
return np.random.uniform(0, 1, size=8)
def compute_feedback(self, oracle, last_action=-1):
"""
Return the expert action from the previous timestep.
"""
# Copy so we don't mess up the state of the real oracle
oracle_copy = pkl.loads(pkl.dumps(oracle))
self.step_ahead(oracle_copy, last_action=last_action)
return np.concatenate([self.next_state_coords])
# TODO: THIS IS NO IMPLEMENTED FOR THIS TEACHER! IF WE END UP USING THIS METRIC, WE SHOULD MAKE IT CORRECT!
def success_check(self, state, action, oracle):
return True
def step_ahead(self, oracle, last_action=-1):
env = oracle.mission
# Remove teacher so we don't end up with a recursion error
env.teacher = None
try:
curr_coords = np.concatenate([env.agent_pos, [env.agent_dir, int(env.carrying is not None)]]).astype(
np.float32)
self.next_state, next_state_coords, _, _ = self.step_away_state(oracle, self.cartesian_steps,
last_action=last_action)
# Coords are quite large, so normalize them to between [-1, 1]
self.next_state_coords = next_state_coords.astype(np.float32)
self.next_state_coords[:2] = (self.next_state_coords[:2].astype(np.float32) - 12) / 12
curr_coords[:2] = (curr_coords[:2] - 12) / 6
self.next_state_coords = np.concatenate([self.next_state_coords, curr_coords])
# Also normalize direction
self.next_state_coords[2] = self.next_state_coords[2] - 2
self.next_state_coords[6] = self.next_state_coords[6] - 2
except Exception as e:
print("STEP AWAY FAILED XY!", e)
self.next_state = self.next_state * 0
self.next_state_coords = self.empty_feedback()
self.last_step_error = True
return oracle
|
[
"pickle.dumps",
"numpy.zeros",
"numpy.concatenate",
"numpy.random.uniform"
] |
[((541, 572), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '(8)'}), '(0, 1, size=8)\n', (558, 572), True, 'import numpy as np\n'), ((907, 947), 'numpy.concatenate', 'np.concatenate', (['[self.next_state_coords]'], {}), '([self.next_state_coords])\n', (921, 947), True, 'import numpy as np\n'), ((400, 411), 'numpy.zeros', 'np.zeros', (['(8)'], {}), '(8)\n', (408, 411), True, 'import numpy as np\n'), ((811, 828), 'pickle.dumps', 'pkl.dumps', (['oracle'], {}), '(oracle)\n', (820, 828), True, 'import pickle as pkl\n'), ((2011, 2064), 'numpy.concatenate', 'np.concatenate', (['[self.next_state_coords, curr_coords]'], {}), '([self.next_state_coords, curr_coords])\n', (2025, 2064), True, 'import numpy as np\n')]
|
import torch
from torchvision import datasets
import shutil
import argparse
import os
import numpy as np
from tqdm import tqdm
########### Help ###########
'''
#size = (h,w)
python split_train_val.py \
--data_dir /Users/aman.gupta/Documents/self/datasets/blank_page_detection/letterbox_training_data/ \
--val_ratio 0.10 \
--output_dir /Users/aman.gupta/Documents/self/datasets/blank_page_detection/splitted_letterbox_training_data
'''
###########################
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="this script splits classification data into train and val based on ratio provided by user")
parser.add_argument("--data_dir",required = True,help="training data path")
parser.add_argument("--val_ratio",default = 0.2,type = float, help="ratio of val in total data")
parser.add_argument("--output_dir",required=False,default="./data/",type=str,help="dir to save images")
args = parser.parse_args()
os.makedirs(args.output_dir,exist_ok=True)
data = datasets.ImageFolder(args.data_dir)
imgs_info = data.imgs
classes = data.classes
output_folders = ['train','val']
for o_folder in output_folders:
for folder in classes:
os.makedirs(os.path.join(args.output_dir,o_folder,folder),exist_ok=True)
print(f"Total classes:{len(classes)}")
np.random.shuffle(imgs_info)
num_samples = len(imgs_info)
split = int(np.floor(args.val_ratio * num_samples))
train_info, test_info = imgs_info[split:], imgs_info[:split]
print(f"processing train...")
for info in tqdm(train_info):
folder = classes[info[1]]
source = info[0]
file_name = os.path.basename(source)
destination = os.path.join(args.output_dir,output_folders[0],folder,file_name)
shutil.copy(source, destination)
print(f"processing val...")
for info in tqdm(test_info):
folder = classes[info[1]]
source = info[0]
file_name = os.path.basename(source)
destination = os.path.join(args.output_dir,output_folders[1],folder,file_name)
shutil.copy(source, destination)
|
[
"os.makedirs",
"argparse.ArgumentParser",
"tqdm.tqdm",
"numpy.floor",
"os.path.join",
"torchvision.datasets.ImageFolder",
"os.path.basename",
"shutil.copy",
"numpy.random.shuffle"
] |
[((524, 662), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""this script splits classification data into train and val based on ratio provided by user"""'}), "(description=\n 'this script splits classification data into train and val based on ratio provided by user'\n )\n", (547, 662), False, 'import argparse\n'), ((982, 1025), 'os.makedirs', 'os.makedirs', (['args.output_dir'], {'exist_ok': '(True)'}), '(args.output_dir, exist_ok=True)\n', (993, 1025), False, 'import os\n'), ((1038, 1073), 'torchvision.datasets.ImageFolder', 'datasets.ImageFolder', (['args.data_dir'], {}), '(args.data_dir)\n', (1058, 1073), False, 'from torchvision import datasets\n'), ((1370, 1398), 'numpy.random.shuffle', 'np.random.shuffle', (['imgs_info'], {}), '(imgs_info)\n', (1387, 1398), True, 'import numpy as np\n'), ((1610, 1626), 'tqdm.tqdm', 'tqdm', (['train_info'], {}), '(train_info)\n', (1614, 1626), False, 'from tqdm import tqdm\n'), ((1914, 1929), 'tqdm.tqdm', 'tqdm', (['test_info'], {}), '(test_info)\n', (1918, 1929), False, 'from tqdm import tqdm\n'), ((1453, 1491), 'numpy.floor', 'np.floor', (['(args.val_ratio * num_samples)'], {}), '(args.val_ratio * num_samples)\n', (1461, 1491), True, 'import numpy as np\n'), ((1707, 1731), 'os.path.basename', 'os.path.basename', (['source'], {}), '(source)\n', (1723, 1731), False, 'import os\n'), ((1754, 1821), 'os.path.join', 'os.path.join', (['args.output_dir', 'output_folders[0]', 'folder', 'file_name'], {}), '(args.output_dir, output_folders[0], folder, file_name)\n', (1766, 1821), False, 'import os\n'), ((1827, 1859), 'shutil.copy', 'shutil.copy', (['source', 'destination'], {}), '(source, destination)\n', (1838, 1859), False, 'import shutil\n'), ((2010, 2034), 'os.path.basename', 'os.path.basename', (['source'], {}), '(source)\n', (2026, 2034), False, 'import os\n'), ((2057, 2124), 'os.path.join', 'os.path.join', (['args.output_dir', 'output_folders[1]', 'folder', 'file_name'], {}), '(args.output_dir, output_folders[1], folder, file_name)\n', (2069, 2124), False, 'import os\n'), ((2130, 2162), 'shutil.copy', 'shutil.copy', (['source', 'destination'], {}), '(source, destination)\n', (2141, 2162), False, 'import shutil\n'), ((1256, 1303), 'os.path.join', 'os.path.join', (['args.output_dir', 'o_folder', 'folder'], {}), '(args.output_dir, o_folder, folder)\n', (1268, 1303), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 11:09:33 2019
@author: 10365
"""
#CreateDataSet
import numpy as np
import sys
sys.path.append('../subway_system')
sys.path.append('../ato_agent')
import TrainAndRoadCharacter as trc
import trainRunningModel as trm
import pandas as pds
import matplotlib.pyplot as plt
import atoController
def readSwitchPointSet(file):
#返回值SwitchPointMat
with open(file,mode='r',encoding='UTF-8-sig') as file_obj:
contents=file_obj.readlines()
row=len(contents) #行数
col=len(contents[0].split(',')) #列数
SwitchPointMat=np.zeros((row,col))
rIndex=0
for line in contents:
line.strip() #移除'\n'
listFormline=line.split(',')
cIndex=0
for ele in listFormline:
SwitchPointMat[rIndex,cIndex]=float(ele)
cIndex+=1
rIndex+=1
return SwitchPointMat
def SaveDataSet(num,data,filedir):
data.reset_index()
data.to_csv(filedir+str(num)+'_dataSet.csv',index=False)
return True
def ReadDataSet(num,filedir):
with open(filedir+str(num)+'_dataSet.csv',mode='r',encoding='UTF-8-sig') as file_obj:
contents=file_obj.readlines()
line=contents[0]
line.strip()
strElems=line.split(',')
row=len(contents)
col=len(strElems)
dataMat=np.zeros((row,col))
for i in range(0,row):
line=contents[i]
line.strip()
strElems=line.split(',')
for j in range(0,col):
dataMat[i,j]=float(strElems[j])
return dataMat
def TanslationBySimulation(switchPoint,index):
#模拟列车运行,将工况控制点转换成(s,v,t,u)组合
dt=0.2 #时间步长
startPoint=trc.SLStartPoint[0]
endPoint=trc.SLStartPoint[-1]
sl=trc.getRoadspeedLimit(startPoint)
gd=trc.getRoadGradinet(startPoint)
nsl=trc.getNextSpeedLimit(startPoint)
nsld=trc.getSpeedLimitEndPoint(startPoint)
vList=[0] #速度
sList=[startPoint] #位置
tList=[0] #时间
uList=[1] #加速度
gdList=[gd] #坡度 千分
slList=[sl] #路段限速(m/s)
nslList=[nsl] #下一限速的值(m/s)
nsldList=[nsld] #下一限速的距离(m)
train=trm.Train_model(startPoint,0,0.6,dt)
PIDC=atoController.PidController(dt,8,10,1)
trd=trc.TrainAndRoadData()
t=0
accList=[0]
stateList=[2]
state=2
acc=0.1
while True:
t=t+dt
laststate=state
state=trc.getRunState(sList[-1],switchPoint)
if state==1 and laststate!=1:
vbar=vList[-1]
if state==2:
#牵引
acc=1
if state==1:
#巡航
acc=PIDC.Step(vbar,vList[-1])
elif state==0:
#惰行
acc=0
elif state==-1:
#制动
acc=-1
if vList[-1]>trd.getEmerencyBrakeSpeed(sList[-1]):
acc=-1
out=train.Step(acc)
trueAcc=out['acc']
stateList.append(state)
accList.append(acc)
sl=trc.getRoadspeedLimit(out['S'])
gd=trc.getRoadGradinet(out['S'])
nsl=trc.getNextSpeedLimit(out['S'])
nsld=trc.getSpeedLimitEndPoint(out['S'])
vList.append(out['v'])
sList.append(out['S'])
tList.append(t)
uList.append(acc)
gdList.append(gd) #坡度 千分
slList.append(sl) #路段限速(m/s)
nslList.append(nsl) #下一限速的值(m/s)
nsldList.append(nsld) #下一限速的距离(m)
if out['S']>endPoint or out['v']<0:
break
#保存数据
plt.plot(sList,accList)
plt.plot(sList,stateList)
plt.show()
trc.plotSpeedLimitRoadGrad('abstract')
plt.plot(sList,vList)
plt.show()
plt.plot(tList,vList)
plt.show()
print('-------------------%d---------------------' %index)
dataList=[]
for i in range(0,len(vList)):
s=sList[i]
# t=tList[i]
sr=endPoint-sList[i]
t=tList[i]
tr=tList[-1]-t
vn=vList[i]
un=uList[i]
sr=round(sr,2)
tr=round(tr,2)
vn=round(vn,2)
sl=slList[i]
gd=gdList[i]
nsl=nslList[i]
nsld=nsldList[i]
line=[s,sr,tList[-1],tr,sl,gd,nsl,nsld,un]
#如果list是一维的,则是以列的形式来进行添加,如果list是二维的则是以行的形式进行添加的
dataList.append(line)
tC=np.mat([sList,vList])
targetCurve=pds.DataFrame(data=tC.T,columns=['s','v'])
pData=pds.DataFrame(data=dataList,columns=['s','sr','t','tr','sl','gd','nsl','nsld','un'])
return pData, targetCurve, tList[-1]
def produceData(style):
if style=='train':
#训练数据
swfile='TrainSwitchPointSet.csv'
outputdir='./TrainningDataSet/'
#测试数据
elif style=='test':
swfile='TestSwitchPointSet.csv'
outputdir='./TestingdataSet/'
sps=readSwitchPointSet(swfile)
print('开始生产数据')
row=sps.shape[0]
maxLevel=0
for i in range(0,row):
dataList,targetCurve,T=TanslationBySimulation(sps[i,:].tolist(),i)
SaveDataSet(i+1,dataList,outputdir)
targetCurve.to_csv('./targetCurveDataSet/'+str(round(T,2))+'_Curve.csv',index=False)
print(str(i))
print(str(T))
return maxLevel
if __name__ == '__main__':
ml=produceData('train')
ml=produceData('test')
|
[
"numpy.mat",
"TrainAndRoadCharacter.getRoadGradinet",
"trainRunningModel.Train_model",
"TrainAndRoadCharacter.TrainAndRoadData",
"pandas.DataFrame",
"atoController.PidController",
"TrainAndRoadCharacter.getNextSpeedLimit",
"TrainAndRoadCharacter.plotSpeedLimitRoadGrad",
"matplotlib.pyplot.plot",
"numpy.zeros",
"TrainAndRoadCharacter.getRoadspeedLimit",
"TrainAndRoadCharacter.getSpeedLimitEndPoint",
"TrainAndRoadCharacter.getRunState",
"sys.path.append",
"matplotlib.pyplot.show"
] |
[((133, 168), 'sys.path.append', 'sys.path.append', (['"""../subway_system"""'], {}), "('../subway_system')\n", (148, 168), False, 'import sys\n'), ((169, 200), 'sys.path.append', 'sys.path.append', (['"""../ato_agent"""'], {}), "('../ato_agent')\n", (184, 200), False, 'import sys\n'), ((1810, 1843), 'TrainAndRoadCharacter.getRoadspeedLimit', 'trc.getRoadspeedLimit', (['startPoint'], {}), '(startPoint)\n', (1831, 1843), True, 'import TrainAndRoadCharacter as trc\n'), ((1851, 1882), 'TrainAndRoadCharacter.getRoadGradinet', 'trc.getRoadGradinet', (['startPoint'], {}), '(startPoint)\n', (1870, 1882), True, 'import TrainAndRoadCharacter as trc\n'), ((1891, 1924), 'TrainAndRoadCharacter.getNextSpeedLimit', 'trc.getNextSpeedLimit', (['startPoint'], {}), '(startPoint)\n', (1912, 1924), True, 'import TrainAndRoadCharacter as trc\n'), ((1934, 1971), 'TrainAndRoadCharacter.getSpeedLimitEndPoint', 'trc.getSpeedLimitEndPoint', (['startPoint'], {}), '(startPoint)\n', (1959, 1971), True, 'import TrainAndRoadCharacter as trc\n'), ((2307, 2346), 'trainRunningModel.Train_model', 'trm.Train_model', (['startPoint', '(0)', '(0.6)', 'dt'], {}), '(startPoint, 0, 0.6, dt)\n', (2322, 2346), True, 'import trainRunningModel as trm\n'), ((2353, 2394), 'atoController.PidController', 'atoController.PidController', (['dt', '(8)', '(10)', '(1)'], {}), '(dt, 8, 10, 1)\n', (2380, 2394), False, 'import atoController\n'), ((2400, 2422), 'TrainAndRoadCharacter.TrainAndRoadData', 'trc.TrainAndRoadData', ([], {}), '()\n', (2420, 2422), True, 'import TrainAndRoadCharacter as trc\n'), ((3707, 3731), 'matplotlib.pyplot.plot', 'plt.plot', (['sList', 'accList'], {}), '(sList, accList)\n', (3715, 3731), True, 'import matplotlib.pyplot as plt\n'), ((3735, 3761), 'matplotlib.pyplot.plot', 'plt.plot', (['sList', 'stateList'], {}), '(sList, stateList)\n', (3743, 3761), True, 'import matplotlib.pyplot as plt\n'), ((3765, 3775), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3773, 3775), True, 'import matplotlib.pyplot as plt\n'), ((3780, 3818), 'TrainAndRoadCharacter.plotSpeedLimitRoadGrad', 'trc.plotSpeedLimitRoadGrad', (['"""abstract"""'], {}), "('abstract')\n", (3806, 3818), True, 'import TrainAndRoadCharacter as trc\n'), ((3823, 3845), 'matplotlib.pyplot.plot', 'plt.plot', (['sList', 'vList'], {}), '(sList, vList)\n', (3831, 3845), True, 'import matplotlib.pyplot as plt\n'), ((3849, 3859), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3857, 3859), True, 'import matplotlib.pyplot as plt\n'), ((3864, 3886), 'matplotlib.pyplot.plot', 'plt.plot', (['tList', 'vList'], {}), '(tList, vList)\n', (3872, 3886), True, 'import matplotlib.pyplot as plt\n'), ((3890, 3900), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3898, 3900), True, 'import matplotlib.pyplot as plt\n'), ((4467, 4489), 'numpy.mat', 'np.mat', (['[sList, vList]'], {}), '([sList, vList])\n', (4473, 4489), True, 'import numpy as np\n'), ((4505, 4549), 'pandas.DataFrame', 'pds.DataFrame', ([], {'data': 'tC.T', 'columns': "['s', 'v']"}), "(data=tC.T, columns=['s', 'v'])\n", (4518, 4549), True, 'import pandas as pds\n'), ((4558, 4655), 'pandas.DataFrame', 'pds.DataFrame', ([], {'data': 'dataList', 'columns': "['s', 'sr', 't', 'tr', 'sl', 'gd', 'nsl', 'nsld', 'un']"}), "(data=dataList, columns=['s', 'sr', 't', 'tr', 'sl', 'gd',\n 'nsl', 'nsld', 'un'])\n", (4571, 4655), True, 'import pandas as pds\n'), ((603, 623), 'numpy.zeros', 'np.zeros', (['(row, col)'], {}), '((row, col))\n', (611, 623), True, 'import numpy as np\n'), ((1377, 1397), 'numpy.zeros', 'np.zeros', (['(row, col)'], {}), '((row, col))\n', (1385, 1397), True, 'import numpy as np\n'), ((2566, 2605), 'TrainAndRoadCharacter.getRunState', 'trc.getRunState', (['sList[-1]', 'switchPoint'], {}), '(sList[-1], switchPoint)\n', (2581, 2605), True, 'import TrainAndRoadCharacter as trc\n'), ((3132, 3163), 'TrainAndRoadCharacter.getRoadspeedLimit', 'trc.getRoadspeedLimit', (["out['S']"], {}), "(out['S'])\n", (3153, 3163), True, 'import TrainAndRoadCharacter as trc\n'), ((3175, 3204), 'TrainAndRoadCharacter.getRoadGradinet', 'trc.getRoadGradinet', (["out['S']"], {}), "(out['S'])\n", (3194, 3204), True, 'import TrainAndRoadCharacter as trc\n'), ((3217, 3248), 'TrainAndRoadCharacter.getNextSpeedLimit', 'trc.getNextSpeedLimit', (["out['S']"], {}), "(out['S'])\n", (3238, 3248), True, 'import TrainAndRoadCharacter as trc\n'), ((3262, 3297), 'TrainAndRoadCharacter.getSpeedLimitEndPoint', 'trc.getSpeedLimitEndPoint', (["out['S']"], {}), "(out['S'])\n", (3287, 3297), True, 'import TrainAndRoadCharacter as trc\n')]
|
import sys
sys.path.insert(0, '../')
from mocap.settings import get_amass_validation_files, get_amass_test_files
from mocap.math.amass_fk import rotmat2euclidean, exp2euclidean
from mocap.visualization.sequence import SequenceVisualizer
from mocap.math.mirror_smpl import mirror_p3d
from mocap.datasets.dataset import Limb
from mocap.datasets.combined import Combined
from mocap.datasets.framerate import AdaptFramerate
import mocap.datasets.h36m as H36M
import numpy as np
import numpy.linalg as la
from mocap.datasets.amass import AMASS_SMPL3d, AMASS_QUAT, AMASS_EXP
data_loc = '/mnt/Data/datasets/amass'
val = get_amass_validation_files()
test = get_amass_test_files()
ds = AMASS_SMPL3d(val, data_loc=data_loc)
print(ds.get_joints_for_limb(Limb.LEFT_LEG))
ds = AdaptFramerate(Combined(ds), target_framerate=50)
print(ds.get_joints_for_limb(Limb.LEFT_LEG))
ds_h36m = Combined(H36M.H36M_FixedSkeleton(actors=['S5'], actions=['walking'], remove_global_Rt=True))
seq3d = ds[0]
seq3d_h36m = ds_h36m[0]
seq3d = seq3d[0:200].reshape((200, 14, 3))
seq3d_h36m = seq3d_h36m[0:200].reshape((200, 14, 3))
a = np.array([[[0.4, 0, 0]]])
b = np.array([[[-0.4, 0, 0]]])
seq3d += a
seq3d_h36m += b
vis_dir = '../output/'
vis = SequenceVisualizer(vis_dir, 'vis_amass_vs_h36m',
to_file=True,
mark_origin=False)
vis.plot(seq1=seq3d, seq2=seq3d_h36m, parallel=True,
create_video=True,
noaxis=False,
plot_jid=False,
)
|
[
"mocap.datasets.combined.Combined",
"sys.path.insert",
"mocap.settings.get_amass_validation_files",
"mocap.datasets.h36m.H36M_FixedSkeleton",
"mocap.datasets.amass.AMASS_SMPL3d",
"numpy.array",
"mocap.settings.get_amass_test_files",
"mocap.visualization.sequence.SequenceVisualizer"
] |
[((11, 36), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (26, 36), False, 'import sys\n'), ((617, 645), 'mocap.settings.get_amass_validation_files', 'get_amass_validation_files', ([], {}), '()\n', (643, 645), False, 'from mocap.settings import get_amass_validation_files, get_amass_test_files\n'), ((653, 675), 'mocap.settings.get_amass_test_files', 'get_amass_test_files', ([], {}), '()\n', (673, 675), False, 'from mocap.settings import get_amass_validation_files, get_amass_test_files\n'), ((682, 718), 'mocap.datasets.amass.AMASS_SMPL3d', 'AMASS_SMPL3d', (['val'], {'data_loc': 'data_loc'}), '(val, data_loc=data_loc)\n', (694, 718), False, 'from mocap.datasets.amass import AMASS_SMPL3d, AMASS_QUAT, AMASS_EXP\n'), ((1112, 1137), 'numpy.array', 'np.array', (['[[[0.4, 0, 0]]]'], {}), '([[[0.4, 0, 0]]])\n', (1120, 1137), True, 'import numpy as np\n'), ((1142, 1168), 'numpy.array', 'np.array', (['[[[-0.4, 0, 0]]]'], {}), '([[[-0.4, 0, 0]]])\n', (1150, 1168), True, 'import numpy as np\n'), ((1229, 1315), 'mocap.visualization.sequence.SequenceVisualizer', 'SequenceVisualizer', (['vis_dir', '"""vis_amass_vs_h36m"""'], {'to_file': '(True)', 'mark_origin': '(False)'}), "(vis_dir, 'vis_amass_vs_h36m', to_file=True, mark_origin=\n False)\n", (1247, 1315), False, 'from mocap.visualization.sequence import SequenceVisualizer\n'), ((785, 797), 'mocap.datasets.combined.Combined', 'Combined', (['ds'], {}), '(ds)\n', (793, 797), False, 'from mocap.datasets.combined import Combined\n'), ((886, 972), 'mocap.datasets.h36m.H36M_FixedSkeleton', 'H36M.H36M_FixedSkeleton', ([], {'actors': "['S5']", 'actions': "['walking']", 'remove_global_Rt': '(True)'}), "(actors=['S5'], actions=['walking'],\n remove_global_Rt=True)\n", (909, 972), True, 'import mocap.datasets.h36m as H36M\n')]
|
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from PySide2.QtWidgets import QVBoxLayout, QWidget
from traitlets import HasTraits, Instance, Bool, directional_link
from regexport.model import AppState
from regexport.views.utils import HasWidget
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
class PlotModel(HasTraits):
selected_data = Instance(np.ndarray, allow_none=True)
data = Instance(np.ndarray, allow_none=True)
show = Bool(default_value=True)
def register(self, model: AppState):
self.model = model
model.observe(self.update, ['cells', 'selected_cells', 'column_to_plot', 'show_plots'])
directional_link((model, 'show_plots'), (self, 'show'))
def update(self, change):
model = self.model
if model.selected_cells is None or model.selected_cells[model.column_to_plot].dtype.name == 'category':
self.selected_data = None
else:
self.data = model.cells[model.column_to_plot].values
self.selected_data = model.selected_cells[model.column_to_plot].values
class PlotView(HasWidget):
# Code from https://www.pythonguis.com/tutorials/plotting-matplotlib/
def __init__(self, model: PlotModel, width=5, height=4, dpi=100):
# Make a figure, turn it into a canvas widget
widget = QWidget()
layout = QVBoxLayout()
widget.setLayout(layout)
HasWidget.__init__(self, widget=widget)
self.fig, self.axes = plt.subplots(ncols=2, figsize=(width, height), dpi=dpi)
self.canvas = FigureCanvasQTAgg(figure=self.fig)
layout.addWidget(self.canvas)
self.toolbar = NavigationToolbar2QT(self.canvas, widget)
layout.addWidget(self.toolbar)
self.model = model
self.model.observe(self.render)
def render(self, change):
if self.model.show:
for ax in self.axes:
ax.cla()
if change.new is None:
return
else:
selected_data = self.model.selected_data
if selected_data is not None:
data = selected_data
_, edges = np.histogram(data[data > 0], bins='auto')
all_edges = np.concatenate([[0, 1], edges])
self.axes[0].hist(
data,
bins=all_edges,
cumulative=False,
# density=True,
)
data = self.model.data
ax: plt.Axes = self.axes[1]
ax.hist(
data,
bins=50,
cumulative=True,
density=True,
)
if selected_data is not None:
ax.vlines(selected_data.max(), 0, 1, colors='black', linestyles='dotted')
# self.axes[1].set_ylim(0, 1)
self.canvas.draw()
|
[
"traitlets.directional_link",
"matplotlib.backends.backend_qt5agg.NavigationToolbar2QT",
"numpy.histogram",
"regexport.views.utils.HasWidget.__init__",
"matplotlib.use",
"traitlets.Instance",
"PySide2.QtWidgets.QWidget",
"numpy.concatenate",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg",
"PySide2.QtWidgets.QVBoxLayout",
"matplotlib.pyplot.subplots",
"traitlets.Bool"
] |
[((269, 293), 'matplotlib.use', 'matplotlib.use', (['"""Qt5Agg"""'], {}), "('Qt5Agg')\n", (283, 293), False, 'import matplotlib\n'), ((470, 507), 'traitlets.Instance', 'Instance', (['np.ndarray'], {'allow_none': '(True)'}), '(np.ndarray, allow_none=True)\n', (478, 507), False, 'from traitlets import HasTraits, Instance, Bool, directional_link\n'), ((519, 556), 'traitlets.Instance', 'Instance', (['np.ndarray'], {'allow_none': '(True)'}), '(np.ndarray, allow_none=True)\n', (527, 556), False, 'from traitlets import HasTraits, Instance, Bool, directional_link\n'), ((568, 592), 'traitlets.Bool', 'Bool', ([], {'default_value': '(True)'}), '(default_value=True)\n', (572, 592), False, 'from traitlets import HasTraits, Instance, Bool, directional_link\n'), ((766, 821), 'traitlets.directional_link', 'directional_link', (["(model, 'show_plots')", "(self, 'show')"], {}), "((model, 'show_plots'), (self, 'show'))\n", (782, 821), False, 'from traitlets import HasTraits, Instance, Bool, directional_link\n'), ((1437, 1446), 'PySide2.QtWidgets.QWidget', 'QWidget', ([], {}), '()\n', (1444, 1446), False, 'from PySide2.QtWidgets import QVBoxLayout, QWidget\n'), ((1465, 1478), 'PySide2.QtWidgets.QVBoxLayout', 'QVBoxLayout', ([], {}), '()\n', (1476, 1478), False, 'from PySide2.QtWidgets import QVBoxLayout, QWidget\n'), ((1520, 1559), 'regexport.views.utils.HasWidget.__init__', 'HasWidget.__init__', (['self'], {'widget': 'widget'}), '(self, widget=widget)\n', (1538, 1559), False, 'from regexport.views.utils import HasWidget\n'), ((1591, 1646), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(2)', 'figsize': '(width, height)', 'dpi': 'dpi'}), '(ncols=2, figsize=(width, height), dpi=dpi)\n', (1603, 1646), True, 'import matplotlib.pyplot as plt\n'), ((1669, 1703), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg', 'FigureCanvasQTAgg', ([], {'figure': 'self.fig'}), '(figure=self.fig)\n', (1686, 1703), False, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT\n'), ((1766, 1807), 'matplotlib.backends.backend_qt5agg.NavigationToolbar2QT', 'NavigationToolbar2QT', (['self.canvas', 'widget'], {}), '(self.canvas, widget)\n', (1786, 1807), False, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT\n'), ((2283, 2324), 'numpy.histogram', 'np.histogram', (['data[data > 0]'], {'bins': '"""auto"""'}), "(data[data > 0], bins='auto')\n", (2295, 2324), True, 'import numpy as np\n'), ((2357, 2388), 'numpy.concatenate', 'np.concatenate', (['[[0, 1], edges]'], {}), '([[0, 1], edges])\n', (2371, 2388), True, 'import numpy as np\n')]
|
import logging
from typing import Any, Dict, List, NewType
import mlflow
import numpy as np
import pandas as pd
import torch
import transformers
from mlflow.models import ModelSignature
from mlflow.pyfunc import PythonModel
from mlflow.types import ColSpec, DataType, Schema, TensorSpec
from mlflow.utils.environment import _mlflow_conda_env
from transformers.pipelines.pt_utils import KeyDataset
from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
Trainer,
pipeline
)
from tagflip.model.autonlp_arguments import AutoNLPArguments
from tagflip.model.mlflow.mlflow_savable import LogArgs, MLflowSavable, Name, Path
Model = NewType("Model", Any)
Tokenizer = NewType("Tokenizer", Any)
Config = NewType("Config", Any)
logger = logging.getLogger(__name__)
class HuggingFaceSequenceClassificationSavable(MLflowSavable):
"""
Saves a NLP model for text classification that has been trained using Hugging Face Transformer API.
"""
def __init__(self, trainer: Trainer, label_list: List[str]):
"""
The constructor
:param trainer: the Hugging Face Trainer being used to train the model
:param label_list: the list of labels
"""
self.trainer = trainer
self.label_list = label_list
def local_artifact_paths(self, autonlp_args: AutoNLPArguments) -> Dict[Name, Path]:
model_identifier = autonlp_args.training_id
logger.info("Saving model locally...")
self.trainer.save_model(model_identifier)
return {model_identifier: model_identifier}
def log_args(self, _: AutoNLPArguments) -> LogArgs:
conda_env = _mlflow_conda_env(
additional_conda_deps=[],
additional_pip_deps=[
"pandas~={}".format(pd.__version__),
"torch~={}".format(torch.__version__),
"transformers=={}".format(transformers.__version__),
"mlflow=={}".format(mlflow.__version__),
])
return LogArgs(artifact_path="huggingface-pyfunc",
input_example=[
"This is some example sentence. Maybe a second sentence in same context.",
"This is some other sentence."
],
signature=ModelSignature(
Schema([ColSpec(type=DataType.string)]),
Schema([TensorSpec(np.dtype('str'), (-1, -1, 2))])
),
conda_env=conda_env
)
def python_model(self, autonlp_args: AutoNLPArguments) -> PythonModel:
model_identifier = autonlp_args.training_id
return HuggingFaceSequenceClassificationSavable.create_python_model(model_identifier, self.label_list)
@classmethod
def create_python_model(cls, model_identifier, label_list):
class SequenceClassificationPythonModel(PythonModel):
def __init__(self):
self.trained_model = None
self.tokenizer = None
self.label_list = None
def load_context(self, context):
model_artifact_path = context.artifacts[model_identifier]
self.trained_model = AutoModelForSequenceClassification.from_pretrained(
f"{model_artifact_path}")
self.tokenizer = AutoTokenizer.from_pretrained(
f"{model_artifact_path}")
self.label_list = label_list
def predict(self, context, input_df):
sentences = input_df.values.tolist()
logger.info(f"predict: input={sentences}")
sentences = list(map(lambda sentence: sentence[0], sentences))
pipe = pipeline(
"text-classification", model=self.trained_model, tokenizer=self.tokenizer)
pipe_sentences = []
for text, result in zip(sentences, pipe(sentences)):
result["text"] = text
pipe_sentences.append(result)
return pipe_sentences
return SequenceClassificationPythonModel()
|
[
"logging.getLogger",
"typing.NewType",
"transformers.AutoModelForSequenceClassification.from_pretrained",
"transformers.AutoTokenizer.from_pretrained",
"numpy.dtype",
"transformers.pipeline",
"mlflow.types.ColSpec"
] |
[((666, 687), 'typing.NewType', 'NewType', (['"""Model"""', 'Any'], {}), "('Model', Any)\n", (673, 687), False, 'from typing import Any, Dict, List, NewType\n'), ((700, 725), 'typing.NewType', 'NewType', (['"""Tokenizer"""', 'Any'], {}), "('Tokenizer', Any)\n", (707, 725), False, 'from typing import Any, Dict, List, NewType\n'), ((735, 757), 'typing.NewType', 'NewType', (['"""Config"""', 'Any'], {}), "('Config', Any)\n", (742, 757), False, 'from typing import Any, Dict, List, NewType\n'), ((768, 795), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (785, 795), False, 'import logging\n'), ((3263, 3339), 'transformers.AutoModelForSequenceClassification.from_pretrained', 'AutoModelForSequenceClassification.from_pretrained', (['f"""{model_artifact_path}"""'], {}), "(f'{model_artifact_path}')\n", (3313, 3339), False, 'from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, pipeline\n'), ((3394, 3449), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['f"""{model_artifact_path}"""'], {}), "(f'{model_artifact_path}')\n", (3423, 3449), False, 'from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, pipeline\n'), ((3781, 3869), 'transformers.pipeline', 'pipeline', (['"""text-classification"""'], {'model': 'self.trained_model', 'tokenizer': 'self.tokenizer'}), "('text-classification', model=self.trained_model, tokenizer=self.\n tokenizer)\n", (3789, 3869), False, 'from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, pipeline\n'), ((2366, 2395), 'mlflow.types.ColSpec', 'ColSpec', ([], {'type': 'DataType.string'}), '(type=DataType.string)\n', (2373, 2395), False, 'from mlflow.types import ColSpec, DataType, Schema, TensorSpec\n'), ((2445, 2460), 'numpy.dtype', 'np.dtype', (['"""str"""'], {}), "('str')\n", (2453, 2460), True, 'import numpy as np\n')]
|
"Code used to generate data for experiments with synthetic data"
import math
import typing as ty
import numba
import numpy as np
import torch
import torch.nn as nn
from numba.experimental import jitclass
from tqdm.auto import tqdm
class MLP(nn.Module):
def __init__(
self,
*,
d_in: int,
d_layers: ty.List[int],
d_out: int,
bias: bool = True,
) -> None:
super().__init__()
self.layers = nn.ModuleList(
[
nn.Linear(d_layers[i - 1] if i else d_in, x, bias=bias)
for i, x in enumerate(d_layers)
]
)
self.head = nn.Linear(d_layers[-1] if d_layers else d_in, d_out)
def init_weights(m):
if isinstance(m, nn.Linear):
torch.nn.init.kaiming_normal_(m.weight, mode='fan_in')
if m.bias is not None:
fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(m.weight)
bound = 1 / math.sqrt(fan_in)
torch.nn.init.uniform_(m.bias, -bound, bound)
self.apply(init_weights)
def forward(self, x: torch.Tensor) -> torch.Tensor:
for layer in self.layers:
x = layer(x)
x = torch.relu(x)
x = self.head(x)
x = x.squeeze(-1)
return x
@jitclass(
spec=[
('left_children', numba.int64[:]),
('right_children', numba.int64[:]),
('feature', numba.int64[:]),
('threshold', numba.float32[:]),
('value', numba.float32[:]),
('is_leaf', numba.int64[:]),
]
)
class Tree:
"Randomly initialized decision tree"
def __init__(self, n_features, n_nodes, max_depth):
assert (2 ** np.arange(max_depth + 1)).sum() >= n_nodes, "Too much nodes"
self.left_children = np.ones(n_nodes, dtype=np.int64) * -1
self.right_children = np.ones(n_nodes, dtype=np.int64) * -1
self.feature = np.random.randint(0, n_features, (n_nodes,))
self.threshold = np.random.randn(n_nodes).astype(np.float32)
self.value = np.random.randn(n_nodes).astype(np.float32)
depth = np.zeros(n_nodes, dtype=np.int64)
# Root is 0
self.is_leaf = np.zeros(n_nodes, dtype=np.int64)
self.is_leaf[0] = 1
# Keep adding nodes while we can (new node must have 2 children)
while True:
idx = np.flatnonzero(self.is_leaf)[np.random.choice(self.is_leaf.sum())]
if depth[idx] < max_depth:
unused = np.flatnonzero(
(self.left_children == -1)
& (self.right_children == -1)
& ~self.is_leaf
)
if len(unused) < 2:
break
lr_child = unused[np.random.permutation(unused.shape[0])[:2]]
self.is_leaf[lr_child] = 1
self.is_leaf[lr_child] = 1
depth[lr_child] = depth[idx] + 1
self.left_children[idx] = lr_child[0]
self.right_children[idx] = lr_child[1]
self.is_leaf[idx] = 0
def apply(self, x):
y = np.zeros(x.shape[0])
for i in range(x.shape[0]):
idx = 0
while not self.is_leaf[idx]:
if x[i, self.feature[idx]] < self.threshold[idx]:
idx = self.left_children[idx]
else:
idx = self.right_children[idx]
y[i] = self.value[idx]
return y
class TreeEnsemble:
"Combine multiple trees"
def __init__(self, *, n_trees, n_features, n_nodes, max_depth):
self.trees = [
Tree(n_features=n_features, n_nodes=n_nodes, max_depth=max_depth)
for _ in range(n_trees)
]
def apply(self, x):
return np.mean([t.apply(x) for t in tqdm(self.trees)], axis=0)
|
[
"numpy.ones",
"numpy.flatnonzero",
"torch.relu",
"torch.nn.init.kaiming_normal_",
"numba.experimental.jitclass",
"math.sqrt",
"torch.nn.init._calculate_fan_in_and_fan_out",
"numpy.random.randint",
"numpy.zeros",
"torch.nn.init.uniform_",
"torch.nn.Linear",
"tqdm.auto.tqdm",
"numpy.random.randn",
"numpy.arange",
"numpy.random.permutation"
] |
[((1341, 1556), 'numba.experimental.jitclass', 'jitclass', ([], {'spec': "[('left_children', numba.int64[:]), ('right_children', numba.int64[:]), (\n 'feature', numba.int64[:]), ('threshold', numba.float32[:]), ('value',\n numba.float32[:]), ('is_leaf', numba.int64[:])]"}), "(spec=[('left_children', numba.int64[:]), ('right_children', numba.\n int64[:]), ('feature', numba.int64[:]), ('threshold', numba.float32[:]),\n ('value', numba.float32[:]), ('is_leaf', numba.int64[:])])\n", (1349, 1556), False, 'from numba.experimental import jitclass\n'), ((654, 706), 'torch.nn.Linear', 'nn.Linear', (['(d_layers[-1] if d_layers else d_in)', 'd_out'], {}), '(d_layers[-1] if d_layers else d_in, d_out)\n', (663, 706), True, 'import torch.nn as nn\n'), ((1960, 2004), 'numpy.random.randint', 'np.random.randint', (['(0)', 'n_features', '(n_nodes,)'], {}), '(0, n_features, (n_nodes,))\n', (1977, 2004), True, 'import numpy as np\n'), ((2155, 2188), 'numpy.zeros', 'np.zeros', (['n_nodes'], {'dtype': 'np.int64'}), '(n_nodes, dtype=np.int64)\n', (2163, 2188), True, 'import numpy as np\n'), ((2233, 2266), 'numpy.zeros', 'np.zeros', (['n_nodes'], {'dtype': 'np.int64'}), '(n_nodes, dtype=np.int64)\n', (2241, 2266), True, 'import numpy as np\n'), ((3165, 3185), 'numpy.zeros', 'np.zeros', (['x.shape[0]'], {}), '(x.shape[0])\n', (3173, 3185), True, 'import numpy as np\n'), ((1256, 1269), 'torch.relu', 'torch.relu', (['x'], {}), '(x)\n', (1266, 1269), False, 'import torch\n'), ((1831, 1863), 'numpy.ones', 'np.ones', (['n_nodes'], {'dtype': 'np.int64'}), '(n_nodes, dtype=np.int64)\n', (1838, 1863), True, 'import numpy as np\n'), ((1899, 1931), 'numpy.ones', 'np.ones', (['n_nodes'], {'dtype': 'np.int64'}), '(n_nodes, dtype=np.int64)\n', (1906, 1931), True, 'import numpy as np\n'), ((506, 561), 'torch.nn.Linear', 'nn.Linear', (['(d_layers[i - 1] if i else d_in)', 'x'], {'bias': 'bias'}), '(d_layers[i - 1] if i else d_in, x, bias=bias)\n', (515, 561), True, 'import torch.nn as nn\n'), ((794, 848), 'torch.nn.init.kaiming_normal_', 'torch.nn.init.kaiming_normal_', (['m.weight'], {'mode': '"""fan_in"""'}), "(m.weight, mode='fan_in')\n", (823, 848), False, 'import torch\n'), ((2030, 2054), 'numpy.random.randn', 'np.random.randn', (['n_nodes'], {}), '(n_nodes)\n', (2045, 2054), True, 'import numpy as np\n'), ((2095, 2119), 'numpy.random.randn', 'np.random.randn', (['n_nodes'], {}), '(n_nodes)\n', (2110, 2119), True, 'import numpy as np\n'), ((2407, 2435), 'numpy.flatnonzero', 'np.flatnonzero', (['self.is_leaf'], {}), '(self.is_leaf)\n', (2421, 2435), True, 'import numpy as np\n'), ((2538, 2631), 'numpy.flatnonzero', 'np.flatnonzero', (['((self.left_children == -1) & (self.right_children == -1) & ~self.is_leaf)'], {}), '((self.left_children == -1) & (self.right_children == -1) & ~\n self.is_leaf)\n', (2552, 2631), True, 'import numpy as np\n'), ((920, 973), 'torch.nn.init._calculate_fan_in_and_fan_out', 'torch.nn.init._calculate_fan_in_and_fan_out', (['m.weight'], {}), '(m.weight)\n', (963, 973), False, 'import torch\n'), ((1044, 1089), 'torch.nn.init.uniform_', 'torch.nn.init.uniform_', (['m.bias', '(-bound)', 'bound'], {}), '(m.bias, -bound, bound)\n', (1066, 1089), False, 'import torch\n'), ((3864, 3880), 'tqdm.auto.tqdm', 'tqdm', (['self.trees'], {}), '(self.trees)\n', (3868, 3880), False, 'from tqdm.auto import tqdm\n'), ((1006, 1023), 'math.sqrt', 'math.sqrt', (['fan_in'], {}), '(fan_in)\n', (1015, 1023), False, 'import math\n'), ((1740, 1764), 'numpy.arange', 'np.arange', (['(max_depth + 1)'], {}), '(max_depth + 1)\n', (1749, 1764), True, 'import numpy as np\n'), ((2802, 2840), 'numpy.random.permutation', 'np.random.permutation', (['unused.shape[0]'], {}), '(unused.shape[0])\n', (2823, 2840), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
import numpy
import storm_analysis
import storm_analysis.simulator.pupil_math as pupilMath
def test_pupil_math_1():
"""
Test GeometryC, intensity, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals)
psf_c = geo_c.pfToPSF(pf, z_vals)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_2():
"""
Test GeometryC, complex values, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals, want_intensity = False)
psf_c = geo_c.pfToPSF(pf, z_vals, want_intensity = False)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_3():
"""
Test GeometryC, intensity, scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
gsf = geo.gaussianScalingFactor(1.8)
psf_py = geo.pfToPSF(pf, z_vals, scaling_factor = gsf)
psf_c = geo_c.pfToPSF(pf, z_vals, scaling_factor = gsf)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_4():
"""
Test GeometryCVectorial, intensity, no scaling.
"""
geo = pupilMath.GeometryVectorial(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryCVectorial(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals)
psf_c = geo_c.pfToPSF(pf, z_vals)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_5():
"""
Test GeometryCVectorial, intensity, scaling.
"""
geo = pupilMath.GeometryVectorial(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryCVectorial(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
gsf = geo.gaussianScalingFactor(1.8)
psf_py = geo.pfToPSF(pf, z_vals, scaling_factor = gsf)
psf_c = geo_c.pfToPSF(pf, z_vals, scaling_factor = gsf)
if (__name__ == "__main__"):
test_pupil_math_1()
test_pupil_math_2()
test_pupil_math_3()
|
[
"numpy.allclose",
"storm_analysis.simulator.pupil_math.GeometryVectorial",
"storm_analysis.simulator.pupil_math.GeometryC",
"numpy.linspace",
"storm_analysis.simulator.pupil_math.GeometryCVectorial",
"storm_analysis.simulator.pupil_math.Geometry"
] |
[((211, 253), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (229, 253), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((266, 309), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (285, 309), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((395, 424), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (409, 424), False, 'import numpy\n'), ((515, 544), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (529, 544), False, 'import numpy\n'), ((645, 687), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (663, 687), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((700, 743), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (719, 743), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((829, 858), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (843, 858), False, 'import numpy\n'), ((997, 1026), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1011, 1026), False, 'import numpy\n'), ((1119, 1161), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1137, 1161), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1174, 1217), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1193, 1217), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1303, 1332), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (1317, 1332), False, 'import numpy\n'), ((1508, 1537), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1522, 1537), False, 'import numpy\n'), ((1642, 1693), 'storm_analysis.simulator.pupil_math.GeometryVectorial', 'pupilMath.GeometryVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1669, 1693), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1706, 1758), 'storm_analysis.simulator.pupil_math.GeometryCVectorial', 'pupilMath.GeometryCVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1734, 1758), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1844, 1873), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (1858, 1873), False, 'import numpy\n'), ((1964, 1993), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1978, 1993), False, 'import numpy\n'), ((2095, 2146), 'storm_analysis.simulator.pupil_math.GeometryVectorial', 'pupilMath.GeometryVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (2122, 2146), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((2159, 2211), 'storm_analysis.simulator.pupil_math.GeometryCVectorial', 'pupilMath.GeometryCVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (2187, 2211), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((2297, 2326), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (2311, 2326), False, 'import numpy\n')]
|
import numpy as np
import gdal
from ..utils.indexing import _LocIndexer, _iLocIndexer
from libpyhat.transform.continuum import continuum_correction
from libpyhat.transform.continuum import polynomial, linear, regression
class HCube(object):
"""
A Mixin class for use with the io_gdal.GeoDataset class
to optionally add support for spectral labels, label
based indexing, and lazy loading for reads.
"""
def __init__(self, data = [], wavelengths = []):
if len(data) != 0:
self._data = data
if len(wavelengths) != 0:
self._wavelengths = wavelengths
@property
def wavelengths(self):
if not hasattr(self, '_wavelengths'):
try:
info = gdal.Info(self.file_name, format='json')
wavelengths = [float(j) for i, j in sorted(info['metadata'][''].items(),
key=lambda x: float(x[0].split('_')[-1]))]
self._original_wavelengths = wavelengths
self._wavelengths = np.round(wavelengths, self.tolerance)
except:
self._wavelengths = []
return self._wavelengths
@property
def data(self):
if not hasattr(self, '_data'):
try:
key = (slice(None, None, None),
slice(None, None, None),
slice(None, None, None))
data = self._read(key)
except Exception as e:
print(e)
data = []
self._data = data
return self._data
@property
def tolerance(self):
return getattr(self, '_tolerance', 2)
@tolerance.setter
def tolerance(self, val):
if isinstance(val, int):
self._tolerance = val
self._reindex()
else:
raise TypeError
def _reindex(self):
if self._original_wavelengths is not None:
self._wavelengths = np.round(self._original_wavelengths, decimals=self.tolerance)
def __getitem__(self, key):
i = _iLocIndexer(self)
return i[key]
@property
def loc(self):
return _LocIndexer(self)
@property
def iloc(self):
return _iLocIndexer(self)
def reduce(self, how = np.mean, axis = (1, 2)):
"""
Parameters
----------
how : function
Function to apply across along axises of the hcube
axis : tuple
List of axis to apply a given function along
Returns
-------
new_hcube : Object
A new hcube object with the reduced data set
"""
res = how(self.data, axis = axis)
new_hcube = HCube(res, self.wavelengths)
return new_hcube
def continuum_correct(self, nodes, correction_nodes = np.array([]), correction = linear,
axis=0, adaptive=False, window=3, **kwargs):
"""
Parameters
----------
nodes : list
A list of wavelengths for the continuum to be corrected along
correction_nodes : list
A list of nodes to limit the correction between
correction : function
Function specifying the type of correction to perform
along the continuum
axis : int
Axis to apply the continuum correction on
adaptive : boolean
?
window : int
?
Returns
-------
new_hcube : Object
A new hcube object with the corrected dataset
"""
continuum_data = continuum_correction(self.data, self.wavelengths, nodes = nodes,
correction_nodes = correction_nodes, correction = correction,
axis = axis, adaptive = adaptive,
window = window, **kwargs)
new_hcube = HCube(continuum_data[0], self.wavelengths)
return new_hcube
def clip_roi(self, x, y, band, tolerance=2):
"""
Parameters
----------
x : tuple
Lower and upper bound along the x axis for clipping
y : tuple
Lower and upper bound along the y axis for clipping
band : tuple
Lower and upper band along the z axis for clipping
tolerance : int
Tolerance given for trying to find wavelengths
between the upper and lower bound
Returns
-------
new_hcube : Object
A new hcube object with the clipped dataset
"""
wavelength_clip = []
for wavelength in self.wavelengths:
wavelength_upper = wavelength + tolerance
wavelength_lower = wavelength - tolerance
if wavelength_upper > band[0] and wavelength_lower < band[1]:
wavelength_clip.append(wavelength)
key = (wavelength_clip, slice(*x), slice(*y))
data_clip = _LocIndexer(self)[key]
new_hcube = HCube(np.copy(data_clip), np.array(wavelength_clip))
return new_hcube
def _read(self, key):
ifnone = lambda a, b: b if a is None else a
y = key[1]
x = key[2]
if isinstance(x, slice):
xstart = ifnone(x.start,0)
xstop = ifnone(x.stop,self.raster_size[0])
xstep = xstop - xstart
else:
raise TypeError("Loc style access elements must be slices, e.g., [:] or [10:100]")
if isinstance(y, slice):
ystart = ifnone(y.start, 0)
ystop = ifnone(y.stop, self.raster_size[1])
ystep = ystop - ystart
else:
raise TypeError("Loc style access elements must be slices, e.g., [:] or [10:100]")
pixels = (xstart, ystart, xstep, ystep)
if isinstance(key[0], (int, np.integer)):
return self.read_array(band=int(key[0]+1), pixels=pixels)
elif isinstance(key[0], slice):
# Given some slice iterate over the bands and get the bands and pixel space requested
arrs = []
for band in list(list(range(1, self.nbands + 1))[key[0]]):
arrs.append(self.read_array(band, pixels = pixels))
return np.stack(arrs)
else:
arrs = []
for b in key[0]:
arrs.append(self.read_array(band=int(b+1), pixels=pixels))
return np.stack(arrs)
|
[
"numpy.copy",
"libpyhat.transform.continuum.continuum_correction",
"numpy.array",
"numpy.stack",
"gdal.Info",
"numpy.round"
] |
[((2841, 2853), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2849, 2853), True, 'import numpy as np\n'), ((3684, 3867), 'libpyhat.transform.continuum.continuum_correction', 'continuum_correction', (['self.data', 'self.wavelengths'], {'nodes': 'nodes', 'correction_nodes': 'correction_nodes', 'correction': 'correction', 'axis': 'axis', 'adaptive': 'adaptive', 'window': 'window'}), '(self.data, self.wavelengths, nodes=nodes,\n correction_nodes=correction_nodes, correction=correction, axis=axis,\n adaptive=adaptive, window=window, **kwargs)\n', (3704, 3867), False, 'from libpyhat.transform.continuum import continuum_correction\n'), ((6561, 6575), 'numpy.stack', 'np.stack', (['arrs'], {}), '(arrs)\n', (6569, 6575), True, 'import numpy as np\n'), ((1971, 2032), 'numpy.round', 'np.round', (['self._original_wavelengths'], {'decimals': 'self.tolerance'}), '(self._original_wavelengths, decimals=self.tolerance)\n', (1979, 2032), True, 'import numpy as np\n'), ((5168, 5186), 'numpy.copy', 'np.copy', (['data_clip'], {}), '(data_clip)\n', (5175, 5186), True, 'import numpy as np\n'), ((5188, 5213), 'numpy.array', 'np.array', (['wavelength_clip'], {}), '(wavelength_clip)\n', (5196, 5213), True, 'import numpy as np\n'), ((741, 781), 'gdal.Info', 'gdal.Info', (['self.file_name'], {'format': '"""json"""'}), "(self.file_name, format='json')\n", (750, 781), False, 'import gdal\n'), ((1040, 1077), 'numpy.round', 'np.round', (['wavelengths', 'self.tolerance'], {}), '(wavelengths, self.tolerance)\n', (1048, 1077), True, 'import numpy as np\n'), ((6390, 6404), 'numpy.stack', 'np.stack', (['arrs'], {}), '(arrs)\n', (6398, 6404), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
"""
Tests of ktrain text classification flows
"""
import sys
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID";
os.environ["CUDA_VISIBLE_DEVICES"]="0"
sys.path.insert(0,'../..')
from unittest import TestCase, main, skip
import ktrain
def synthetic_multilabel():
import numpy as np
# data
X = [[1,0,0,0,0,0,0],
[1,2,0,0,0,0,0],
[3,0,0,0,0,0,0],
[3,4,0,0,0,0,0],
[2,0,0,0,0,0,0],
[3,0,0,0,0,0,0],
[4,0,0,0,0,0,0],
[2,3,0,0,0,0,0],
[1,2,3,0,0,0,0],
[1,2,3,4,0,0,0],
[0,0,0,0,0,0,0],
[1,1,2,3,0,0,0],
[2,3,3,4,0,0,0],
[4,4,1,1,2,0,0],
[1,2,3,3,3,3,3],
[2,4,2,4,2,0,0],
[1,3,3,3,0,0,0],
[4,4,0,0,0,0,0],
[3,3,0,0,0,0,0],
[1,1,4,0,0,0,0]]
Y = [[1,0,0,0],
[1,1,0,0],
[0,0,1,0],
[0,0,1,1],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1],
[0,1,1,0],
[1,1,1,0],
[1,1,1,1],
[0,0,0,0],
[1,1,1,0],
[0,1,1,1],
[1,1,0,1],
[1,1,1,0],
[0,1,0,0],
[1,0,1,0],
[0,0,0,1],
[0,0,1,0],
[1,0,0,1]]
# model
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Embedding
from keras.layers import GlobalAveragePooling1D
import numpy as np
X = np.array(X)
Y = np.array(Y)
MAXLEN = 7
MAXFEATURES = 4
NUM_CLASSES = 4
model = Sequential()
model.add(Embedding(MAXFEATURES+1,
50,
input_length=MAXLEN))
model.add(GlobalAveragePooling1D())
model.add(Dense(NUM_CLASSES, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
#model.fit(X, Y,
#batch_size=1,
#epochs=200,
#validation_data=(X, Y))
learner = ktrain.get_learner(model,
train_data=(X, Y),
val_data=(X, Y),
batch_size=1)
learner.lr_find()
hist = learner.fit(0.001, 200)
learner.view_top_losses(n=5)
learner.validate()
return hist
class TestMultilabel(TestCase):
def test_multilabel(self):
hist = synthetic_multilabel()
final_acc = hist.history['val_acc'][-1]
print('final_accuracy:%s' % (final_acc))
self.assertGreater(final_acc, 0.97)
if __name__ == "__main__":
main()
|
[
"sys.path.insert",
"keras.layers.GlobalAveragePooling1D",
"keras.models.Sequential",
"ktrain.get_learner",
"numpy.array",
"keras.layers.Dense",
"unittest.main",
"keras.layers.Embedding"
] |
[((179, 206), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../.."""'], {}), "(0, '../..')\n", (194, 206), False, 'import sys\n'), ((1700, 1711), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1708, 1711), True, 'import numpy as np\n'), ((1720, 1731), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (1728, 1731), True, 'import numpy as np\n'), ((1799, 1811), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1809, 1811), False, 'from keras.models import Sequential\n'), ((2273, 2348), 'ktrain.get_learner', 'ktrain.get_learner', (['model'], {'train_data': '(X, Y)', 'val_data': '(X, Y)', 'batch_size': '(1)'}), '(model, train_data=(X, Y), val_data=(X, Y), batch_size=1)\n', (2291, 2348), False, 'import ktrain\n'), ((2857, 2863), 'unittest.main', 'main', ([], {}), '()\n', (2861, 2863), False, 'from unittest import TestCase, main, skip\n'), ((1826, 1877), 'keras.layers.Embedding', 'Embedding', (['(MAXFEATURES + 1)', '(50)'], {'input_length': 'MAXLEN'}), '(MAXFEATURES + 1, 50, input_length=MAXLEN)\n', (1835, 1877), False, 'from keras.layers import Embedding\n'), ((1939, 1963), 'keras.layers.GlobalAveragePooling1D', 'GlobalAveragePooling1D', ([], {}), '()\n', (1961, 1963), False, 'from keras.layers import GlobalAveragePooling1D\n'), ((1979, 2019), 'keras.layers.Dense', 'Dense', (['NUM_CLASSES'], {'activation': '"""sigmoid"""'}), "(NUM_CLASSES, activation='sigmoid')\n", (1984, 2019), False, 'from keras.layers import Dense\n')]
|
# -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
import pytfa
from pytfa.io import import_matlab_model, load_thermoDB
from pytfa.io.viz import get_reaction_data
from skimpy.core import *
from skimpy.mechanisms import *
from skimpy.utils.namespace import *
from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler
from skimpy.core.parameters import ParameterValuePopulation
from skimpy.core.solution import ODESolutionPopulation
from skimpy.io.generate_from_pytfa import FromPyTFA
from skimpy.utils.general import sanitize_cobra_vars
from skimpy.utils.tabdict import TabDict
from skimpy.analysis.ode.utils import make_flux_fun
from skimpy.analysis.oracle import *
from optlang.exceptions import SolverError
CONCENTRATION_SCALING = 1e6 # 1 mol to 1 mmol
TIME_SCALING = 1 # 1hr
# Parameters of the E. Coli cell
DENSITY = 1200 # g/L
GDW_GWW_RATIO = 0.3 # Assumes 70% Water
flux_scaling_factor = 1e-3 * (GDW_GWW_RATIO * DENSITY) \
* CONCENTRATION_SCALING \
/ TIME_SCALING
"""
Import and curate a model
"""
this_cobra_model = import_matlab_model('../../models/toy_model.mat',
'model')
"""
Make tfa analysis of the model
"""
# Convert to a thermodynamics model
thermo_data = load_thermoDB('../../data/thermo_data.thermodb')
this_pytfa_model = pytfa.ThermoModel(thermo_data, this_cobra_model)
CPLEX = 'optlang-cplex'
this_pytfa_model.solver = CPLEX
# TFA conversion
this_pytfa_model.prepare()
this_pytfa_model.convert(add_displacement=True)
# We choose a flux directionality profile (FDP)
# with minium fluxes of 1e-3
this_bounds = {'DM_13dpg': (-10.0, -2.0),
'DM_2h3oppan': (1e-3, 100.0),
'DM_adp': (-100.0, -1e-3),
'DM_atp': (1e-3, 100.0),
'DM_h': (1e-3, 100.0),
'DM_h2o': (1e-3, 100.0),
'DM_nad': (-100.0, -1e-3),
'DM_nadh': (1e-3, 100.0),
'DM_pep': (1e-3, 100.0),
'ENO': (2.0, 100.0),
'GLYCK': (1e-3, 100.0),
'GLYCK2': (1e-3, 100.0),
'PGK': (1e-3, 100.0),
'PGM': (2.0, 2.0),
'TRSARr': (2.0, 10.0),
'Trp_adp': (-100.0, 100.0),
'Trp_atp': (-100.0, 100.0),
'Trp_h': (-100.0, 100.0),
'Trp_h2o': (-100.0, 100.0),
'Trp_nad': (-100.0, 100.0),
'Trp_nadh': (-100.0, 100.0)}
for k,v in this_bounds.items():
this_pytfa_model.reactions.get_by_id(k).bounds = v
# Find a solution for this FDP
solution = this_pytfa_model.optimize()
# Force a minimal thermodynamic displacement
min_log_displacement = 1e-1
add_min_log_displacement(this_pytfa_model, min_log_displacement)
# Find a solution for the model
solution = this_pytfa_model.optimize()
this_pytfa_model.thermo_displacement.PGM.variable.lb = np.log(1e-1)
this_pytfa_model.thermo_displacement.PGM.variable.ub = np.log(1e-1)
solution = this_pytfa_model.optimize()
"""
Get a Kinetic Model
"""
# Generate the KineticModel
# Define the molecules that should be considered small-molecules
# These molecules will not be accounted explicitly in the kinetic mechanism as
# substrates and products
small_molecules = ['h_c', 'h_e']
model_gen = FromPyTFA(small_molecules=small_molecules)
this_skimpy_model = model_gen.import_model(this_pytfa_model, solution.raw)
"""
Load the reference solutions
"""
fluxes = load_fluxes(solution.raw, this_pytfa_model, this_skimpy_model,
density=DENSITY,
ratio_gdw_gww=GDW_GWW_RATIO,
concentration_scaling=CONCENTRATION_SCALING,
time_scaling=TIME_SCALING)
concentrations = load_concentrations(solution.raw, this_pytfa_model, this_skimpy_model,
concentration_scaling=CONCENTRATION_SCALING)
load_equilibrium_constants(solution.raw, this_pytfa_model, this_skimpy_model,
concentration_scaling=CONCENTRATION_SCALING,
in_place=True)
"""
Sample the kinetic parameters based on linear stablity
"""
this_skimpy_model.parameters.km_substrate_ENO.bounds = (1e-4, 1e-3)
this_skimpy_model.parameters.km_product_ENO.bounds = (1e-4, 1e-3)
this_skimpy_model.prepare(mca=True)
# Compile MCA functions
this_skimpy_model.compile_mca(sim_type=QSSA)
# Initialize parameter sampler
sampling_parameters = SimpleParameterSampler.Parameters(n_samples=1)
sampler = SimpleParameterSampler(sampling_parameters)
# Sample the model
parameter_population = sampler.sample(this_skimpy_model,
fluxes,
concentrations)
parameter_population = ParameterValuePopulation(parameter_population, this_skimpy_model, index=range(1))
"""
Calculate control coefficients
"""
parameter_list = TabDict([(k, p.symbol) for k, p in
this_skimpy_model.parameters.items() if
p.name.startswith('vmax_forward')])
this_skimpy_model.compile_mca(mca_type=SPLIT,sim_type=QSSA, parameter_list=parameter_list)
flux_control_coeff = this_skimpy_model.flux_control_fun(fluxes,
concentrations,
parameter_population)
"""
Integrate the ODEs
"""
this_skimpy_model.compile_ode(sim_type=QSSA)
this_skimpy_model.initial_conditions = TabDict([(k,v) for k,v in concentrations.iteritems()])
solutions = []
this_parameters = parameter_population[0]
vmax_glyck2 = this_parameters['vmax_forward_GLYCK2']
# For each solution calulate the fluxes
calc_fluxes = make_flux_fun(this_skimpy_model, QSSA)
fluxes_pgm_expression = []
this_skimpy_model.parameters = this_parameters
for rel_e in np.logspace(-3, 3, 100):
this_parameters['vmax_forward_GLYCK2'] = vmax_glyck2*rel_e
this_skimpy_model.parameters = this_parameters
sol = this_skimpy_model.solve_ode(np.linspace(0.0, 1.0, 1000),
solver_type='cvode',
rtol=1e-9,
atol=1e-9,
max_steps=1e9,)
solutions.append(sol)
steady_state_fluxes = calc_fluxes(sol.concentrations.iloc[-1], parameters=this_parameters)
fluxes_pgm_expression.append(steady_state_fluxes)
fluxes_pgm_expression = pd.DataFrame(fluxes_pgm_expression)/flux_scaling_factor
|
[
"skimpy.analysis.ode.utils.make_flux_fun",
"skimpy.io.generate_from_pytfa.FromPyTFA",
"pytfa.io.import_matlab_model",
"numpy.log",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler.Parameters",
"pytfa.io.load_thermoDB",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler",
"numpy.linspace",
"numpy.logspace",
"pytfa.ThermoModel"
] |
[((1890, 1948), 'pytfa.io.import_matlab_model', 'import_matlab_model', (['"""../../models/toy_model.mat"""', '"""model"""'], {}), "('../../models/toy_model.mat', 'model')\n", (1909, 1948), False, 'from pytfa.io import import_matlab_model, load_thermoDB\n'), ((2080, 2128), 'pytfa.io.load_thermoDB', 'load_thermoDB', (['"""../../data/thermo_data.thermodb"""'], {}), "('../../data/thermo_data.thermodb')\n", (2093, 2128), False, 'from pytfa.io import import_matlab_model, load_thermoDB\n'), ((2148, 2196), 'pytfa.ThermoModel', 'pytfa.ThermoModel', (['thermo_data', 'this_cobra_model'], {}), '(thermo_data, this_cobra_model)\n', (2165, 2196), False, 'import pytfa\n'), ((3807, 3818), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (3813, 3818), True, 'import numpy as np\n'), ((3875, 3886), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (3881, 3886), True, 'import numpy as np\n'), ((4203, 4245), 'skimpy.io.generate_from_pytfa.FromPyTFA', 'FromPyTFA', ([], {'small_molecules': 'small_molecules'}), '(small_molecules=small_molecules)\n', (4212, 4245), False, 'from skimpy.io.generate_from_pytfa import FromPyTFA\n'), ((5357, 5403), 'skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler.Parameters', 'SimpleParameterSampler.Parameters', ([], {'n_samples': '(1)'}), '(n_samples=1)\n', (5390, 5403), False, 'from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler\n'), ((5414, 5457), 'skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler', 'SimpleParameterSampler', (['sampling_parameters'], {}), '(sampling_parameters)\n', (5436, 5457), False, 'from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler\n'), ((6605, 6643), 'skimpy.analysis.ode.utils.make_flux_fun', 'make_flux_fun', (['this_skimpy_model', 'QSSA'], {}), '(this_skimpy_model, QSSA)\n', (6618, 6643), False, 'from skimpy.analysis.ode.utils import make_flux_fun\n'), ((6734, 6757), 'numpy.logspace', 'np.logspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (6745, 6757), True, 'import numpy as np\n'), ((6913, 6940), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(1000)'], {}), '(0.0, 1.0, 1000)\n', (6924, 6940), True, 'import numpy as np\n')]
|
"""
Usage Instructions:
10-shot sinusoid:
python main.py --datasource=sinusoid --logdir=logs/sine/ --metatrain_iterations=70000 --norm=None --update_batch_size=10
10-shot sinusoid baselines:
python main.py --datasource=sinusoid --logdir=logs/sine/ --pretrain_iterations=70000 --metatrain_iterations=0 --norm=None --update_batch_size=10 --baseline=oracle
python main.py --datasource=sinusoid --logdir=logs/sine/ --pretrain_iterations=70000 --metatrain_iterations=0 --norm=None --update_batch_size=10
5-way, 1-shot omniglot:
python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=32 --update_batch_size=1 --update_lr=0.4 --num_updates=1 --logdir=logs/omniglot5way/
20-way, 1-shot omniglot:
python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=16 --update_batch_size=1 --num_classes=20 --update_lr=0.1 --num_updates=5 --logdir=logs/omniglot20way/
5-way 1-shot mini imagenet:
python main.py --datasource=miniimagenet --metatrain_iterations=60000 --meta_batch_size=4 --update_batch_size=1 --update_lr=0.01 --num_updates=5 --num_classes=5 --logdir=logs/miniimagenet1shot/ --num_filters=32 --max_pool=True
5-way 5-shot mini imagenet:
python main.py --datasource=miniimagenet --metatrain_iterations=60000 --meta_batch_size=4 --update_batch_size=5 --update_lr=0.01 --num_updates=5 --num_classes=5 --logdir=logs/miniimagenet5shot/ --num_filters=32 --max_pool=True
To run evaluation, use the '--train=False' flag and the '--test_set=True' flag to use the test set.
For omniglot and miniimagenet training, acquire the dataset online, put it in the correspoding data directory, and see the python script instructions in that directory to preprocess the data.
Note that better sinusoid results can be achieved by using a larger network.
"""
import csv
import numpy as np
import pickle
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from data_generator import DataGenerator
from maml import MAML
from tensorflow.python.platform import flags
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
FLAGS = flags.FLAGS
## Dataset/method options
flags.DEFINE_string('datasource', 'sinusoid', 'sinusoid or omniglot or miniimagenet')
flags.DEFINE_integer('num_classes', 5, 'number of classes used in classification (e.g. 5-way classification).')
# oracle means task id is input (only suitable for sinusoid)
# flags.DEFINE_string('baseline', "oracle", 'oracle, or None')
flags.DEFINE_string('baseline', None, 'oracle, or None')
## Training options
flags.DEFINE_integer('pretrain_iterations', 0, 'number of pre-training iterations.')
flags.DEFINE_integer('metatrain_iterations', 15000, 'number of metatraining iterations.') # 15k for omniglot, 50k for sinusoid
flags.DEFINE_integer('meta_batch_size', 25, 'number of tasks sampled per meta-update')
flags.DEFINE_float('meta_lr', 0.001, 'the base learning rate of the generator')
flags.DEFINE_integer('update_batch_size', 5, 'number of examples used for inner gradient update (K for K-shot learning).')
flags.DEFINE_float('update_lr', 1e-3, 'step size alpha for inner gradient update.') # 0.1 for omniglot
# flags.DEFINE_float('update_lr', 1e-2, 'step size alpha for inner gradient update.') # 0.1 for omniglot
flags.DEFINE_integer('num_updates', 1, 'number of inner gradient updates during training.')
## Model options
flags.DEFINE_string('norm', 'batch_norm', 'batch_norm, layer_norm, or None')
flags.DEFINE_integer('num_filters', 64, 'number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot.')
flags.DEFINE_bool('conv', True, 'whether or not to use a convolutional network, only applicable in some cases')
flags.DEFINE_bool('max_pool', False, 'Whether or not to use max pooling rather than strided convolutions')
flags.DEFINE_bool('stop_grad', False, 'if True, do not use second derivatives in meta-optimization (for speed)')
flags.DEFINE_float('keep_prob', 0.5, 'if not None, used as keep_prob for all layers')
flags.DEFINE_bool('drop_connect', True, 'if True, use dropconnect, otherwise, use dropout')
# flags.DEFINE_float('keep_prob', None, 'if not None, used as keep_prob for all layers')
## Logging, saving, and testing options
flags.DEFINE_bool('log', True, 'if false, do not log summaries, for debugging code.')
flags.DEFINE_string('logdir', '/tmp/data', 'directory for summaries and checkpoints.')
flags.DEFINE_bool('resume', False, 'resume training if there is a model available')
flags.DEFINE_bool('train', True, 'True to train, False to test.')
flags.DEFINE_integer('test_iter', -1, 'iteration to load model (-1 for latest model)')
flags.DEFINE_bool('test_set', False, 'Set to true to test on the the test set, False for the validation set.')
flags.DEFINE_integer('train_update_batch_size', -1, 'number of examples used for gradient update during training (use if you want to test with a different number).')
flags.DEFINE_float('train_update_lr', -1, 'value of inner gradient step step during training. (use if you want to test with a different value)') # 0.1 for omniglot
def train(model, saver, sess, exp_string, data_generator, resume_itr=0):
SUMMARY_INTERVAL = 100
SAVE_INTERVAL = 1000
if FLAGS.datasource == 'sinusoid':
PRINT_INTERVAL = 1000
TEST_PRINT_INTERVAL = PRINT_INTERVAL*5
else:
PRINT_INTERVAL = 100
TEST_PRINT_INTERVAL = PRINT_INTERVAL*5
if FLAGS.log:
train_writer = tf.summary.FileWriter(FLAGS.logdir + '/' + exp_string, sess.graph)
print('Done initializing, starting training.')
prelosses, postlosses = [], []
num_classes = data_generator.num_classes # for classification, 1 otherwise
multitask_weights, reg_weights = [], []
for itr in range(resume_itr, FLAGS.pretrain_iterations + FLAGS.metatrain_iterations):
feed_dict = {}
if 'generate' in dir(data_generator):
batch_x, batch_y, amp, phase = data_generator.generate()
if FLAGS.baseline == 'oracle':
batch_x = np.concatenate([batch_x, np.zeros([batch_x.shape[0], batch_x.shape[1], 2])], 2)
for i in range(FLAGS.meta_batch_size):
batch_x[i, :, 1] = amp[i]
batch_x[i, :, 2] = phase[i]
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:, num_classes*FLAGS.update_batch_size:, :] # b used for testing
labelb = batch_y[:, num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb}
if itr < FLAGS.pretrain_iterations:
input_tensors = [model.pretrain_op]
else:
input_tensors = [model.metatrain_op]
if (itr % SUMMARY_INTERVAL == 0 or itr % PRINT_INTERVAL == 0):
input_tensors.extend([model.summ_op, model.total_loss1, model.total_losses2[FLAGS.num_updates-1]])
if model.classification:
input_tensors.extend([model.total_accuracy1, model.total_accuracies2[FLAGS.num_updates-1]])
result = sess.run(input_tensors, feed_dict)
if itr % SUMMARY_INTERVAL == 0:
prelosses.append(result[-2])
if FLAGS.log:
train_writer.add_summary(result[1], itr)
postlosses.append(result[-1])
if (itr!=0) and itr % PRINT_INTERVAL == 0:
if itr < FLAGS.pretrain_iterations:
print_str = 'Pretrain Iteration ' + str(itr)
else:
print_str = 'Iteration ' + str(itr - FLAGS.pretrain_iterations)
print_str += ': ' + str(np.mean(prelosses)) + ', ' + str(np.mean(postlosses))
print(print_str)
prelosses, postlosses = [], []
if (itr!=0) and itr % SAVE_INTERVAL == 0:
saver.save(sess, FLAGS.logdir + '/' + exp_string + '/model' + str(itr))
# sinusoid is infinite data, so no need to test on meta-validation set.
if (itr!=0) and itr % TEST_PRINT_INTERVAL == 0 and FLAGS.datasource !='sinusoid':
if 'generate' not in dir(data_generator):
feed_dict = {}
if model.classification:
input_tensors = [model.metaval_total_accuracy1, model.metaval_total_accuracies2[FLAGS.num_updates-1], model.summ_op]
else:
input_tensors = [model.metaval_total_loss1, model.metaval_total_losses2[FLAGS.num_updates-1], model.summ_op]
else:
batch_x, batch_y, amp, phase = data_generator.generate(train=False)
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:, num_classes*FLAGS.update_batch_size:, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
labelb = batch_y[:, num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb, model.meta_lr: 0.0}
if model.classification:
input_tensors = [model.total_accuracy1, model.total_accuracies2[FLAGS.num_updates-1]]
else:
input_tensors = [model.total_loss1, model.total_losses2[FLAGS.num_updates-1]]
result = sess.run(input_tensors, feed_dict)
print('Validation results: ' + str(result[0]) + ', ' + str(result[1]))
saver.save(sess, FLAGS.logdir + '/' + exp_string + '/model' + str(itr))
# calculated for omniglot
NUM_TEST_POINTS = 600
def generate_test():
batch_size = 2
num_points = 101
# amp = np.array([3, 5])
# phase = np.array([0, 2.3])
amp = np.array([5, 3])
phase = np.array([2.3, 0])
outputs = np.zeros([batch_size, num_points, 1])
init_inputs = np.zeros([batch_size, num_points, 1])
for func in range(batch_size):
init_inputs[func, :, 0] = np.linspace(-5, 5, num_points)
outputs[func] = amp[func] * np.sin(init_inputs[func] - phase[func])
if FLAGS.baseline == 'oracle': # NOTE - this flag is specific to sinusoid
init_inputs = np.concatenate([init_inputs, np.zeros([init_inputs.shape[0], init_inputs.shape[1], 2])], 2)
for i in range(batch_size):
init_inputs[i, :, 1] = amp[i]
init_inputs[i, :, 2] = phase[i]
return init_inputs, outputs, amp, phase
def test_line_limit_Baye(model, sess, exp_string, mc_simulation=20, points_train=10, random_seed=1999):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
np.random.seed(random_seed)
index = np.random.choice(inputs_all.shape[1], [inputs_all.shape[0], points_train], replace=False)
inputs_a = np.zeros([inputs_all.shape[0], points_train, inputs_all.shape[2]])
outputs_a = np.zeros([outputs_all.shape[0], points_train, outputs_all.shape[2]])
for line in range(len(index)):
inputs_a[line] = inputs_all[line, index[line], :]
outputs_a[line] = outputs_all[line, index[line], :]
feed_dict_line = {model.inputa: inputs_a, model.inputb: inputs_all, model.labela: outputs_a, model.labelb: outputs_all, model.meta_lr: 0.0}
mc_prediction = []
for mc_iter in range(mc_simulation):
predictions_all = sess.run(model.outputbs, feed_dict_line)
mc_prediction.append(np.array(predictions_all))
print("total mc simulation: ", mc_simulation)
print("shape of predictions_all is: ", predictions_all[0].shape)
prob_mean = np.nanmean(mc_prediction, axis=0)
prob_variance = np.var(mc_prediction, axis=0)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
# for update_step in range(len(predictions_all)):
for update_step in [0, len(predictions_all)-1]:
X = inputs_all[line, ..., 0].squeeze()
mu = prob_mean[update_step][line, ...].squeeze()
uncertainty = np.sqrt(prob_variance[update_step][line, ...].squeeze())
plt.plot(X, mu, "--", label="update_step_{:d}".format(update_step))
plt.fill_between(X, mu + uncertainty, mu - uncertainty, alpha=0.1)
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}_numtrain_{1:d}_seed_{2:d}.png'.format(line, points_train, random_seed)
plt.plot(inputs_a[line, :, 0], outputs_a[line, :, 0], "b*", label="training points")
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
def test_line_limit(model, sess, exp_string, num_train=10, random_seed=1999):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
np.random.seed(random_seed)
index = np.random.choice(inputs_all.shape[1], [inputs_all.shape[0], num_train], replace=False)
inputs_a = np.zeros([inputs_all.shape[0], num_train, inputs_all.shape[2]])
outputs_a = np.zeros([outputs_all.shape[0], num_train, outputs_all.shape[2]])
for line in range(len(index)):
inputs_a[line] = inputs_all[line, index[line], :]
outputs_a[line] = outputs_all[line, index[line], :]
feed_dict_line = {model.inputa: inputs_a, model.inputb: inputs_all, model.labela: outputs_a, model.labelb: outputs_all, model.meta_lr: 0.0}
predictions_all = sess.run([model.outputas, model.outputbs], feed_dict_line)
print("shape of predictions_all is: ", predictions_all[0].shape)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
for update_step in range(len(predictions_all[1])):
plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[1][update_step][line, ...].squeeze(), "--", label="update_step_{:d}".format(update_step))
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}_numtrain_{1:d}_seed_{2:d}.png'.format(line, num_train, random_seed)
plt.plot(inputs_a[line, :, 0], outputs_a[line, :, 0], "b*", label="training points")
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
def test_line(model, sess, exp_string):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
feed_dict_line = {model.inputa: inputs_all, model.inputb: inputs_all, model.labela: outputs_all, model.labelb: outputs_all, model.meta_lr: 0.0}
predictions_all = sess.run([model.outputas, model.outputbs], feed_dict_line)
print("shape of predictions_all is: ", predictions_all[0].shape)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
for update_step in range(len(predictions_all[1])):
plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[1][update_step][line, ...].squeeze(), "--", label="update_step_{:d}".format(update_step))
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}.png'.format(line)
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
# for line in range(len(inputs_all)):
# plt.figure()
# plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
#
# plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[0][line, ...].squeeze(), "--",
# label="initial")
# plt.legend()
#
# out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
# FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'init_line_{0:d}.png'.format(line)
#
# plt.savefig(out_figure, bbox_inches="tight", dpi=300)
# plt.close()
def test(model, saver, sess, exp_string, data_generator, test_num_updates=None):
num_classes = data_generator.num_classes # for classification, 1 otherwise
np.random.seed(1)
random.seed(1)
metaval_accuracies = []
for _ in range(NUM_TEST_POINTS):
if 'generate' not in dir(data_generator):
feed_dict = {}
feed_dict = {model.meta_lr : 0.0}
else:
batch_x, batch_y, amp, phase = data_generator.generate(train=False)
if FLAGS.baseline == 'oracle': # NOTE - this flag is specific to sinusoid
batch_x = np.concatenate([batch_x, np.zeros([batch_x.shape[0], batch_x.shape[1], 2])], 2)
batch_x[0, :, 1] = amp[0]
batch_x[0, :, 2] = phase[0]
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:,num_classes*FLAGS.update_batch_size:, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
labelb = batch_y[:,num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb, model.meta_lr: 0.0}
if model.classification:
result = sess.run([model.metaval_total_accuracy1] + model.metaval_total_accuracies2, feed_dict)
else: # this is for sinusoid
result = sess.run([model.total_loss1] + model.total_losses2, feed_dict)
metaval_accuracies.append(result)
metaval_accuracies = np.array(metaval_accuracies)
means = np.mean(metaval_accuracies, 0)
stds = np.std(metaval_accuracies, 0)
ci95 = 1.96*stds/np.sqrt(NUM_TEST_POINTS)
print('Mean validation accuracy/loss, stddev, and confidence intervals')
print((means, stds, ci95))
out_filename = FLAGS.logdir +'/'+ exp_string + '/' + 'test_ubs' + str(FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + '.csv'
out_pkl = FLAGS.logdir +'/'+ exp_string + '/' + 'test_ubs' + str(FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + '.pkl'
with open(out_pkl, 'wb') as f:
pickle.dump({'mses': metaval_accuracies}, f)
with open(out_filename, 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(['update'+str(i) for i in range(len(means))])
writer.writerow(means)
writer.writerow(stds)
writer.writerow(ci95)
def main():
if FLAGS.datasource == 'sinusoid':
if FLAGS.train:
test_num_updates = 5
else:
test_num_updates = 10
else:
if FLAGS.datasource == 'miniimagenet':
if FLAGS.train == True:
test_num_updates = 1 # eval on at least one update during training
else:
test_num_updates = 10
else:
test_num_updates = 10
if FLAGS.train == False:
orig_meta_batch_size = FLAGS.meta_batch_size
# always use meta batch size of 1 when testing.
FLAGS.meta_batch_size = 1
if FLAGS.datasource == 'sinusoid':
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size)
else:
if FLAGS.metatrain_iterations == 0 and FLAGS.datasource == 'miniimagenet':
assert FLAGS.meta_batch_size == 1
assert FLAGS.update_batch_size == 1
data_generator = DataGenerator(1, FLAGS.meta_batch_size) # only use one datapoint,
else:
if FLAGS.datasource == 'miniimagenet': # TODO - use 15 val examples for imagenet?
if FLAGS.train:
data_generator = DataGenerator(FLAGS.update_batch_size+15, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
else:
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
else:
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
dim_output = data_generator.dim_output
if FLAGS.baseline == 'oracle':
assert FLAGS.datasource == 'sinusoid'
dim_input = 3
FLAGS.pretrain_iterations += FLAGS.metatrain_iterations
FLAGS.metatrain_iterations = 0
else:
dim_input = data_generator.dim_input
if FLAGS.datasource == 'miniimagenet' or FLAGS.datasource == 'omniglot':
tf_data_load = True
num_classes = data_generator.num_classes
if FLAGS.train: # only construct training model if needed
random.seed(5)
image_tensor, label_tensor = data_generator.make_data_tensor()
inputa = tf.slice(image_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
inputb = tf.slice(image_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
labela = tf.slice(label_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
labelb = tf.slice(label_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
input_tensors = {'inputa': inputa, 'inputb': inputb, 'labela': labela, 'labelb': labelb}
random.seed(6)
image_tensor, label_tensor = data_generator.make_data_tensor(train=False)
inputa = tf.slice(image_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
inputb = tf.slice(image_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
labela = tf.slice(label_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
labelb = tf.slice(label_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
metaval_input_tensors = {'inputa': inputa, 'inputb': inputb, 'labela': labela, 'labelb': labelb}
else:
tf_data_load = False
input_tensors = None
model = MAML(dim_input, dim_output, test_num_updates=test_num_updates)
if FLAGS.train or not tf_data_load:
model.construct_model(input_tensors=input_tensors, prefix='metatrain_')
if tf_data_load:
model.construct_model(input_tensors=metaval_input_tensors, prefix='metaval_')
model.summ_op = tf.summary.merge_all()
saver = loader = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES), max_to_keep=10)
sess = tf.InteractiveSession()
if FLAGS.train == False:
# change to original meta batch size when loading model.
FLAGS.meta_batch_size = orig_meta_batch_size
if FLAGS.train_update_batch_size == -1:
FLAGS.train_update_batch_size = FLAGS.update_batch_size
if FLAGS.train_update_lr == -1:
FLAGS.train_update_lr = FLAGS.update_lr
exp_string = 'cls_'+str(FLAGS.num_classes)+'.mbs_'+str(FLAGS.meta_batch_size) + '.ubs_' + str(FLAGS.train_update_batch_size) + '.numstep' + str(FLAGS.num_updates) + '.updatelr' + str(FLAGS.train_update_lr)
if FLAGS.num_filters != 64:
exp_string += 'hidden' + str(FLAGS.num_filters)
if FLAGS.max_pool:
exp_string += 'maxpool'
if FLAGS.stop_grad:
exp_string += 'stopgrad'
if FLAGS.baseline:
exp_string += FLAGS.baseline
if FLAGS.norm == 'batch_norm':
exp_string += 'batchnorm'
elif FLAGS.norm == 'layer_norm':
exp_string += 'layernorm'
elif FLAGS.norm == 'None':
exp_string += 'nonorm'
else:
print('Norm setting not recognized.')
if FLAGS.pretrain_iterations != 0:
exp_string += '.pt' + str(FLAGS.pretrain_iterations)
if FLAGS.metatrain_iterations != 0:
exp_string += '.mt' + str(FLAGS.metatrain_iterations)
if FLAGS.keep_prob is not None:
exp_string += "kp{:.2f}".format(FLAGS.keep_prob)
if FLAGS.drop_connect is True:
exp_string += ".dropconn"
resume_itr = 0
model_file = None
tf.global_variables_initializer().run()
tf.train.start_queue_runners()
if FLAGS.resume or not FLAGS.train:
if exp_string == 'cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000':
model_file = 'logs/sine//cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000/model69999'
else:
model_file = tf.train.latest_checkpoint(FLAGS.logdir + '/' + exp_string)
# model_file = 'logs/sine//cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000/model69999'
if FLAGS.test_iter > 0:
model_file = model_file[:model_file.index('model')] + 'model' + str(FLAGS.test_iter)
if model_file:
ind1 = model_file.index('model')
resume_itr = int(model_file[ind1+5:])
print("Restoring model weights from " + model_file)
saver.restore(sess, model_file)
if FLAGS.train:
train(model, saver, sess, exp_string, data_generator, resume_itr)
else:
# test_line(model, sess, exp_string)
# test_line_limit(model, sess, exp_string, num_train=2, random_seed=1999)
test_line_limit_Baye(model, sess, exp_string, mc_simulation=20, points_train=10, random_seed=1999)
# test(model, saver, sess, exp_string, data_generator, test_num_updates)
if __name__ == "__main__":
main()
# import matplotlib.pyplot as plt
# plt.plot(inputa.squeeze(), labela.squeeze(), "*")
# re = sess.run(model.result, feed_dict)
# plt.plot(inputa.squeeze(), re[0].squeeze(), "*")
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/preda.png", bbox_inches="tight", dpi=300)
# for i in range(len(re[1])):
# plt.figure()
# plt.plot(inputb.squeeze(), labelb.squeeze(), "*")
# plt.plot(inputb.squeeze(), re[1][i].squeeze(), "*")
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/predb_{:d}.png".format(i), bbox_inches="tight", dpi=300)
# plt.close()
# plt.figure()
# plt.imshow(metaval_accuracies)
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/losses.png", bbox_inches="tight", dpi=300)
## Generate all sine
# def generate_test():
# amp_range = [0.1, 5.0]
# phase_range = [0, np.pi]
# batch_size = 100
# num_points = 101
# # amp = np.array([3, 5])
# # phase = np.array([0, 2.3])
# amp = np.random.uniform(amp_range[0], amp_range[1], [batch_size])
# phase = np.random.uniform(phase_range[0], phase_range[1], [batch_size])
# outputs = np.zeros([batch_size, num_points, 1])
# init_inputs = np.zeros([batch_size, num_points, 1])
# for func in range(batch_size):
# init_inputs[func, :, 0] = np.linspace(-5, 5, num_points)
# outputs[func] = amp[func] * np.sin(init_inputs[func] - phase[func])
# return init_inputs, outputs, amp, phase
# init_inputs, outputs, amp, phase = generate_test()
# plt.figure()
# for i in range(len(init_inputs)):
# plt.plot(init_inputs[i].squeeze(), outputs[i].squeeze())
|
[
"numpy.sqrt",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.nanmean",
"numpy.sin",
"numpy.mean",
"tensorflow.slice",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.linspace",
"numpy.random.seed",
"tensorflow.summary.merge_all",
"tensorflow.python.platform.flags.DEFINE_integer",
"tensorflow.InteractiveSession",
"matplotlib.pyplot.savefig",
"numpy.random.choice",
"csv.writer",
"tensorflow.train.start_queue_runners",
"data_generator.DataGenerator",
"numpy.std",
"tensorflow.python.platform.flags.DEFINE_float",
"tensorflow.train.latest_checkpoint",
"tensorflow.summary.FileWriter",
"matplotlib.pyplot.legend",
"maml.MAML",
"pickle.dump",
"tensorflow.python.platform.flags.DEFINE_string",
"random.seed",
"tensorflow.global_variables_initializer",
"numpy.zeros",
"matplotlib.pyplot.figure",
"tensorflow.python.platform.flags.DEFINE_bool",
"numpy.var",
"tensorflow.get_collection"
] |
[((2210, 2299), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""datasource"""', '"""sinusoid"""', '"""sinusoid or omniglot or miniimagenet"""'], {}), "('datasource', 'sinusoid',\n 'sinusoid or omniglot or miniimagenet')\n", (2229, 2299), False, 'from tensorflow.python.platform import flags\n'), ((2296, 2411), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_classes"""', '(5)', '"""number of classes used in classification (e.g. 5-way classification)."""'], {}), "('num_classes', 5,\n 'number of classes used in classification (e.g. 5-way classification).')\n", (2316, 2411), False, 'from tensorflow.python.platform import flags\n'), ((2532, 2588), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""baseline"""', 'None', '"""oracle, or None"""'], {}), "('baseline', None, 'oracle, or None')\n", (2551, 2588), False, 'from tensorflow.python.platform import flags\n'), ((2610, 2698), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""pretrain_iterations"""', '(0)', '"""number of pre-training iterations."""'], {}), "('pretrain_iterations', 0,\n 'number of pre-training iterations.')\n", (2630, 2698), False, 'from tensorflow.python.platform import flags\n'), ((2695, 2788), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""metatrain_iterations"""', '(15000)', '"""number of metatraining iterations."""'], {}), "('metatrain_iterations', 15000,\n 'number of metatraining iterations.')\n", (2715, 2788), False, 'from tensorflow.python.platform import flags\n'), ((2822, 2912), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""meta_batch_size"""', '(25)', '"""number of tasks sampled per meta-update"""'], {}), "('meta_batch_size', 25,\n 'number of tasks sampled per meta-update')\n", (2842, 2912), False, 'from tensorflow.python.platform import flags\n'), ((2909, 2988), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""meta_lr"""', '(0.001)', '"""the base learning rate of the generator"""'], {}), "('meta_lr', 0.001, 'the base learning rate of the generator')\n", (2927, 2988), False, 'from tensorflow.python.platform import flags\n'), ((2989, 3120), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""update_batch_size"""', '(5)', '"""number of examples used for inner gradient update (K for K-shot learning)."""'], {}), "('update_batch_size', 5,\n 'number of examples used for inner gradient update (K for K-shot learning).'\n )\n", (3009, 3120), False, 'from tensorflow.python.platform import flags\n'), ((3112, 3200), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""update_lr"""', '(0.001)', '"""step size alpha for inner gradient update."""'], {}), "('update_lr', 0.001,\n 'step size alpha for inner gradient update.')\n", (3130, 3200), False, 'from tensorflow.python.platform import flags\n'), ((3320, 3415), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_updates"""', '(1)', '"""number of inner gradient updates during training."""'], {}), "('num_updates', 1,\n 'number of inner gradient updates during training.')\n", (3340, 3415), False, 'from tensorflow.python.platform import flags\n'), ((3430, 3506), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""norm"""', '"""batch_norm"""', '"""batch_norm, layer_norm, or None"""'], {}), "('norm', 'batch_norm', 'batch_norm, layer_norm, or None')\n", (3449, 3506), False, 'from tensorflow.python.platform import flags\n'), ((3507, 3625), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_filters"""', '(64)', '"""number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot."""'], {}), "('num_filters', 64,\n 'number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot.')\n", (3527, 3625), False, 'from tensorflow.python.platform import flags\n'), ((3622, 3742), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""conv"""', '(True)', '"""whether or not to use a convolutional network, only applicable in some cases"""'], {}), "('conv', True,\n 'whether or not to use a convolutional network, only applicable in some cases'\n )\n", (3639, 3742), False, 'from tensorflow.python.platform import flags\n'), ((3734, 3844), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""max_pool"""', '(False)', '"""Whether or not to use max pooling rather than strided convolutions"""'], {}), "('max_pool', False,\n 'Whether or not to use max pooling rather than strided convolutions')\n", (3751, 3844), False, 'from tensorflow.python.platform import flags\n'), ((3841, 3957), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""stop_grad"""', '(False)', '"""if True, do not use second derivatives in meta-optimization (for speed)"""'], {}), "('stop_grad', False,\n 'if True, do not use second derivatives in meta-optimization (for speed)')\n", (3858, 3957), False, 'from tensorflow.python.platform import flags\n'), ((3954, 4043), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""keep_prob"""', '(0.5)', '"""if not None, used as keep_prob for all layers"""'], {}), "('keep_prob', 0.5,\n 'if not None, used as keep_prob for all layers')\n", (3972, 4043), False, 'from tensorflow.python.platform import flags\n'), ((4040, 4135), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""drop_connect"""', '(True)', '"""if True, use dropconnect, otherwise, use dropout"""'], {}), "('drop_connect', True,\n 'if True, use dropconnect, otherwise, use dropout')\n", (4057, 4135), False, 'from tensorflow.python.platform import flags\n'), ((4262, 4351), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""log"""', '(True)', '"""if false, do not log summaries, for debugging code."""'], {}), "('log', True,\n 'if false, do not log summaries, for debugging code.')\n", (4279, 4351), False, 'from tensorflow.python.platform import flags\n'), ((4348, 4438), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""logdir"""', '"""/tmp/data"""', '"""directory for summaries and checkpoints."""'], {}), "('logdir', '/tmp/data',\n 'directory for summaries and checkpoints.')\n", (4367, 4438), False, 'from tensorflow.python.platform import flags\n'), ((4435, 4522), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""resume"""', '(False)', '"""resume training if there is a model available"""'], {}), "('resume', False,\n 'resume training if there is a model available')\n", (4452, 4522), False, 'from tensorflow.python.platform import flags\n'), ((4519, 4584), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""train"""', '(True)', '"""True to train, False to test."""'], {}), "('train', True, 'True to train, False to test.')\n", (4536, 4584), False, 'from tensorflow.python.platform import flags\n'), ((4585, 4675), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""test_iter"""', '(-1)', '"""iteration to load model (-1 for latest model)"""'], {}), "('test_iter', -1,\n 'iteration to load model (-1 for latest model)')\n", (4605, 4675), False, 'from tensorflow.python.platform import flags\n'), ((4672, 4786), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""test_set"""', '(False)', '"""Set to true to test on the the test set, False for the validation set."""'], {}), "('test_set', False,\n 'Set to true to test on the the test set, False for the validation set.')\n", (4689, 4786), False, 'from tensorflow.python.platform import flags\n'), ((4783, 4957), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""train_update_batch_size"""', '(-1)', '"""number of examples used for gradient update during training (use if you want to test with a different number)."""'], {}), "('train_update_batch_size', -1,\n 'number of examples used for gradient update during training (use if you want to test with a different number).'\n )\n", (4803, 4957), False, 'from tensorflow.python.platform import flags\n'), ((4949, 5102), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""train_update_lr"""', '(-1)', '"""value of inner gradient step step during training. (use if you want to test with a different value)"""'], {}), "('train_update_lr', -1,\n 'value of inner gradient step step during training. (use if you want to test with a different value)'\n )\n", (4967, 5102), False, 'from tensorflow.python.platform import flags\n'), ((9817, 9833), 'numpy.array', 'np.array', (['[5, 3]'], {}), '([5, 3])\n', (9825, 9833), True, 'import numpy as np\n'), ((9846, 9864), 'numpy.array', 'np.array', (['[2.3, 0]'], {}), '([2.3, 0])\n', (9854, 9864), True, 'import numpy as np\n'), ((9879, 9916), 'numpy.zeros', 'np.zeros', (['[batch_size, num_points, 1]'], {}), '([batch_size, num_points, 1])\n', (9887, 9916), True, 'import numpy as np\n'), ((9935, 9972), 'numpy.zeros', 'np.zeros', (['[batch_size, num_points, 1]'], {}), '([batch_size, num_points, 1])\n', (9943, 9972), True, 'import numpy as np\n'), ((10688, 10715), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (10702, 10715), True, 'import numpy as np\n'), ((10728, 10821), 'numpy.random.choice', 'np.random.choice', (['inputs_all.shape[1]', '[inputs_all.shape[0], points_train]'], {'replace': '(False)'}), '(inputs_all.shape[1], [inputs_all.shape[0], points_train],\n replace=False)\n', (10744, 10821), True, 'import numpy as np\n'), ((10833, 10899), 'numpy.zeros', 'np.zeros', (['[inputs_all.shape[0], points_train, inputs_all.shape[2]]'], {}), '([inputs_all.shape[0], points_train, inputs_all.shape[2]])\n', (10841, 10899), True, 'import numpy as np\n'), ((10916, 10984), 'numpy.zeros', 'np.zeros', (['[outputs_all.shape[0], points_train, outputs_all.shape[2]]'], {}), '([outputs_all.shape[0], points_train, outputs_all.shape[2]])\n', (10924, 10984), True, 'import numpy as np\n'), ((11607, 11640), 'numpy.nanmean', 'np.nanmean', (['mc_prediction'], {'axis': '(0)'}), '(mc_prediction, axis=0)\n', (11617, 11640), True, 'import numpy as np\n'), ((11661, 11690), 'numpy.var', 'np.var', (['mc_prediction'], {'axis': '(0)'}), '(mc_prediction, axis=0)\n', (11667, 11690), True, 'import numpy as np\n'), ((12927, 12954), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (12941, 12954), True, 'import numpy as np\n'), ((12967, 13057), 'numpy.random.choice', 'np.random.choice', (['inputs_all.shape[1]', '[inputs_all.shape[0], num_train]'], {'replace': '(False)'}), '(inputs_all.shape[1], [inputs_all.shape[0], num_train],\n replace=False)\n', (12983, 13057), True, 'import numpy as np\n'), ((13069, 13132), 'numpy.zeros', 'np.zeros', (['[inputs_all.shape[0], num_train, inputs_all.shape[2]]'], {}), '([inputs_all.shape[0], num_train, inputs_all.shape[2]])\n', (13077, 13132), True, 'import numpy as np\n'), ((13149, 13214), 'numpy.zeros', 'np.zeros', (['[outputs_all.shape[0], num_train, outputs_all.shape[2]]'], {}), '([outputs_all.shape[0], num_train, outputs_all.shape[2]])\n', (13157, 13214), True, 'import numpy as np\n'), ((16413, 16430), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (16427, 16430), True, 'import numpy as np\n'), ((16435, 16449), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (16446, 16449), False, 'import random\n'), ((17772, 17800), 'numpy.array', 'np.array', (['metaval_accuracies'], {}), '(metaval_accuracies)\n', (17780, 17800), True, 'import numpy as np\n'), ((17813, 17843), 'numpy.mean', 'np.mean', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (17820, 17843), True, 'import numpy as np\n'), ((17855, 17884), 'numpy.std', 'np.std', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (17861, 17884), True, 'import numpy as np\n'), ((22125, 22187), 'maml.MAML', 'MAML', (['dim_input', 'dim_output'], {'test_num_updates': 'test_num_updates'}), '(dim_input, dim_output, test_num_updates=test_num_updates)\n', (22129, 22187), False, 'from maml import MAML\n'), ((22435, 22457), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (22455, 22457), True, 'import tensorflow as tf\n'), ((22576, 22599), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (22597, 22599), True, 'import tensorflow as tf\n'), ((24126, 24156), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {}), '()\n', (24154, 24156), True, 'import tensorflow as tf\n'), ((5483, 5549), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(FLAGS.logdir + '/' + exp_string)", 'sess.graph'], {}), "(FLAGS.logdir + '/' + exp_string, sess.graph)\n", (5504, 5549), True, 'import tensorflow as tf\n'), ((10042, 10072), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', 'num_points'], {}), '(-5, 5, num_points)\n', (10053, 10072), True, 'import numpy as np\n'), ((11740, 11752), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (11750, 11752), True, 'import matplotlib.pyplot as plt\n'), ((12347, 12359), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12357, 12359), True, 'import matplotlib.pyplot as plt\n'), ((12607, 12696), 'matplotlib.pyplot.plot', 'plt.plot', (['inputs_a[line, :, 0]', 'outputs_a[line, :, 0]', '"""b*"""'], {'label': '"""training points"""'}), "(inputs_a[line, :, 0], outputs_a[line, :, 0], 'b*', label=\n 'training points')\n", (12615, 12696), True, 'import matplotlib.pyplot as plt\n'), ((12701, 12754), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (12712, 12754), True, 'import matplotlib.pyplot as plt\n'), ((12763, 12774), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12772, 12774), True, 'import matplotlib.pyplot as plt\n'), ((13712, 13724), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13722, 13724), True, 'import matplotlib.pyplot as plt\n'), ((14073, 14085), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (14083, 14085), True, 'import matplotlib.pyplot as plt\n'), ((14330, 14419), 'matplotlib.pyplot.plot', 'plt.plot', (['inputs_a[line, :, 0]', 'outputs_a[line, :, 0]', '"""b*"""'], {'label': '"""training points"""'}), "(inputs_a[line, :, 0], outputs_a[line, :, 0], 'b*', label=\n 'training points')\n", (14338, 14419), True, 'import matplotlib.pyplot as plt\n'), ((14424, 14477), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (14435, 14477), True, 'import matplotlib.pyplot as plt\n'), ((14486, 14497), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14495, 14497), True, 'import matplotlib.pyplot as plt\n'), ((14958, 14970), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14968, 14970), True, 'import matplotlib.pyplot as plt\n'), ((15319, 15331), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (15329, 15331), True, 'import matplotlib.pyplot as plt\n'), ((15527, 15580), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (15538, 15580), True, 'import matplotlib.pyplot as plt\n'), ((15589, 15600), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15598, 15600), True, 'import matplotlib.pyplot as plt\n'), ((17906, 17930), 'numpy.sqrt', 'np.sqrt', (['NUM_TEST_POINTS'], {}), '(NUM_TEST_POINTS)\n', (17913, 17930), True, 'import numpy as np\n'), ((18369, 18413), 'pickle.dump', 'pickle.dump', (["{'mses': metaval_accuracies}", 'f'], {}), "({'mses': metaval_accuracies}, f)\n", (18380, 18413), False, 'import pickle\n'), ((18470, 18498), 'csv.writer', 'csv.writer', (['f'], {'delimiter': '""","""'}), "(f, delimiter=',')\n", (18480, 18498), False, 'import csv\n'), ((19336, 19401), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (19349, 19401), False, 'from data_generator import DataGenerator\n'), ((21460, 21474), 'random.seed', 'random.seed', (['(6)'], {}), '(6)\n', (21471, 21474), False, 'import random\n'), ((21574, 21661), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(image_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21582, 21661), True, 'import tensorflow as tf\n'), ((21669, 21757), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(image_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21677, 21757), True, 'import tensorflow as tf\n'), ((21765, 21852), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(label_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21773, 21852), True, 'import tensorflow as tf\n'), ((21860, 21948), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(label_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21868, 21948), True, 'import tensorflow as tf\n'), ((22495, 22546), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES)\n', (22512, 22546), True, 'import tensorflow as tf\n'), ((10109, 10148), 'numpy.sin', 'np.sin', (['(init_inputs[func] - phase[func])'], {}), '(init_inputs[func] - phase[func])\n', (10115, 10148), True, 'import numpy as np\n'), ((11444, 11469), 'numpy.array', 'np.array', (['predictions_all'], {}), '(predictions_all)\n', (11452, 11469), True, 'import numpy as np\n'), ((12272, 12338), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['X', '(mu + uncertainty)', '(mu - uncertainty)'], {'alpha': '(0.1)'}), '(X, mu + uncertainty, mu - uncertainty, alpha=0.1)\n', (12288, 12338), True, 'import matplotlib.pyplot as plt\n'), ((19616, 19655), 'data_generator.DataGenerator', 'DataGenerator', (['(1)', 'FLAGS.meta_batch_size'], {}), '(1, FLAGS.meta_batch_size)\n', (19629, 19655), False, 'from data_generator import DataGenerator\n'), ((20862, 20876), 'random.seed', 'random.seed', (['(5)'], {}), '(5)\n', (20873, 20876), False, 'import random\n'), ((20973, 21060), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(image_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (20981, 21060), True, 'import tensorflow as tf\n'), ((21072, 21160), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(image_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21080, 21160), True, 'import tensorflow as tf\n'), ((21172, 21259), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(label_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21180, 21259), True, 'import tensorflow as tf\n'), ((21271, 21359), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(label_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21279, 21359), True, 'import tensorflow as tf\n'), ((24082, 24115), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (24113, 24115), True, 'import tensorflow as tf\n'), ((24428, 24487), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["(FLAGS.logdir + '/' + exp_string)"], {}), "(FLAGS.logdir + '/' + exp_string)\n", (24454, 24487), True, 'import tensorflow as tf\n'), ((10280, 10337), 'numpy.zeros', 'np.zeros', (['[init_inputs.shape[0], init_inputs.shape[1], 2]'], {}), '([init_inputs.shape[0], init_inputs.shape[1], 2])\n', (10288, 10337), True, 'import numpy as np\n'), ((20205, 20270), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (20218, 20270), False, 'from data_generator import DataGenerator\n'), ((7788, 7807), 'numpy.mean', 'np.mean', (['postlosses'], {}), '(postlosses)\n', (7795, 7807), True, 'import numpy as np\n'), ((19860, 19926), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size + 15)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size + 15, FLAGS.meta_batch_size)\n', (19873, 19926), False, 'from data_generator import DataGenerator\n'), ((20037, 20102), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (20050, 20102), False, 'from data_generator import DataGenerator\n'), ((6084, 6133), 'numpy.zeros', 'np.zeros', (['[batch_x.shape[0], batch_x.shape[1], 2]'], {}), '([batch_x.shape[0], batch_x.shape[1], 2])\n', (6092, 6133), True, 'import numpy as np\n'), ((16872, 16921), 'numpy.zeros', 'np.zeros', (['[batch_x.shape[0], batch_x.shape[1], 2]'], {}), '([batch_x.shape[0], batch_x.shape[1], 2])\n', (16880, 16921), True, 'import numpy as np\n'), ((7755, 7773), 'numpy.mean', 'np.mean', (['prelosses'], {}), '(prelosses)\n', (7762, 7773), True, 'import numpy as np\n')]
|
import numpy as np
import torch
from scipy.stats import norm
from codes.worker import ByzantineWorker
from codes.aggregator import DecentralizedAggregator
class DecentralizedByzantineWorker(ByzantineWorker):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# The target of attack
self.target = None
self.tagg = None
self.target_good_neighbors = None
def _initialize_target(self):
if self.target is None:
assert len(self.running["neighbor_workers"]) == 1
self.target = self.running["neighbor_workers"][0]
self.tagg = self.target.running["aggregator"]
self.target_good_neighbors = self.simulator.get_good_neighbor_workers(
self.target.running["node"]
)
class DissensusWorker(DecentralizedByzantineWorker):
def __init__(self, epsilon, *args, **kwargs):
super().__init__(*args, **kwargs)
self.epsilon = epsilon
def _attack_decentralized_aggregator(self, mixing=None):
tm = self.target.running["flattened_model"]
# Compute Byzantine weights
partial_sum = []
partial_byz_weights = []
for neighbor in self.target.running["neighbor_workers"]:
nm = neighbor.running["flattened_model"]
nn = neighbor.running["node"]
nw = mixing or self.tagg.weights[nn.index]
if isinstance(neighbor, ByzantineWorker):
partial_byz_weights.append(nw)
else:
partial_sum.append(nw * (nm - tm))
partial_sum = sum(partial_sum)
partial_byz_weights = sum(partial_byz_weights)
return tm, partial_sum / partial_byz_weights
def pre_aggr(self, epoch, batch):
self._initialize_target()
if isinstance(self.tagg, DecentralizedAggregator):
# Dissensus using the gossip weight
tm, v = self._attack_decentralized_aggregator()
self.running["flattened_model"] = tm - self.epsilon * v
else:
# TODO: check
# Dissensus using the gossip weight
mixing = 1 / (len(self.target.running["neighbor_workers"]) + 1)
tm, v = self._attack_decentralized_aggregator(mixing)
self.running["flattened_model"] = tm - self.epsilon * v
class BitFlippingWorker(ByzantineWorker):
def __str__(self) -> str:
return "BitFlippingWorker"
def pre_aggr(self, epoch, batch):
self.running["flattened_model"] = -self.running["flattened_model"]
class LabelFlippingWorker(ByzantineWorker):
def __init__(self, revertible_label_transformer, *args, **kwargs):
"""
Args:
revertible_label_transformer (callable):
E.g. lambda label: 9 - label
"""
super().__init__(*args, **kwargs)
self.revertible_label_transformer = revertible_label_transformer
def train_epoch_start(self) -> None:
super().train_epoch_start()
self.running["train_loader_iterator"].__next__ = self._wrap_iterator(
self.running["train_loader_iterator"].__next__
)
def _wrap_iterator(self, func):
def wrapper():
data, target = func()
return data, self.revertible_label_transformer(target)
return wrapper
def _wrap_metric(self, func):
def wrapper(output, target):
return func(output, self.revertible_label_transformer(target))
return wrapper
def add_metric(self, name, callback):
if name in self.metrics or name in ["loss", "length"]:
raise KeyError(f"Metrics ({name}) already added.")
self.metrics[name] = self._wrap_metric(callback)
def __str__(self) -> str:
return "LabelFlippingWorker"
class ALittleIsEnoughAttack(DecentralizedByzantineWorker):
"""
Adapted for the decentralized environment.
Args:
n (int): Total number of workers
m (int): Number of Byzantine workers
"""
def __init__(self, n, m, z=None, *args, **kwargs):
super().__init__(*args, **kwargs)
# Number of supporters
if z is not None:
self.z_max = z
else:
s = np.floor(n / 2 + 1) - m
cdf_value = (n - m - s) / (n - m)
self.z_max = norm.ppf(cdf_value)
self.n_good = n - m
def get_gradient(self):
return 0
def set_gradient(self, gradient):
pass
def apply_gradient(self):
pass
def pre_aggr(self, epoch, batch):
self._initialize_target()
tm = self.target.running["flattened_model"]
models = [tm]
for neighbor in self.target_good_neighbors:
models.append(neighbor.running["flattened_model"])
stacked_models = torch.stack(models, 1)
mu = torch.mean(stacked_models, 1)
std = torch.std(stacked_models, 1)
self.running["flattened_model"] = mu - std * self.z_max
class IPMAttack(DecentralizedByzantineWorker):
def __init__(self, epsilon, *args, **kwargs):
super().__init__(*args, **kwargs)
self.epsilon = epsilon
def get_gradient(self):
return 0
def set_gradient(self, gradient):
pass
def apply_gradient(self):
pass
def pre_aggr(self, epoch, batch):
self._initialize_target()
tm = self.target.running["flattened_model"]
models = [tm]
for neighbor in self.target_good_neighbors:
models.append(neighbor.running["flattened_model"])
self.running["flattened_model"] = -self.epsilon * sum(models) / len(models)
def get_attackers(
args, rank, trainer, model, opt, loss_func, loader, device, lr_scheduler
):
if args.attack == "BF":
return BitFlippingWorker(
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
if args.attack == "LF":
return LabelFlippingWorker(
revertible_label_transformer=lambda label: 9 - label,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
if args.attack.startswith("ALIE"):
if args.attack == "ALIE":
z = None
else:
z = float(args.attack[4:])
attacker = ALittleIsEnoughAttack(
n=args.n,
m=args.f,
z=z,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
if args.attack == "IPM":
attacker = IPMAttack(
epsilon=0.1,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
if args.attack.startswith("dissensus"):
epsilon = float(args.attack[len("dissensus") :])
attacker = DissensusWorker(
epsilon=epsilon,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
raise NotImplementedError(f"No such attack {args.attack}")
|
[
"torch.mean",
"torch.stack",
"scipy.stats.norm.ppf",
"numpy.floor",
"torch.std"
] |
[((4811, 4833), 'torch.stack', 'torch.stack', (['models', '(1)'], {}), '(models, 1)\n', (4822, 4833), False, 'import torch\n'), ((4847, 4876), 'torch.mean', 'torch.mean', (['stacked_models', '(1)'], {}), '(stacked_models, 1)\n', (4857, 4876), False, 'import torch\n'), ((4891, 4919), 'torch.std', 'torch.std', (['stacked_models', '(1)'], {}), '(stacked_models, 1)\n', (4900, 4919), False, 'import torch\n'), ((4332, 4351), 'scipy.stats.norm.ppf', 'norm.ppf', (['cdf_value'], {}), '(cdf_value)\n', (4340, 4351), False, 'from scipy.stats import norm\n'), ((4237, 4256), 'numpy.floor', 'np.floor', (['(n / 2 + 1)'], {}), '(n / 2 + 1)\n', (4245, 4256), True, 'import numpy as np\n')]
|
import astropy.units as u
from astropy.coordinates import Angle, SkyCoord
from astropy import wcs
from regions import CircleSkyRegion
import numpy as np
from scipy.stats import expon
def estimate_exposure_time(timestamps):
'''
Takes numpy datetime64[ns] timestamps and returns an estimates of the exposure time in seconds.
'''
delta_s = np.diff(timestamps).astype(int) * float(1e-9)
# take only events that came within 30 seconds or so
delta_s = delta_s[delta_s < 30]
scale = delta_s.mean()
exposure_time = len(delta_s) * scale
loc = min(delta_s)
# this percentile is somewhat abritrary but seems to work well.
live_time_fraction = 1 - expon.ppf(0.1, loc=loc, scale=scale)
return (exposure_time * live_time_fraction) * u.s
@u.quantity_input(ra=u.hourangle, dec=u.deg, fov=u.deg)
def build_exposure_regions(pointing_coords, fov=4.5 * u.deg):
'''
Takes a list of pointing positions and a field of view and returns
the unique pointing positions and the astropy.regions.
For an observation with N wobble positions this will return N unique
pointing positions and N circular regions.
'''
unique_pointing_positions = SkyCoord(
ra=np.unique(pointing_coords.ra),
dec=np.unique(pointing_coords.dec)
)
regions = [CircleSkyRegion(
center=pointing,
radius=Angle(fov) / 2
) for pointing in unique_pointing_positions]
return unique_pointing_positions, regions
def _build_standard_wcs(image_center, shape, naxis=2, fov=9 * u.deg):
width, height = shape
w = wcs.WCS(naxis=2)
w.wcs.crpix = [width / 2 + 0.5, height / 2 + 0.5]
w.wcs.cdelt = np.array([-fov.value / width, fov.value / height])
w.wcs.crval = [image_center.ra.deg, image_center.dec.deg]
w.wcs.ctype = ["RA---TAN", "DEC--TAN"]
w.wcs.radesys = 'FK5'
w.wcs.equinox = 2000.0
w.wcs.cunit = ['deg', 'deg']
w._naxis = [width, height]
return w
@u.quantity_input(event_ra=u.hourangle, event_dec=u.deg, fov=u.deg)
def build_exposure_map(pointing_coords, event_time, fov=4.5 * u.deg, wcs=None, shape=(1000, 1000)):
'''
Takes pointing coordinates for each event and the corresponding timestamp.
Returns a masked array containing the estimated exposure time in hours
and a WCS object so the mask can be plotted.
'''
if not wcs:
image_center = SkyCoord(ra=pointing_coords.ra.mean(), dec=pointing_coords.dec.mean())
wcs = _build_standard_wcs(image_center, shape, fov=2 * fov)
unique_pointing_positions, regions = build_exposure_regions(pointing_coords)
times = []
for p in unique_pointing_positions:
m = (pointing_coords.ra == p.ra) & (pointing_coords.dec == p.dec)
exposure_time = estimate_exposure_time(event_time[m])
times.append(exposure_time)
masks = [r.to_pixel(wcs).to_mask().to_image(shape) for r in regions]
cutout = sum(masks).astype(bool)
mask = sum([w.to('h').value * m for w, m in zip(times, masks)])
return np.ma.masked_array(mask, mask=~cutout), wcs
|
[
"numpy.unique",
"astropy.coordinates.Angle",
"numpy.diff",
"numpy.array",
"numpy.ma.masked_array",
"scipy.stats.expon.ppf",
"astropy.wcs.WCS",
"astropy.units.quantity_input"
] |
[((780, 834), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'ra': 'u.hourangle', 'dec': 'u.deg', 'fov': 'u.deg'}), '(ra=u.hourangle, dec=u.deg, fov=u.deg)\n', (796, 834), True, 'import astropy.units as u\n'), ((1966, 2032), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'event_ra': 'u.hourangle', 'event_dec': 'u.deg', 'fov': 'u.deg'}), '(event_ra=u.hourangle, event_dec=u.deg, fov=u.deg)\n', (1982, 2032), True, 'import astropy.units as u\n'), ((1588, 1604), 'astropy.wcs.WCS', 'wcs.WCS', ([], {'naxis': '(2)'}), '(naxis=2)\n', (1595, 1604), False, 'from astropy import wcs\n'), ((1677, 1727), 'numpy.array', 'np.array', (['[-fov.value / width, fov.value / height]'], {}), '([-fov.value / width, fov.value / height])\n', (1685, 1727), True, 'import numpy as np\n'), ((685, 721), 'scipy.stats.expon.ppf', 'expon.ppf', (['(0.1)'], {'loc': 'loc', 'scale': 'scale'}), '(0.1, loc=loc, scale=scale)\n', (694, 721), False, 'from scipy.stats import expon\n'), ((3032, 3070), 'numpy.ma.masked_array', 'np.ma.masked_array', (['mask'], {'mask': '(~cutout)'}), '(mask, mask=~cutout)\n', (3050, 3070), True, 'import numpy as np\n'), ((1217, 1246), 'numpy.unique', 'np.unique', (['pointing_coords.ra'], {}), '(pointing_coords.ra)\n', (1226, 1246), True, 'import numpy as np\n'), ((1260, 1290), 'numpy.unique', 'np.unique', (['pointing_coords.dec'], {}), '(pointing_coords.dec)\n', (1269, 1290), True, 'import numpy as np\n'), ((355, 374), 'numpy.diff', 'np.diff', (['timestamps'], {}), '(timestamps)\n', (362, 374), True, 'import numpy as np\n'), ((1370, 1380), 'astropy.coordinates.Angle', 'Angle', (['fov'], {}), '(fov)\n', (1375, 1380), False, 'from astropy.coordinates import Angle, SkyCoord\n')]
|
import numpy as np
a = np.zeros((10,6))
a[1,4:6] = [2,3]
b = a[1,4]
print(b)
check = np.array([2,3])
for i in range(a.shape[0]):
t = int(a[i,4])
idx = int(a[i,5])
if t == 2 and idx == 4:
a = np.delete(a,i,0)
break
else:
continue
print(a.shape)
|
[
"numpy.array",
"numpy.zeros",
"numpy.delete"
] |
[((24, 41), 'numpy.zeros', 'np.zeros', (['(10, 6)'], {}), '((10, 6))\n', (32, 41), True, 'import numpy as np\n'), ((88, 104), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (96, 104), True, 'import numpy as np\n'), ((216, 234), 'numpy.delete', 'np.delete', (['a', 'i', '(0)'], {}), '(a, i, 0)\n', (225, 234), True, 'import numpy as np\n')]
|
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Created by: <NAME>
#BE department, University of Pennsylvania
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import numpy as np
import nibabel as nib
import os
from tqdm import tqdm
from functools import partial
import matplotlib.pyplot as plt
from multiprocessing import Pool
from scipy.spatial.distance import directed_hausdorff
import data_utils.surface_distance as surface_distance
def estimate_weights_mfb(labels):
labels = labels.astype(np.float64)
class_weights = np.zeros_like(labels)
unique, counts = np.unique(labels, return_counts=True)
median_freq = np.median(counts)
weights = np.zeros(len(unique))
for i, label in enumerate(unique):
class_weights += (median_freq // counts[i]) * np.array(labels == label)
weights[int(label)] = median_freq // counts[i]
grads = np.gradient(labels)
edge_weights = (grads[0] ** 2 + grads[1] ** 2) > 0
class_weights += 2 * edge_weights
return class_weights, weights
def remaplabels(id, labelfiles, labeldir, savedir):
labelfile = labelfiles[id]
if os.path.exists(os.path.join(savedir,labelfile[:-7]+'.npy')):
return
label = nib.load(os.path.join(labeldir,labelfile))
labelnpy = label.get_fdata()
labelnpy = labelnpy.astype(np.int32)
########################this is for coarse-grained dataset##############################
# labelnpy[(labelnpy >= 100) & (labelnpy % 2 == 0)] = 210
# labelnpy[(labelnpy >= 100) & (labelnpy % 2 == 1)] = 211
# label_list = [45, 211, 44, 210, 52, 41, 39, 60, 37, 58, 56, 4, 11, 35, 48, 32, 62, 51, 40, 38, 59, 36, 57,
# 55, 47, 31, 61]
########################this is for fine-grained dataset##############################
label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207])
new_labels = np.zeros_like(labelnpy)
for i, num in enumerate(label_list):
label_present = np.zeros_like(labelnpy)
label_present[labelnpy == num] = 1
new_labels = new_labels + (i + 1) * label_present
if (np.sum(np.unique(new_labels)>139) and np.sum(np.unique(new_labels)<0)) > 0:
print('error')
np.save(os.path.join(savedir,labelfile[:-7]), new_labels)
print('finished converting label: ' + labelfile)
def process_resampled_labels():
labeldir = None #label directory for all nifty images
savedir = None #directory to save numpy images
labelfiles = [f for f in os.listdir(labeldir) if os.path.isfile(os.path.join(labeldir, f))]
labelfiles = [f for f in labelfiles if '_lab.nii.gz' in f]
pool = Pool(processes=20)
partial_mri = partial(remaplabels, labelfiles=labelfiles, labeldir=labeldir, savedir=savedir)
pool.map(partial_mri, range(len(labelfiles)))
pool.close()
pool.join()
print('end preprocessing brain data')
def convertTonpy(datadir, savedir):
if not os.path.exists(savedir):
os.makedirs(savedir)
datafiles = [f for f in os.listdir(datadir) if os.path.isfile(os.path.join(datadir, f))]
datafiles = [f for f in datafiles if '_brainmask.nii.gz' in f]
tbar = tqdm(datafiles)
for datafile in tbar:
data = nib.load(os.path.join(datadir,datafile))
datanpy = data.get_fdata()
datanpy = datanpy.astype(np.int32)
# datanpy = datanpy.astype(np.float32)
datanpy[datanpy>0]=1
np.save(os.path.join(savedir,datafile[:-7]), datanpy)
def convertToNifty(datadir, savedir):
if not os.path.exists(savedir):
os.makedirs(savedir)
datafiles = [f for f in os.listdir(datadir) if os.path.isfile(os.path.join(datadir, f))]
for datafile in datafiles:
datanpy = np.load(os.path.join(datadir,datafile))
datanpy = np.transpose(datanpy, (1,2,0))
datanpy = datanpy.astype(np.uint8)
img = nib.Nifti1Image(datanpy, np.eye(4))
assert(img.get_data_dtype() == np.uint8)
nib.save(img, os.path.join(savedir,datafile[:-4]+'.nii.gz'))
def process_fine_labels(fine_label_dir):
dice_score = np.load(os.path.join(fine_label_dir, 'dice_score.npy'))
iou_score = np.load(os.path.join(fine_label_dir, 'iou_score.npy'))
label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207])
total_idx = np.arange(0, len(label_list))
ignore = np.array([42, 43, 64, 69])
valid_idx = [i+1 for i in total_idx if label_list[i] not in ignore]
valid_idx = [0] + valid_idx
dice_score_vali = dice_score[:,valid_idx]
iou_score_vali = iou_score[:,valid_idx]
print(np.mean(dice_score_vali))
print(np.std(dice_score_vali))
print(np.mean(iou_score_vali))
print(np.std(iou_score_vali))
def remap_IXI_images(id, subfodlers, savedir):
subname = subfodlers[id]
orig_dir = subname+'_orig.nii.gz'
aseg_dir = subname+'_aseg.nii.gz'
brain_mask_dir = subname+'_brainmask.nii.gz'
name = subname.split('/')[-1]
orig = nib.load(orig_dir)
orig_npy = orig.get_fdata()
orig_npy = orig_npy.astype(np.int32)
np.save(os.path.join(savedir,'training_images/'+name+'.npy'), orig_npy)
aseg = nib.load(aseg_dir)
aseg_npy = aseg.get_fdata()
aseg_npy = aseg_npy.astype(np.int32)
correspond_labels = [2, 3, 41, 42, 4, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 28, 43, 46, 47,
49, 50, 51, 52, 53, 54, 60]
new_labels = np.zeros_like(aseg_npy)
for i, num in enumerate(correspond_labels):
label_present = np.zeros_like(aseg_npy)
label_present[aseg_npy == num] = 1
new_labels = new_labels + (i + 1) * label_present
np.save(os.path.join(savedir,'training_labels/'+name+'.npy'), new_labels)
brain_mask = nib.load(brain_mask_dir)
brain_mask_npy = brain_mask.get_fdata()
brain_mask_npy = brain_mask_npy.astype(np.int32)
brain_mask_npy[brain_mask_npy>0]=1
np.save(os.path.join(savedir,'training_skulls/'+name+'.npy'), brain_mask_npy)
print('finished processing image '+name)
def process_IXI_images():
datadir = '/IXI_T1_surf/'
nii_path = '/IXI_T1_surf_nii/'
savedir = '/IXI_T1_surf/'
subfodlers = [os.path.join(nii_path, name) for name in os.listdir(datadir) if os.path.isdir(os.path.join(datadir, name)) and 'IXI' in name]
pool = Pool(processes=20)
partial_mri = partial(remap_IXI_images, subfodlers=subfodlers, savedir=savedir)
pool.map(partial_mri, range(len(subfodlers)))
pool.close()
pool.join()
print('end preprocessing IXI data')
def compute_Hausdorff_distance(id, subfiles, gt_dir, pred_dir, baseline_dir):
file_name = subfiles[id]
# subfiles = [name for name in os.listdir(gt_dir)]
dist_pred_lists = []
dist_quick_lists = []
# label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
# 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
# 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
# 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
# 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
# 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
# 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
# 156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
# 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
# 184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
# 199, 200, 201, 202, 203, 204, 205, 206, 207])
# total_idx = np.arange(0, len(label_list))
#
# ignore = np.array([42,43,64, 69])
#
# non_valid_idx = [i+1 for i in total_idx if label_list[i] in ignore]
# non_valid_idx = non_valid_idx
#this is originally a for loop
file_gt = nib.load(os.path.join(gt_dir,file_name))
file_gt_npy = file_gt.get_fdata().astype(np.int32)
file_pred = nib.load(os.path.join(pred_dir,file_name))
file_pred_npy = file_pred.get_fdata().astype(np.int32)
file_quick = nib.load(os.path.join(baseline_dir,file_name))
file_quick_npy = file_quick.get_fdata().astype(np.int32)
# for idx in non_valid_idx:
# file_pred_npy[file_pred_npy==idx] = 0
# file_quick_npy[file_quick_npy==idx] = 0
# file_gt_npy[file_gt_npy==idx] = 0
for idx in np.unique(file_gt_npy):
temp_gt = np.zeros_like(file_gt_npy)
temp_pred = np.zeros_like(file_gt_npy)
temp_quick = np.zeros_like(file_gt_npy)
temp_gt[file_gt_npy==idx] = 1
temp_pred[file_pred_npy==idx] = 1
temp_quick[file_quick_npy==idx] = 1
surface_distances_pred = surface_distance.compute_surface_distances(temp_gt, temp_pred, spacing_mm=(1, 1, 1))
dist_pred = surface_distance.compute_robust_hausdorff(surface_distances_pred, 100)
dist_pred_lists.append(dist_pred)
surface_distances_quick = surface_distance.compute_surface_distances(temp_gt, temp_quick, spacing_mm=(1, 1, 1))
dist_quick = surface_distance.compute_robust_hausdorff(surface_distances_quick, 100)
dist_quick_lists.append(dist_quick)
np.save(os.path.join(pred_dir,file_name+'_pred.npy'), dist_pred_lists)
np.save(os.path.join(pred_dir,file_name+'_quick.npy'), dist_quick_lists)
def process_Hausdorff_distance():
baseline_dir = '/MRI_model/quicknat/pred' #this is our baseline
pred_dir = '/MRI_model/coarse_dir/pred'
gt_dir = None #gt label directory, double check the rotation matches with pred
subfiles = [name for name in os.listdir(gt_dir)]
pool = Pool(processes=16)
partial_mri = partial(compute_Hausdorff_distance, subfiles=subfiles, gt_dir=gt_dir, pred_dir=pred_dir, baseline_dir=baseline_dir)
pool.map(partial_mri, range(len(subfiles)))
pool.close()
pool.join()
print('end preprocessing IXI data')
def process_Hausdorff_npy():
#this is for MALC27
gt_dir = '/label/' #gt label directory, double check the rotation matches with pred
pred_dir = '/MRI_model/coarse_dir/pred'
subfiles = [name for name in os.listdir(gt_dir)]
dist_pred_lists = []
dist_quick_lists = []
for file_name in subfiles:
pred_dist = np.load(os.path.join(pred_dir,file_name+'_pred.npy'))
quick_dist = np.load(os.path.join(pred_dir,file_name+'_quick.npy'))
quick_dist[quick_dist==np.inf]=150
dist_pred_lists.append(np.mean(pred_dist[1:,0].astype(np.float32)))
dist_quick_lists.append(np.mean(quick_dist[1:,0].astype(np.float32)))
dist_pred_lists = np.asarray(dist_pred_lists)
dist_quick_lists = np.asarray(dist_quick_lists)
print(np.mean(dist_pred_lists))
print(np.mean(dist_quick_lists))
if __name__ == '__main__':
process_resampled_labels()
|
[
"nibabel.load",
"numpy.array",
"numpy.gradient",
"os.path.exists",
"numpy.mean",
"os.listdir",
"numpy.asarray",
"numpy.eye",
"numpy.std",
"numpy.transpose",
"numpy.median",
"data_utils.surface_distance.compute_robust_hausdorff",
"numpy.unique",
"os.makedirs",
"tqdm.tqdm",
"os.path.join",
"functools.partial",
"multiprocessing.Pool",
"data_utils.surface_distance.compute_surface_distances",
"numpy.zeros_like"
] |
[((588, 609), 'numpy.zeros_like', 'np.zeros_like', (['labels'], {}), '(labels)\n', (601, 609), True, 'import numpy as np\n'), ((631, 668), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (640, 668), True, 'import numpy as np\n'), ((687, 704), 'numpy.median', 'np.median', (['counts'], {}), '(counts)\n', (696, 704), True, 'import numpy as np\n'), ((928, 947), 'numpy.gradient', 'np.gradient', (['labels'], {}), '(labels)\n', (939, 947), True, 'import numpy as np\n'), ((1887, 2589), 'numpy.array', 'np.array', (['[4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72,\n 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112, 113,\n 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 128, 129, \n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, \n 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 160, 161, \n 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, \n 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 190, 191, \n 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, \n 206, 207]'], {}), '([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69,\n 71, 72, 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, \n 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, \n 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, \n 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, \n 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, \n 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, \n 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, \n 204, 205, 206, 207])\n', (1895, 2589), True, 'import numpy as np\n'), ((2794, 2817), 'numpy.zeros_like', 'np.zeros_like', (['labelnpy'], {}), '(labelnpy)\n', (2807, 2817), True, 'import numpy as np\n'), ((3568, 3586), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(20)'}), '(processes=20)\n', (3572, 3586), False, 'from multiprocessing import Pool\n'), ((3605, 3684), 'functools.partial', 'partial', (['remaplabels'], {'labelfiles': 'labelfiles', 'labeldir': 'labeldir', 'savedir': 'savedir'}), '(remaplabels, labelfiles=labelfiles, labeldir=labeldir, savedir=savedir)\n', (3612, 3684), False, 'from functools import partial\n'), ((4107, 4122), 'tqdm.tqdm', 'tqdm', (['datafiles'], {}), '(datafiles)\n', (4111, 4122), False, 'from tqdm import tqdm\n'), ((5195, 5897), 'numpy.array', 'np.array', (['[4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72,\n 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112, 113,\n 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 128, 129, \n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, \n 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 160, 161, \n 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, \n 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 190, 191, \n 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, \n 206, 207]'], {}), '([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69,\n 71, 72, 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, \n 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, \n 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, \n 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, \n 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, \n 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, \n 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, \n 204, 205, 206, 207])\n', (5203, 5897), True, 'import numpy as np\n'), ((6173, 6199), 'numpy.array', 'np.array', (['[42, 43, 64, 69]'], {}), '([42, 43, 64, 69])\n', (6181, 6199), True, 'import numpy as np\n'), ((6826, 6844), 'nibabel.load', 'nib.load', (['orig_dir'], {}), '(orig_dir)\n', (6834, 6844), True, 'import nibabel as nib\n'), ((7010, 7028), 'nibabel.load', 'nib.load', (['aseg_dir'], {}), '(aseg_dir)\n', (7018, 7028), True, 'import nibabel as nib\n'), ((7278, 7301), 'numpy.zeros_like', 'np.zeros_like', (['aseg_npy'], {}), '(aseg_npy)\n', (7291, 7301), True, 'import numpy as np\n'), ((7600, 7624), 'nibabel.load', 'nib.load', (['brain_mask_dir'], {}), '(brain_mask_dir)\n', (7608, 7624), True, 'import nibabel as nib\n'), ((8188, 8206), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(20)'}), '(processes=20)\n', (8192, 8206), False, 'from multiprocessing import Pool\n'), ((8225, 8290), 'functools.partial', 'partial', (['remap_IXI_images'], {'subfodlers': 'subfodlers', 'savedir': 'savedir'}), '(remap_IXI_images, subfodlers=subfodlers, savedir=savedir)\n', (8232, 8290), False, 'from functools import partial\n'), ((10407, 10429), 'numpy.unique', 'np.unique', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10416, 10429), True, 'import numpy as np\n'), ((11705, 11723), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(16)'}), '(processes=16)\n', (11709, 11723), False, 'from multiprocessing import Pool\n'), ((11742, 11861), 'functools.partial', 'partial', (['compute_Hausdorff_distance'], {'subfiles': 'subfiles', 'gt_dir': 'gt_dir', 'pred_dir': 'pred_dir', 'baseline_dir': 'baseline_dir'}), '(compute_Hausdorff_distance, subfiles=subfiles, gt_dir=gt_dir,\n pred_dir=pred_dir, baseline_dir=baseline_dir)\n', (11749, 11861), False, 'from functools import partial\n'), ((12689, 12716), 'numpy.asarray', 'np.asarray', (['dist_pred_lists'], {}), '(dist_pred_lists)\n', (12699, 12716), True, 'import numpy as np\n'), ((12740, 12768), 'numpy.asarray', 'np.asarray', (['dist_quick_lists'], {}), '(dist_quick_lists)\n', (12750, 12768), True, 'import numpy as np\n'), ((1191, 1237), 'os.path.join', 'os.path.join', (['savedir', "(labelfile[:-7] + '.npy')"], {}), "(savedir, labelfile[:-7] + '.npy')\n", (1203, 1237), False, 'import os\n'), ((1282, 1315), 'os.path.join', 'os.path.join', (['labeldir', 'labelfile'], {}), '(labeldir, labelfile)\n', (1294, 1315), False, 'import os\n'), ((2884, 2907), 'numpy.zeros_like', 'np.zeros_like', (['labelnpy'], {}), '(labelnpy)\n', (2897, 2907), True, 'import numpy as np\n'), ((3138, 3175), 'os.path.join', 'os.path.join', (['savedir', 'labelfile[:-7]'], {}), '(savedir, labelfile[:-7])\n', (3150, 3175), False, 'import os\n'), ((3872, 3895), 'os.path.exists', 'os.path.exists', (['savedir'], {}), '(savedir)\n', (3886, 3895), False, 'import os\n'), ((3905, 3925), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (3916, 3925), False, 'import os\n'), ((4476, 4499), 'os.path.exists', 'os.path.exists', (['savedir'], {}), '(savedir)\n', (4490, 4499), False, 'import os\n'), ((4509, 4529), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (4520, 4529), False, 'import os\n'), ((4744, 4776), 'numpy.transpose', 'np.transpose', (['datanpy', '(1, 2, 0)'], {}), '(datanpy, (1, 2, 0))\n', (4756, 4776), True, 'import numpy as np\n'), ((5054, 5100), 'os.path.join', 'os.path.join', (['fine_label_dir', '"""dice_score.npy"""'], {}), "(fine_label_dir, 'dice_score.npy')\n", (5066, 5100), False, 'import os\n'), ((5126, 5171), 'os.path.join', 'os.path.join', (['fine_label_dir', '"""iou_score.npy"""'], {}), "(fine_label_dir, 'iou_score.npy')\n", (5138, 5171), False, 'import os\n'), ((6419, 6443), 'numpy.mean', 'np.mean', (['dice_score_vali'], {}), '(dice_score_vali)\n', (6426, 6443), True, 'import numpy as np\n'), ((6455, 6478), 'numpy.std', 'np.std', (['dice_score_vali'], {}), '(dice_score_vali)\n', (6461, 6478), True, 'import numpy as np\n'), ((6495, 6518), 'numpy.mean', 'np.mean', (['iou_score_vali'], {}), '(iou_score_vali)\n', (6502, 6518), True, 'import numpy as np\n'), ((6530, 6552), 'numpy.std', 'np.std', (['iou_score_vali'], {}), '(iou_score_vali)\n', (6536, 6552), True, 'import numpy as np\n'), ((6930, 6987), 'os.path.join', 'os.path.join', (['savedir', "('training_images/' + name + '.npy')"], {}), "(savedir, 'training_images/' + name + '.npy')\n", (6942, 6987), False, 'import os\n'), ((7375, 7398), 'numpy.zeros_like', 'np.zeros_like', (['aseg_npy'], {}), '(aseg_npy)\n', (7388, 7398), True, 'import numpy as np\n'), ((7512, 7569), 'os.path.join', 'os.path.join', (['savedir', "('training_labels/' + name + '.npy')"], {}), "(savedir, 'training_labels/' + name + '.npy')\n", (7524, 7569), False, 'import os\n'), ((7773, 7830), 'os.path.join', 'os.path.join', (['savedir', "('training_skulls/' + name + '.npy')"], {}), "(savedir, 'training_skulls/' + name + '.npy')\n", (7785, 7830), False, 'import os\n'), ((8050, 8078), 'os.path.join', 'os.path.join', (['nii_path', 'name'], {}), '(nii_path, name)\n', (8062, 8078), False, 'import os\n'), ((9872, 9903), 'os.path.join', 'os.path.join', (['gt_dir', 'file_name'], {}), '(gt_dir, file_name)\n', (9884, 9903), False, 'import os\n'), ((9989, 10022), 'os.path.join', 'os.path.join', (['pred_dir', 'file_name'], {}), '(pred_dir, file_name)\n', (10001, 10022), False, 'import os\n'), ((10113, 10150), 'os.path.join', 'os.path.join', (['baseline_dir', 'file_name'], {}), '(baseline_dir, file_name)\n', (10125, 10150), False, 'import os\n'), ((10449, 10475), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10462, 10475), True, 'import numpy as np\n'), ((10496, 10522), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10509, 10522), True, 'import numpy as np\n'), ((10544, 10570), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10557, 10570), True, 'import numpy as np\n'), ((10746, 10835), 'data_utils.surface_distance.compute_surface_distances', 'surface_distance.compute_surface_distances', (['temp_gt', 'temp_pred'], {'spacing_mm': '(1, 1, 1)'}), '(temp_gt, temp_pred, spacing_mm=(\n 1, 1, 1))\n', (10788, 10835), True, 'import data_utils.surface_distance as surface_distance\n'), ((10851, 10921), 'data_utils.surface_distance.compute_robust_hausdorff', 'surface_distance.compute_robust_hausdorff', (['surface_distances_pred', '(100)'], {}), '(surface_distances_pred, 100)\n', (10892, 10921), True, 'import data_utils.surface_distance as surface_distance\n'), ((11007, 11097), 'data_utils.surface_distance.compute_surface_distances', 'surface_distance.compute_surface_distances', (['temp_gt', 'temp_quick'], {'spacing_mm': '(1, 1, 1)'}), '(temp_gt, temp_quick, spacing_mm=\n (1, 1, 1))\n', (11049, 11097), True, 'import data_utils.surface_distance as surface_distance\n'), ((11114, 11185), 'data_utils.surface_distance.compute_robust_hausdorff', 'surface_distance.compute_robust_hausdorff', (['surface_distances_quick', '(100)'], {}), '(surface_distances_quick, 100)\n', (11155, 11185), True, 'import data_utils.surface_distance as surface_distance\n'), ((11251, 11298), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_pred.npy')"], {}), "(pred_dir, file_name + '_pred.npy')\n", (11263, 11298), False, 'import os\n'), ((11326, 11374), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_quick.npy')"], {}), "(pred_dir, file_name + '_quick.npy')\n", (11338, 11374), False, 'import os\n'), ((12779, 12803), 'numpy.mean', 'np.mean', (['dist_pred_lists'], {}), '(dist_pred_lists)\n', (12786, 12803), True, 'import numpy as np\n'), ((12815, 12840), 'numpy.mean', 'np.mean', (['dist_quick_lists'], {}), '(dist_quick_lists)\n', (12822, 12840), True, 'import numpy as np\n'), ((834, 859), 'numpy.array', 'np.array', (['(labels == label)'], {}), '(labels == label)\n', (842, 859), True, 'import numpy as np\n'), ((3426, 3446), 'os.listdir', 'os.listdir', (['labeldir'], {}), '(labeldir)\n', (3436, 3446), False, 'import os\n'), ((3959, 3978), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (3969, 3978), False, 'import os\n'), ((4178, 4209), 'os.path.join', 'os.path.join', (['datadir', 'datafile'], {}), '(datadir, datafile)\n', (4190, 4209), False, 'import os\n'), ((4379, 4415), 'os.path.join', 'os.path.join', (['savedir', 'datafile[:-7]'], {}), '(savedir, datafile[:-7])\n', (4391, 4415), False, 'import os\n'), ((4567, 4586), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (4577, 4586), False, 'import os\n'), ((4694, 4725), 'os.path.join', 'os.path.join', (['datadir', 'datafile'], {}), '(datadir, datafile)\n', (4706, 4725), False, 'import os\n'), ((4857, 4866), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (4863, 4866), True, 'import numpy as np\n'), ((4939, 4987), 'os.path.join', 'os.path.join', (['savedir', "(datafile[:-4] + '.nii.gz')"], {}), "(savedir, datafile[:-4] + '.nii.gz')\n", (4951, 4987), False, 'import os\n'), ((8091, 8110), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (8101, 8110), False, 'import os\n'), ((11673, 11691), 'os.listdir', 'os.listdir', (['gt_dir'], {}), '(gt_dir)\n', (11683, 11691), False, 'import os\n'), ((12213, 12231), 'os.listdir', 'os.listdir', (['gt_dir'], {}), '(gt_dir)\n', (12223, 12231), False, 'import os\n'), ((12348, 12395), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_pred.npy')"], {}), "(pred_dir, file_name + '_pred.npy')\n", (12360, 12395), False, 'import os\n'), ((12423, 12471), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_quick.npy')"], {}), "(pred_dir, file_name + '_quick.npy')\n", (12435, 12471), False, 'import os\n'), ((3465, 3490), 'os.path.join', 'os.path.join', (['labeldir', 'f'], {}), '(labeldir, f)\n', (3477, 3490), False, 'import os\n'), ((3997, 4021), 'os.path.join', 'os.path.join', (['datadir', 'f'], {}), '(datadir, f)\n', (4009, 4021), False, 'import os\n'), ((4605, 4629), 'os.path.join', 'os.path.join', (['datadir', 'f'], {}), '(datadir, f)\n', (4617, 4629), False, 'import os\n'), ((3029, 3050), 'numpy.unique', 'np.unique', (['new_labels'], {}), '(new_labels)\n', (3038, 3050), True, 'import numpy as np\n'), ((3067, 3088), 'numpy.unique', 'np.unique', (['new_labels'], {}), '(new_labels)\n', (3076, 3088), True, 'import numpy as np\n'), ((8128, 8155), 'os.path.join', 'os.path.join', (['datadir', 'name'], {}), '(datadir, name)\n', (8140, 8155), False, 'import os\n')]
|
import tempfile
import unittest
from pathlib import Path
from typing import Iterable
import numpy as np
from tests.fixtures.algorithms import SupervisedDeviatingFromMean
from timeeval import (
TimeEval,
Algorithm,
Datasets,
TrainingType,
InputDimensionality,
Status,
Metric,
ResourceConstraints,
DatasetManager
)
from timeeval.datasets import Dataset, DatasetRecord
from timeeval.experiments import Experiment, Experiments
from timeeval.utils.hash_dict import hash_dict
class TestDatasetAndAlgorithmMatch(unittest.TestCase):
def setUp(self) -> None:
self.dmgr = DatasetManager("./tests/example_data")
self.algorithms = [
Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SUPERVISED,
input_dimensionality=InputDimensionality.UNIVARIATE,
data_as_file=False
)
]
def _prepare_dmgr(self, path: Path,
training_type: Iterable[str] = ("unsupervised",),
dimensionality: Iterable[str] = ("univariate",)) -> Datasets:
dmgr = DatasetManager(path / "data")
for t, d in zip(training_type, dimensionality):
dmgr.add_dataset(DatasetRecord(
collection_name="test",
dataset_name=f"dataset-{t}-{d}",
train_path="train.csv",
test_path="test.csv",
dataset_type="synthetic",
datetime_index=False,
split_at=-1,
train_type=t,
train_is_normal=True if t == "semi-supervised" else False,
input_type=d,
length=10000,
dimensions=5 if d == "multivariate" else 1,
contamination=0.1,
num_anomalies=1,
min_anomaly_length=100,
median_anomaly_length=100,
max_anomaly_length=100,
mean=0.0,
stddev=1.0,
trend="no-trend",
stationarity="stationary",
period_size=50
))
return dmgr
def test_supervised_algorithm(self):
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-datetime")], self.algorithms,
repetitions=1,
results_path=Path(tmp_path))
timeeval.run()
results = timeeval.get_results(aggregated=False)
np.testing.assert_array_almost_equal(results["ROC_AUC"].values, [0.810225])
def test_mismatched_training_type(self):
algo = Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SEMI_SUPERVISED,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-datetime")], [algo],
repetitions=1,
results_path=Path(tmp_path),
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("training type", results.loc[0, "error_message"])
self.assertIn("incompatible", results.loc[0, "error_message"])
def test_mismatched_input_dimensionality(self):
algo = Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
input_dimensionality=InputDimensionality.UNIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path, training_type=["supervised"], dimensionality=["multivariate"])
timeeval = TimeEval(dmgr, [("test", "dataset-supervised-multivariate")], [algo],
repetitions=1,
results_path=tmp_path,
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("input dimensionality", results.loc[0, "error_message"])
self.assertIn("incompatible", results.loc[0, "error_message"])
def test_missing_training_dataset_timeeval(self):
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-int")], self.algorithms,
repetitions=1,
results_path=Path(tmp_path),
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("training dataset", results.loc[0, "error_message"])
self.assertIn("not found", results.loc[0, "error_message"])
def test_missing_training_dataset_experiment(self):
exp = Experiment(
dataset=Dataset(
datasetId=("test", "dataset-datetime"),
dataset_type="synthetic",
training_type=TrainingType.SUPERVISED,
num_anomalies=1,
dimensions=1,
length=3000,
contamination=0.0002777777777777778,
min_anomaly_length=1,
median_anomaly_length=1,
max_anomaly_length=1,
period_size=None
),
algorithm=self.algorithms[0],
params={},
params_id=hash_dict({}),
repetition=0,
base_results_dir=Path("tmp_path"),
resource_constraints=ResourceConstraints(),
metrics=Metric.default_list(),
resolved_test_dataset_path=self.dmgr.get_dataset_path(("test", "dataset-datetime")),
resolved_train_dataset_path=None
)
with self.assertRaises(ValueError) as e:
exp._perform_training()
self.assertIn("No training dataset", str(e.exception))
def test_dont_skip_invalid_combinations(self):
datasets = [self.dmgr.get(d) for d in self.dmgr.select()]
exps = Experiments(
dmgr=self.dmgr,
datasets=datasets,
algorithms=self.algorithms,
metrics=Metric.default_list(),
base_result_path=Path("tmp_path"),
skip_invalid_combinations=False
)
self.assertEqual(len(exps), len(datasets) * len(self.algorithms))
def test_skip_invalid_combinations(self):
datasets = [self.dmgr.get(d) for d in self.dmgr.select()]
exps = Experiments(
dmgr=self.dmgr,
datasets=datasets,
algorithms=self.algorithms,
metrics=Metric.default_list(),
base_result_path=Path("tmp_path"),
skip_invalid_combinations=True
)
self.assertEqual(len(exps), 1)
exp = list(exps)[0]
self.assertEqual(exp.dataset.training_type, exp.algorithm.training_type)
self.assertEqual(exp.dataset.input_dimensionality, exp.algorithm.input_dimensionality)
def test_force_training_type_match(self):
algo = Algorithm(
name="supervised_deviating_from_mean2",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SUPERVISED,
input_dimensionality=InputDimensionality.MULTIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path,
training_type=["unsupervised", "semi-supervised", "supervised", "supervised"],
dimensionality=["univariate", "univariate", "univariate", "multivariate"])
datasets = [dmgr.get(d) for d in dmgr.select()]
exps = Experiments(
dmgr=dmgr,
datasets=datasets,
algorithms=self.algorithms + [algo],
metrics=Metric.default_list(),
base_result_path=tmp_path,
force_training_type_match=True
)
self.assertEqual(len(exps), 3)
exps = list(exps)
# algo1 and dataset 3
exp = exps[0]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.UNIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
# algo2 and dataset 4
exp = exps[1]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
# algo1 and dataset 3
exp = exps[2]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
def test_force_dimensionality_match(self):
algo = Algorithm(
name="supervised_deviating_from_mean2",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.UNSUPERVISED,
input_dimensionality=InputDimensionality.MULTIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path,
training_type=["unsupervised", "supervised", "supervised", "unsupervised"],
dimensionality=["univariate", "multivariate", "univariate", "multivariate"])
datasets = [dmgr.get(d) for d in dmgr.select()]
exps = Experiments(
dmgr=dmgr,
datasets=datasets,
algorithms=self.algorithms + [algo],
metrics=Metric.default_list(),
base_result_path=tmp_path,
force_dimensionality_match=True
)
self.assertEqual(len(exps), 3)
exps = list(exps)
# algo1 and dataset 2
exp = exps[0]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.UNIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
# algo2 and dataset 2
exp = exps[1]
self.assertEqual(exp.algorithm.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
# algo2 and dataset 4
exp = exps[2]
self.assertEqual(exp.algorithm.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
|
[
"tempfile.TemporaryDirectory",
"timeeval.utils.hash_dict.hash_dict",
"numpy.testing.assert_array_almost_equal",
"pathlib.Path",
"timeeval.TimeEval",
"timeeval.datasets.Dataset",
"tests.fixtures.algorithms.SupervisedDeviatingFromMean",
"timeeval.DatasetManager",
"timeeval.ResourceConstraints",
"timeeval.Metric.default_list",
"timeeval.datasets.DatasetRecord"
] |
[((615, 653), 'timeeval.DatasetManager', 'DatasetManager', (['"""./tests/example_data"""'], {}), "('./tests/example_data')\n", (629, 653), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((1207, 1236), 'timeeval.DatasetManager', 'DatasetManager', (["(path / 'data')"], {}), "(path / 'data')\n", (1221, 1236), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((2617, 2692), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (["results['ROC_AUC'].values", '[0.810225]'], {}), "(results['ROC_AUC'].values, [0.810225])\n", (2653, 2692), True, 'import numpy as np\n'), ((2281, 2310), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2308, 2310), False, 'import tempfile\n'), ((2974, 3003), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3001, 3003), False, 'import tempfile\n'), ((3863, 3892), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3890, 3892), False, 'import tempfile\n'), ((3929, 3943), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (3933, 3943), False, 'from pathlib import Path\n'), ((4078, 4222), 'timeeval.TimeEval', 'TimeEval', (['dmgr', "[('test', 'dataset-supervised-multivariate')]", '[algo]'], {'repetitions': '(1)', 'results_path': 'tmp_path', 'skip_invalid_combinations': '(False)'}), "(dmgr, [('test', 'dataset-supervised-multivariate')], [algo],\n repetitions=1, results_path=tmp_path, skip_invalid_combinations=False)\n", (4086, 4222), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((4683, 4712), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (4710, 4712), False, 'import tempfile\n'), ((7862, 7891), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (7889, 7891), False, 'import tempfile\n'), ((7928, 7942), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (7932, 7942), False, 'from pathlib import Path\n'), ((10174, 10203), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (10201, 10203), False, 'import tempfile\n'), ((10240, 10254), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (10244, 10254), False, 'from pathlib import Path\n'), ((1322, 1866), 'timeeval.datasets.DatasetRecord', 'DatasetRecord', ([], {'collection_name': '"""test"""', 'dataset_name': 'f"""dataset-{t}-{d}"""', 'train_path': '"""train.csv"""', 'test_path': '"""test.csv"""', 'dataset_type': '"""synthetic"""', 'datetime_index': '(False)', 'split_at': '(-1)', 'train_type': 't', 'train_is_normal': "(True if t == 'semi-supervised' else False)", 'input_type': 'd', 'length': '(10000)', 'dimensions': "(5 if d == 'multivariate' else 1)", 'contamination': '(0.1)', 'num_anomalies': '(1)', 'min_anomaly_length': '(100)', 'median_anomaly_length': '(100)', 'max_anomaly_length': '(100)', 'mean': '(0.0)', 'stddev': '(1.0)', 'trend': '"""no-trend"""', 'stationarity': '"""stationary"""', 'period_size': '(50)'}), "(collection_name='test', dataset_name=f'dataset-{t}-{d}',\n train_path='train.csv', test_path='test.csv', dataset_type='synthetic',\n datetime_index=False, split_at=-1, train_type=t, train_is_normal=True if\n t == 'semi-supervised' else False, input_type=d, length=10000,\n dimensions=5 if d == 'multivariate' else 1, contamination=0.1,\n num_anomalies=1, min_anomaly_length=100, median_anomaly_length=100,\n max_anomaly_length=100, mean=0.0, stddev=1.0, trend='no-trend',\n stationarity='stationary', period_size=50)\n", (1335, 1866), False, 'from timeeval.datasets import Dataset, DatasetRecord\n'), ((2833, 2862), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (2860, 2862), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((3713, 3742), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (3740, 3742), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((5382, 5674), 'timeeval.datasets.Dataset', 'Dataset', ([], {'datasetId': "('test', 'dataset-datetime')", 'dataset_type': '"""synthetic"""', 'training_type': 'TrainingType.SUPERVISED', 'num_anomalies': '(1)', 'dimensions': '(1)', 'length': '(3000)', 'contamination': '(0.0002777777777777778)', 'min_anomaly_length': '(1)', 'median_anomaly_length': '(1)', 'max_anomaly_length': '(1)', 'period_size': 'None'}), "(datasetId=('test', 'dataset-datetime'), dataset_type='synthetic',\n training_type=TrainingType.SUPERVISED, num_anomalies=1, dimensions=1,\n length=3000, contamination=0.0002777777777777778, min_anomaly_length=1,\n median_anomaly_length=1, max_anomaly_length=1, period_size=None)\n", (5389, 5674), False, 'from timeeval.datasets import Dataset, DatasetRecord\n'), ((5941, 5954), 'timeeval.utils.hash_dict.hash_dict', 'hash_dict', (['{}'], {}), '({})\n', (5950, 5954), False, 'from timeeval.utils.hash_dict import hash_dict\n'), ((6011, 6027), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (6015, 6027), False, 'from pathlib import Path\n'), ((6062, 6083), 'timeeval.ResourceConstraints', 'ResourceConstraints', ([], {}), '()\n', (6081, 6083), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6105, 6126), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (6124, 6126), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6693, 6714), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (6712, 6714), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6745, 6761), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (6749, 6761), False, 'from pathlib import Path\n'), ((7151, 7172), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (7170, 7172), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((7203, 7219), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (7207, 7219), False, 'from pathlib import Path\n'), ((7659, 7688), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (7686, 7688), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((9969, 9998), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (9996, 9998), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((781, 810), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (808, 810), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((2508, 2522), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (2512, 2522), False, 'from pathlib import Path\n'), ((3192, 3206), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (3196, 3206), False, 'from pathlib import Path\n'), ((4905, 4919), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (4909, 4919), False, 'from pathlib import Path\n'), ((8452, 8473), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (8471, 8473), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((10763, 10784), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (10782, 10784), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n')]
|
#==========================================================================================
# A very clumsy attemp to read and write data stored in csv files
# because I have tried hard to write cutomized data file in .npz and .pt but both gave trouble
# so I gave up and now use the old good csv--->but everything is a string so I need to convert everyhing
# resources from https://docs.python.org/3.6/library/csv.html#module-contents
# https://code.tutsplus.com/tutorials/how-to-read-and-write-csv-files-in-python--cms-29907
# and https://github.com/utkuozbulak/pytorch-custom-dataset-examples
#==========================================================================================
import random, string, copy, math, os, sys, csv
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import torch
#importing pyTorch's neural network object + optimizer
from torch import nn, optim
#import functions like ReLU and log softmax
import torch.nn.functional as F
from torchvision import datasets, transforms
# everything must be float/long data type
# IMPORTANT NOTEs: pytorch only takes 0-based labels, so last col is just
# 0=256, 1=512, 2=1024, 3=2048, 4=4096, 5=8192
data = [
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 1, '512'],
# first 14
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 0, '256'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 1, '512']
]
def writeCSV():
with open('data/data.csv', 'w', newline='') as dataFile:
writer = csv.writer(dataFile)
writer.writerows(data)
print("Writing complete")
# need to rewrite the csv file everytime we add new data
writeCSV()
def readCSV():
with open('data/data.csv', newline='') as dataFile:
reader = csv.reader(dataFile)
for row in reader:
print(row)
def customCSV(csvPath):
dataset = pd.read_csv(csvPath, header=None)
xLocation = np.asarray(dataset.iloc[:, 0])
xEmptySquare = np.asarray(dataset.iloc[:, 1])
xMono = np.asarray(dataset.iloc[:, 2])
xSmooth = np.asarray(dataset.iloc[:, 3])
parameters = []
for row in range(len(xLocation)):
parameters.append([xLocation[row], xEmptySquare[row], xMono[row], xSmooth[row] ])
parameters = np.array(parameters)
# Second column is the labels, datatype: numpy array, float
labels = np.asarray(dataset.iloc[:, 4])
#print(labels)
return dataset, parameters, labels
#dataset, parameters, labels = customCSV('data/data.csv')
|
[
"pandas.read_csv",
"csv.writer",
"numpy.asarray",
"numpy.array",
"csv.reader"
] |
[((2653, 2686), 'pandas.read_csv', 'pd.read_csv', (['csvPath'], {'header': 'None'}), '(csvPath, header=None)\n', (2664, 2686), True, 'import pandas as pd\n'), ((2708, 2738), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 0]'], {}), '(dataset.iloc[:, 0])\n', (2718, 2738), True, 'import numpy as np\n'), ((2762, 2792), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 1]'], {}), '(dataset.iloc[:, 1])\n', (2772, 2792), True, 'import numpy as np\n'), ((2809, 2839), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 2]'], {}), '(dataset.iloc[:, 2])\n', (2819, 2839), True, 'import numpy as np\n'), ((2858, 2888), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 3]'], {}), '(dataset.iloc[:, 3])\n', (2868, 2888), True, 'import numpy as np\n'), ((3071, 3091), 'numpy.array', 'np.array', (['parameters'], {}), '(parameters)\n', (3079, 3091), True, 'import numpy as np\n'), ((3178, 3208), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 4]'], {}), '(dataset.iloc[:, 4])\n', (3188, 3208), True, 'import numpy as np\n'), ((2298, 2318), 'csv.writer', 'csv.writer', (['dataFile'], {}), '(dataFile)\n', (2308, 2318), False, 'import random, string, copy, math, os, sys, csv\n'), ((2539, 2559), 'csv.reader', 'csv.reader', (['dataFile'], {}), '(dataFile)\n', (2549, 2559), False, 'import random, string, copy, math, os, sys, csv\n')]
|
import os
import numpy as np
# import jax.numpy as jnp
from sklearn.decomposition import TruncatedSVD
def Temporal_basis_POD(K, SAVE_T_POD=False, FOLDER_OUT='./',n_Modes=10):
"""
This method computes the POD basis. For some theoretical insights, you can find
the theoretical background of the proper orthogonal decomposition in a nutshell here:
https://youtu.be/8fhupzhAR_M
--------------------------------------------------------------------------------------------------------------------
Parameters:
----------
:param FOLDER_OUT: str
Folder in which the results will be saved (if SAVE_T_POD=True)
:param K: np.array
Temporal correlation matrix
:param SAVE_T_POD: bool
A flag deciding whether the results are saved on disk or not. If the MEMORY_SAVING feature is active, it is
switched True by default.
:param n_Modes: int
number of modes that will be computed
--------------------------------------------------------------------------------------------------------------------
Returns:
--------
:return: Psi_P: np.array
POD Psis
:return: Sigma_P: np.array
POD Sigmas
"""
# Solver 1: Use the standard SVD
# Psi_P, Lambda_P, _ = np.linalg.svd(K)
# Sigma_P = np.sqrt(Lambda_P)
# Solver 2: Use randomized SVD ############## WARNING #################
svd = TruncatedSVD(n_Modes)
svd.fit_transform(K)
Psi_P = svd.components_.T
Lambda_P=svd.singular_values_
Sigma_P=np.sqrt(Lambda_P)
if SAVE_T_POD:
os.makedirs(FOLDER_OUT + "/POD/", exist_ok=True)
print("Saving POD temporal basis")
np.savez(FOLDER_OUT + '/POD/temporal_basis', Psis=Psi_P, Lambdas=Lambda_P, Sigmas=Sigma_P)
return Psi_P, Sigma_P
|
[
"os.makedirs",
"numpy.savez",
"numpy.sqrt",
"sklearn.decomposition.TruncatedSVD"
] |
[((1438, 1459), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', (['n_Modes'], {}), '(n_Modes)\n', (1450, 1459), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((1561, 1578), 'numpy.sqrt', 'np.sqrt', (['Lambda_P'], {}), '(Lambda_P)\n', (1568, 1578), True, 'import numpy as np\n'), ((1611, 1659), 'os.makedirs', 'os.makedirs', (["(FOLDER_OUT + '/POD/')"], {'exist_ok': '(True)'}), "(FOLDER_OUT + '/POD/', exist_ok=True)\n", (1622, 1659), False, 'import os\n'), ((1711, 1805), 'numpy.savez', 'np.savez', (["(FOLDER_OUT + '/POD/temporal_basis')"], {'Psis': 'Psi_P', 'Lambdas': 'Lambda_P', 'Sigmas': 'Sigma_P'}), "(FOLDER_OUT + '/POD/temporal_basis', Psis=Psi_P, Lambdas=Lambda_P,\n Sigmas=Sigma_P)\n", (1719, 1805), True, 'import numpy as np\n')]
|
import numpy as np
import pandas as pd
import torch
import src.configuration as C
import src.dataset as dataset
import src.models as models
import src.utils as utils
from pathlib import Path
from fastprogress import progress_bar
if __name__ == "__main__":
args = utils.get_sed_parser().parse_args()
config = utils.load_config(args.config)
global_params = config["globals"]
output_dir = Path(global_params["output_dir"])
output_dir.mkdir(exist_ok=True, parents=True)
utils.set_seed(global_params["seed"])
device = C.get_device(global_params["device"])
df, datadir = C.get_metadata(config)
splitter = C.get_split(config)
for i, (_, val_idx) in enumerate(splitter.split(df, y=df["ebird_code"])):
if i not in global_params["folds"]:
continue
val_df = df.loc[val_idx, :].reset_index(drop=True)
loader = C.get_sed_inference_loader(val_df, datadir, config)
model = models.get_model_for_inference(config,
global_params["weights"][i])
if not torch.cuda.is_available():
device = torch.device("cpu")
else:
device = torch.device("cuda")
model.to(device)
model.eval()
estimated_event_list = []
for batch in progress_bar(loader):
waveform = batch["waveform"]
ebird_code = batch["ebird_code"][0]
wav_name = batch["wav_name"][0]
target = batch["targets"].detach().cpu().numpy()[0]
global_time = 0.0
if waveform.ndim == 3:
waveform = waveform.squeeze(0)
batch_size = 32
whole_size = waveform.size(0)
if whole_size % batch_size == 0:
n_iter = whole_size // batch_size
else:
n_iter = whole_size // batch_size + 1
for index in range(n_iter):
iter_batch = waveform[index * batch_size:(index + 1) * batch_size]
if iter_batch.ndim == 1:
iter_batch = iter_batch.unsqueeze(0)
iter_batch = iter_batch.to(device)
with torch.no_grad():
prediction = model(iter_batch)
framewise_output = prediction["framewise_output"].detach(
).cpu().numpy()
thresholded = framewise_output >= args.threshold
target_indices = np.argwhere(target).reshape(-1)
for short_clip in thresholded:
for target_idx in target_indices:
if short_clip[:, target_idx].mean() == 0:
pass
else:
detected = np.argwhere(
short_clip[:, target_idx]).reshape(-1)
head_idx = 0
tail_idx = 0
while True:
if (tail_idx + 1 == len(detected)) or (
detected[tail_idx + 1] -
detected[tail_idx] != 1):
onset = 0.01 * detected[head_idx] + global_time
offset = 0.01 * detected[tail_idx] + global_time
estimated_event = {
"filename": wav_name,
"ebird_code": dataset.INV_BIRD_CODE[target_idx],
"onset": onset,
"offset": offset
}
estimated_event_list.append(estimated_event)
head_idx = tail_idx + 1
tail_idx = tail_idx + 1
if head_idx > len(detected):
break
else:
tail_idx = tail_idx + 1
global_time += 5.0
estimated_event_df = pd.DataFrame(estimated_event_list)
save_filename = global_params["save_path"].replace(".csv", "")
save_filename += f"_th{args.threshold}" + ".csv"
save_path = output_dir / save_filename
if save_path.exists():
event_level_labels = pd.read_csv(save_path)
estimated_event_df = pd.concat(
[event_level_labels, estimated_event_df], axis=0,
sort=False).reset_index(drop=True)
estimated_event_df.to_csv(save_path, index=False)
else:
estimated_event_df.to_csv(save_path, index=False)
|
[
"src.utils.get_sed_parser",
"src.configuration.get_metadata",
"src.models.get_model_for_inference",
"pathlib.Path",
"fastprogress.progress_bar",
"src.configuration.get_device",
"src.configuration.get_split",
"pandas.read_csv",
"src.configuration.get_sed_inference_loader",
"torch.cuda.is_available",
"pandas.concat",
"numpy.argwhere",
"src.utils.load_config",
"pandas.DataFrame",
"torch.no_grad",
"src.utils.set_seed",
"torch.device"
] |
[((321, 351), 'src.utils.load_config', 'utils.load_config', (['args.config'], {}), '(args.config)\n', (338, 351), True, 'import src.utils as utils\n'), ((409, 442), 'pathlib.Path', 'Path', (["global_params['output_dir']"], {}), "(global_params['output_dir'])\n", (413, 442), False, 'from pathlib import Path\n'), ((498, 535), 'src.utils.set_seed', 'utils.set_seed', (["global_params['seed']"], {}), "(global_params['seed'])\n", (512, 535), True, 'import src.utils as utils\n'), ((549, 586), 'src.configuration.get_device', 'C.get_device', (["global_params['device']"], {}), "(global_params['device'])\n", (561, 586), True, 'import src.configuration as C\n'), ((606, 628), 'src.configuration.get_metadata', 'C.get_metadata', (['config'], {}), '(config)\n', (620, 628), True, 'import src.configuration as C\n'), ((644, 663), 'src.configuration.get_split', 'C.get_split', (['config'], {}), '(config)\n', (655, 663), True, 'import src.configuration as C\n'), ((885, 936), 'src.configuration.get_sed_inference_loader', 'C.get_sed_inference_loader', (['val_df', 'datadir', 'config'], {}), '(val_df, datadir, config)\n', (911, 936), True, 'import src.configuration as C\n'), ((953, 1020), 'src.models.get_model_for_inference', 'models.get_model_for_inference', (['config', "global_params['weights'][i]"], {}), "(config, global_params['weights'][i])\n", (983, 1020), True, 'import src.models as models\n'), ((1314, 1334), 'fastprogress.progress_bar', 'progress_bar', (['loader'], {}), '(loader)\n', (1326, 1334), False, 'from fastprogress import progress_bar\n'), ((4174, 4208), 'pandas.DataFrame', 'pd.DataFrame', (['estimated_event_list'], {}), '(estimated_event_list)\n', (4186, 4208), True, 'import pandas as pd\n'), ((272, 294), 'src.utils.get_sed_parser', 'utils.get_sed_parser', ([], {}), '()\n', (292, 294), True, 'import src.utils as utils\n'), ((1084, 1109), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1107, 1109), False, 'import torch\n'), ((1132, 1151), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1144, 1151), False, 'import torch\n'), ((1187, 1207), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1199, 1207), False, 'import torch\n'), ((4448, 4470), 'pandas.read_csv', 'pd.read_csv', (['save_path'], {}), '(save_path)\n', (4459, 4470), True, 'import pandas as pd\n'), ((2177, 2192), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2190, 2192), False, 'import torch\n'), ((4504, 4575), 'pandas.concat', 'pd.concat', (['[event_level_labels, estimated_event_df]'], {'axis': '(0)', 'sort': '(False)'}), '([event_level_labels, estimated_event_df], axis=0, sort=False)\n', (4513, 4575), True, 'import pandas as pd\n'), ((2458, 2477), 'numpy.argwhere', 'np.argwhere', (['target'], {}), '(target)\n', (2469, 2477), True, 'import numpy as np\n'), ((2759, 2797), 'numpy.argwhere', 'np.argwhere', (['short_clip[:, target_idx]'], {}), '(short_clip[:, target_idx])\n', (2770, 2797), True, 'import numpy as np\n')]
|
import os
import numpy as np
from ._population import Population
from pychemia import pcm_log
from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, \
angle_between_vectors
from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput
from pychemia.crystal import KPoints
class NonCollinearMagMoms(Population):
def __init__(self, name, source_dir='.', mag_atoms=None, magmom_magnitude=2.0, distance_tolerance=0.1):
Population.__init__(self, name, 'global')
if not os.path.isfile(source_dir + os.sep + 'INCAR'):
raise ValueError("INCAR not found")
if not os.path.isfile(source_dir + os.sep + 'POSCAR'):
raise ValueError("POSCAR not found")
self.input = read_incar(source_dir + os.sep + 'INCAR')
magmom = np.array(self.input.get_value('MAGMOM')).reshape((-1, 3))
self.structure = read_poscar(source_dir + os.sep + 'POSCAR')
if mag_atoms is None:
self.mag_atoms = list(np.where(np.apply_along_axis(np.linalg.norm, 1, magmom) > 0.0)[0])
self.mag_atoms = [int(x) for x in self.mag_atoms]
else:
self.mag_atoms = mag_atoms
self.magmom_magnitude = magmom_magnitude
self.distance_tolerance = distance_tolerance
def __str__(self):
ret = ' Population NonColl\n\n'
ret += ' Name: %s\n' % self.name
ret += ' Tag: %s\n' % self.tag
ret += ' Formula: %s\n' % self.structure.formula
ret += ' Members: %d\n' % len(self.members)
ret += ' Actives: %d\n' % len(self.actives)
ret += ' Evaluated: %d\n' % len(self.evaluated)
return ret
@property
def to_dict(self):
return {'name': self.name,
'tag': self.tag,
'mag_atoms': self.mag_atoms,
'magmom_magnitude': self.magmom_magnitude,
'distance_tolerance': self.distance_tolerance}
@staticmethod
def from_dict(self, population_dict):
return NonCollinearMagMoms(name=population_dict['name'],
mag_atoms=population_dict['mag_atoms'],
magmom_magnitude=population_dict['magmom_magnitude'],
distance_tolerance=population_dict['distance_tolerance'])
def new_entry(self, data, active=True):
data = np.array(data)
# Magnetic moments are stored in spherical coordinates
properties = {'magmom': list(data.flatten())}
status = {self.tag: active}
entry={'structure': self.structure.to_dict, 'properties': properties, 'status': status}
entry_id = self.insert_entry(entry)
pcm_log.debug('Added new entry: %s with tag=%s: %s' % (str(entry_id), self.tag, str(active)))
return entry_id
def is_evaluated(self, entry_id):
entry = self.get_entry(entry_id, {'_id': 0, 'properties': 1})
if 'energy' in entry['properties']:
return True
else:
return False
def check_duplicates(self, ids):
selection = self.ids_sorted(ids)
ret = {}
for i in range(len(ids) - 1):
for j in range(i, len(ids)):
if self.distance(selection[i], selection[j]) < self.distance_tolerance:
ret[selection[j]] = selection[i]
return ret
def distance(self, entry_id, entry_jd):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = spherical_to_cartesian(entry['properties']['magmom'])
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_j = spherical_to_cartesian(entry['properties']['magmom'])
magmom_ixyz = spherical_to_cartesian(magmom_i)
magmom_jxyz = spherical_to_cartesian(magmom_j)
distance = np.sum(angle_between_vectors(magmom_ixyz, magmom_jxyz))
distance /= len(self.mag_atoms)
return distance
def move_random(self, entry_id, factor=0.2, in_place=False, kind='move'):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
# Magnetic Momenta are stored in spherical coordinates
magmom_i = spherical_to_cartesian(entry['properties']['magmom'])
# Converted into cartesians
magmom_xyz = spherical_to_cartesian(magmom_i)
# Randomly disturbed using the factor
magmom_xyz += factor * np.random.rand((self.structure.natom, 3)) - factor / 2
# Reconverting to spherical coordinates
magmom_new = cartesian_to_spherical(magmom_xyz)
# Resetting magnitudes
magmom_new[:, 0] = self.magmom_magnitude
properties = {'magmom': magmom_new}
if in_place:
return self.update_properties(entry_id, new_properties=properties)
else:
return self.new_entry(magmom_new, active=False)
def move(self, entry_id, entry_jd, factor=0.2, in_place=False):
magmom_new_xyz = np.zeros((self.structure.natom, 3))
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_ixyz = spherical_to_cartesian(magmom_i)
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_j = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_jxyz = spherical_to_cartesian(magmom_j)
for i in range(self.structure.natom):
if magmom_ixyz[i][0] > 0 and magmom_jxyz[i][0] > 0:
magmom_new_xyz[i] = rotate_towards_axis(magmom_ixyz[i], magmom_jxyz[i],
fraction=factor)
magmom_new = cartesian_to_spherical(magmom_new_xyz)
magmom_new[:, 0] = self.magmom_magnitude
properties = {'magmom': magmom_new}
if in_place:
return self.update_properties(entry_id, new_properties=properties)
else:
return self.new_entry(magmom_new, active=False)
def value(self, entry_id):
entry = self.get_entry(entry_id, {'properties.energy': 1})
if 'energy' in entry['properties']:
return entry['properties']['energy']
else:
return None
def str_entry(self, entry_id):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
print(np.array(entry['properties']['magmom']).reshape((-1, 3)))
def get_duplicates(self, ids):
return None
def add_random(self):
"""
:return:
"""
n = self.structure.natom
a = self.magmom_magnitude * np.ones(n)
b = 2 * np.pi * np.random.rand(n)
c = np.pi * np.random.rand(n)
print(a.shape)
print(b.shape)
print(c.shape)
magmom = np.vstack((a, b, c)).T
for i in range(self.structure.natom):
if i not in self.mag_atoms:
magmom[i, :] = 0.0
return self.new_entry(magmom), None
def recover(self):
data = self.get_population_info()
if data is not None:
self.mag_atoms = data['mag_atoms']
self.distance_tolerance = data['distance_tolerance']
self.name = data['name']
self.magmom_magnitude = data['magmom_magnitude']
def cross(self, ids):
entry_id = ids[0]
entry_jd = ids[1]
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = np.array(entry['properties']['magmom']).reshape((-1, 3))
entry = self.get_entry(entry_jd, {'properties.magmom': 1})
magmom_j = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_inew = np.zeros((self.structure.natom, 3))
magmom_jnew = np.zeros((self.structure.natom, 3))
for i in range(self.structure.natom):
rnd = np.random.rand()
if rnd < 0.5:
magmom_inew[i] = magmom_j[i]
magmom_jnew[i] = magmom_i[i]
else:
magmom_inew[i] = magmom_i[i]
magmom_jnew[i] = magmom_j[i]
entry_id = self.new_entry(magmom_inew, active=True)
entry_jd = self.new_entry(magmom_jnew, active=True)
return entry_id, entry_jd
def prepare_folder(self, entry_id, workdir, binary='vasp', source_dir='.'):
vj = VaspJob()
structure = self.get_structure(entry_id)
kp = KPoints.optimized_grid(structure.lattice, kp_density=2E4)
vj.initialize(structure, workdir=workdir, kpoints=kp, binary=binary)
vj.clean()
vj.input_variables = read_incar(source_dir + '/INCAR')
magmom_sph = self.get_entry(entry_id, {'properties.magmom': 1})['properties']['magmom']
magmom_car = spherical_to_cartesian(magmom_sph)
vj.input_variables.variables['MAGMOM'] = [float(x) for x in magmom_car.flatten()]
vj.input_variables.variables['M_CONSTR'] = [float(x) for x in magmom_car.flatten()]
vj.input_variables.variables['IBRION'] = -1
vj.input_variables.variables['LWAVE'] = True
vj.input_variables.variables['EDIFF'] = 1E-5
vj.input_variables.variables['LAMBDA'] = 10
vj.input_variables.variables['NSW'] = 0
vj.input_variables.variables['I_CONSTRAINED_M'] = 1
vj.set_inputs()
def collect_data(self, entry_id, workdir):
if os.path.isfile(workdir + '/OUTCAR'):
vo = VaspOutput(workdir + '/OUTCAR')
if 'energy' in vo.final_data:
if 'free_energy' in vo.final_data['energy']:
energy = vo.final_data['energy']['free_energy']
print('Uploading energy data for %s' % entry_id)
self.set_in_properties(entry_id, 'energy', energy)
return True
else:
return False
else:
return False
else:
return False
|
[
"pychemia.code.vasp.VaspJob",
"numpy.ones",
"pychemia.code.vasp.read_poscar",
"pychemia.utils.mathematics.angle_between_vectors",
"pychemia.code.vasp.read_incar",
"pychemia.utils.mathematics.spherical_to_cartesian",
"pychemia.crystal.KPoints.optimized_grid",
"numpy.random.rand",
"os.path.isfile",
"numpy.array",
"numpy.zeros",
"numpy.apply_along_axis",
"numpy.vstack",
"pychemia.utils.mathematics.rotate_towards_axis",
"pychemia.code.vasp.VaspOutput",
"pychemia.utils.mathematics.cartesian_to_spherical"
] |
[((785, 826), 'pychemia.code.vasp.read_incar', 'read_incar', (["(source_dir + os.sep + 'INCAR')"], {}), "(source_dir + os.sep + 'INCAR')\n", (795, 826), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((928, 971), 'pychemia.code.vasp.read_poscar', 'read_poscar', (["(source_dir + os.sep + 'POSCAR')"], {}), "(source_dir + os.sep + 'POSCAR')\n", (939, 971), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((2482, 2496), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2490, 2496), True, 'import numpy as np\n'), ((3598, 3651), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (3620, 3651), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3738, 3791), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (3760, 3791), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3814, 3846), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (3836, 3846), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3869, 3901), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_j'], {}), '(magmom_j)\n', (3891, 3901), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4270, 4323), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (4292, 4323), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4381, 4413), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (4403, 4413), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4615, 4649), 'pychemia.utils.mathematics.cartesian_to_spherical', 'cartesian_to_spherical', (['magmom_xyz'], {}), '(magmom_xyz)\n', (4637, 4649), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5043, 5078), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (5051, 5078), True, 'import numpy as np\n'), ((5244, 5276), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (5266, 5276), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5442, 5474), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_j'], {}), '(magmom_j)\n', (5464, 5474), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5796, 5834), 'pychemia.utils.mathematics.cartesian_to_spherical', 'cartesian_to_spherical', (['magmom_new_xyz'], {}), '(magmom_new_xyz)\n', (5818, 5834), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((7760, 7795), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (7768, 7795), True, 'import numpy as np\n'), ((7818, 7853), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (7826, 7853), True, 'import numpy as np\n'), ((8409, 8418), 'pychemia.code.vasp.VaspJob', 'VaspJob', ([], {}), '()\n', (8416, 8418), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((8481, 8542), 'pychemia.crystal.KPoints.optimized_grid', 'KPoints.optimized_grid', (['structure.lattice'], {'kp_density': '(20000.0)'}), '(structure.lattice, kp_density=20000.0)\n', (8503, 8542), False, 'from pychemia.crystal import KPoints\n'), ((8664, 8697), 'pychemia.code.vasp.read_incar', 'read_incar', (["(source_dir + '/INCAR')"], {}), "(source_dir + '/INCAR')\n", (8674, 8697), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((8815, 8849), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_sph'], {}), '(magmom_sph)\n', (8837, 8849), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((9433, 9468), 'os.path.isfile', 'os.path.isfile', (["(workdir + '/OUTCAR')"], {}), "(workdir + '/OUTCAR')\n", (9447, 9468), False, 'import os\n'), ((557, 602), 'os.path.isfile', 'os.path.isfile', (["(source_dir + os.sep + 'INCAR')"], {}), "(source_dir + os.sep + 'INCAR')\n", (571, 602), False, 'import os\n'), ((667, 713), 'os.path.isfile', 'os.path.isfile', (["(source_dir + os.sep + 'POSCAR')"], {}), "(source_dir + os.sep + 'POSCAR')\n", (681, 713), False, 'import os\n'), ((3928, 3975), 'pychemia.utils.mathematics.angle_between_vectors', 'angle_between_vectors', (['magmom_ixyz', 'magmom_jxyz'], {}), '(magmom_ixyz, magmom_jxyz)\n', (3949, 3975), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((6702, 6712), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (6709, 6712), True, 'import numpy as np\n'), ((6737, 6754), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (6751, 6754), True, 'import numpy as np\n'), ((6775, 6792), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (6789, 6792), True, 'import numpy as np\n'), ((6879, 6899), 'numpy.vstack', 'np.vstack', (['(a, b, c)'], {}), '((a, b, c))\n', (6888, 6899), True, 'import numpy as np\n'), ((7918, 7934), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (7932, 7934), True, 'import numpy as np\n'), ((9487, 9518), 'pychemia.code.vasp.VaspOutput', 'VaspOutput', (["(workdir + '/OUTCAR')"], {}), "(workdir + '/OUTCAR')\n", (9497, 9518), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((4491, 4532), 'numpy.random.rand', 'np.random.rand', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (4505, 4532), True, 'import numpy as np\n'), ((5165, 5204), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (5173, 5204), True, 'import numpy as np\n'), ((5363, 5402), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (5371, 5402), True, 'import numpy as np\n'), ((5622, 5690), 'pychemia.utils.mathematics.rotate_towards_axis', 'rotate_towards_axis', (['magmom_ixyz[i]', 'magmom_jxyz[i]'], {'fraction': 'factor'}), '(magmom_ixyz[i], magmom_jxyz[i], fraction=factor)\n', (5641, 5690), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((7538, 7577), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (7546, 7577), True, 'import numpy as np\n'), ((7681, 7720), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (7689, 7720), True, 'import numpy as np\n'), ((6450, 6489), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (6458, 6489), True, 'import numpy as np\n'), ((1045, 1091), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.linalg.norm', '(1)', 'magmom'], {}), '(np.linalg.norm, 1, magmom)\n', (1064, 1091), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""Generator reserve plots.
This module creates plots of reserve provision and shortage at the generation
and region level.
@author: <NAME>
"""
import logging
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import marmot.config.mconfig as mconfig
import marmot.plottingmodules.plotutils.plot_library as plotlib
from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper
from marmot.plottingmodules.plotutils.plot_exceptions import (MissingInputData, MissingZoneData)
class MPlot(PlotDataHelper):
"""reserves MPlot class.
All the plotting modules use this same class name.
This class contains plotting methods that are grouped based on the
current module name.
The reserves.py module contains methods that are
related to reserve provision and shortage.
MPlot inherits from the PlotDataHelper class to assist in creating figures.
"""
def __init__(self, argument_dict: dict):
"""
Args:
argument_dict (dict): Dictionary containing all
arguments passed from MarmotPlot.
"""
# iterate over items in argument_dict and set as properties of class
# see key_list in Marmot_plot_main for list of properties
for prop in argument_dict:
self.__setattr__(prop, argument_dict[prop])
# Instantiation of MPlotHelperFunctions
super().__init__(self.Marmot_Solutions_folder, self.AGG_BY, self.ordered_gen,
self.PLEXOS_color_dict, self.Scenarios, self.ylabels,
self.xlabels, self.gen_names_dict, Region_Mapping=self.Region_Mapping)
self.logger = logging.getLogger('marmot_plot.'+__name__)
self.y_axes_decimalpt = mconfig.parser("axes_options","y_axes_decimalpt")
def reserve_gen_timeseries(self, figure_name: str = None, prop: str = None,
start: float = None, end: float= None,
timezone: str = "", start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a generation timeseries stackplot of total cumulative reserve provision by tech type.
The code will create either a facet plot or a single plot depending on
if the Facet argument is active.
If a facet plot is created, each scenario is plotted on a separate facet,
otherwise all scenarios are plotted on a single plot.
To make a facet plot, ensure the work 'Facet' is found in the figure_name.
Generation order is determined by the ordered_gen_categories.csv.
Args:
figure_name (str, optional): User defined figure output name. Used here
to determine if a Facet plot should be created.
Defaults to None.
prop (str, optional): Special argument used to adjust specific
plot settings. Controlled through the plot_select.csv.
Opinions available are:
- Peak Demand
- Date Range
Defaults to None.
start (float, optional): Used in conjunction with the prop argument.
Will define the number of days to plot before a certain event in
a timeseries plot, e.g Peak Demand.
Defaults to None.
end (float, optional): Used in conjunction with the prop argument.
Will define the number of days to plot after a certain event in
a timeseries plot, e.g Peak Demand.
Defaults to None.
timezone (str, optional): The timezone to display on the x-axes.
Defaults to "".
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
# If not facet plot, only plot first scenario
facet=False
if 'Facet' in figure_name:
facet = True
if not facet:
Scenarios = [self.Scenarios[0]]
else:
Scenarios = self.Scenarios
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True,"reserves_generators_Provision",self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
xdimension, ydimension = self.setup_facet_xy_dimensions(facet,multi_scenario=Scenarios)
grid_size = xdimension*ydimension
excess_axs = grid_size - len(Scenarios)
fig1, axs = plotlib.setup_plot(xdimension,ydimension)
plt.subplots_adjust(wspace=0.05, hspace=0.2)
data_tables = []
unique_tech_names = []
for n, scenario in enumerate(Scenarios):
self.logger.info(f"Scenario = {scenario}")
reserve_provision_timeseries = self["reserves_generators_Provision"].get(scenario)
#Check if zone has reserves, if not skips
try:
reserve_provision_timeseries = reserve_provision_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
reserve_provision_timeseries = self.df_process_gen_inputs(reserve_provision_timeseries)
if reserve_provision_timeseries.empty is True:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
# unitconversion based off peak generation hour, only checked once
if n == 0:
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(reserve_provision_timeseries.sum(axis=1)))
if prop == "Peak Demand":
self.logger.info("Plotting Peak Demand period")
total_reserve = reserve_provision_timeseries.sum(axis=1)/unitconversion['divisor']
peak_reserve_t = total_reserve.idxmax()
start_date = peak_reserve_t - dt.timedelta(days=start)
end_date = peak_reserve_t + dt.timedelta(days=end)
reserve_provision_timeseries = reserve_provision_timeseries[start_date : end_date]
Peak_Reserve = total_reserve[peak_reserve_t]
elif prop == 'Date Range':
self.logger.info(f"Plotting specific date range: \
{str(start_date_range)} to {str(end_date_range)}")
reserve_provision_timeseries = reserve_provision_timeseries[start_date_range : end_date_range]
else:
self.logger.info("Plotting graph for entire timeperiod")
reserve_provision_timeseries = reserve_provision_timeseries/unitconversion['divisor']
scenario_names = pd.Series([scenario] * len(reserve_provision_timeseries),name = 'Scenario')
data_table = reserve_provision_timeseries.add_suffix(f" ({unitconversion['units']})")
data_table = data_table.set_index([scenario_names],append = True)
data_tables.append(data_table)
plotlib.create_stackplot(axs, reserve_provision_timeseries, self.PLEXOS_color_dict, labels=reserve_provision_timeseries.columns,n=n)
PlotDataHelper.set_plot_timeseries_format(axs,n=n,minticks=4, maxticks=8)
if prop == "Peak Demand":
axs[n].annotate('Peak Reserve: \n' + str(format(int(Peak_Reserve), '.2f')) + ' {}'.format(unitconversion['units']),
xy=(peak_reserve_t, Peak_Reserve),
xytext=((peak_reserve_t + dt.timedelta(days=0.25)), (Peak_Reserve + Peak_Reserve*0.05)),
fontsize=13, arrowprops=dict(facecolor='black', width=3, shrink=0.1))
# create list of gen technologies
l1 = reserve_provision_timeseries.columns.tolist()
unique_tech_names.extend(l1)
if not data_tables:
self.logger.warning(f'No reserves in {region}')
out = MissingZoneData()
outputs[region] = out
continue
# create handles list of unique tech names then order
handles = np.unique(np.array(unique_tech_names)).tolist()
handles.sort(key = lambda i:self.ordered_gen.index(i))
handles = reversed(handles)
# create custom gen_tech legend
gen_tech_legend = []
for tech in handles:
legend_handles = [Patch(facecolor=self.PLEXOS_color_dict[tech],
alpha=1.0,
label=tech)]
gen_tech_legend.extend(legend_handles)
# Add legend
axs[grid_size-1].legend(handles=gen_tech_legend, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
#Remove extra axes
if excess_axs != 0:
PlotDataHelper.remove_excess_axs(axs,excess_axs,grid_size)
# add facet labels
self.add_facet_labels(fig1)
fig1.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
if mconfig.parser("plot_title_as_region"):
plt.title(region)
plt.ylabel(f"Reserve Provision ({unitconversion['units']})", color='black', rotation='vertical', labelpad=40)
data_table_out = pd.concat(data_tables)
outputs[region] = {'fig': fig1, 'data_table': data_table_out}
return outputs
def total_reserves_by_gen(self, start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a generation stacked barplot of total reserve provision by generator tech type.
A separate bar is created for each scenario.
Args:
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True,"reserves_generators_Provision",self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
Total_Reserves_Out = pd.DataFrame()
unique_tech_names = []
for scenario in self.Scenarios:
self.logger.info(f"Scenario = {scenario}")
reserve_provision_timeseries = self["reserves_generators_Provision"].get(scenario)
#Check if zone has reserves, if not skips
try:
reserve_provision_timeseries = reserve_provision_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
reserve_provision_timeseries = self.df_process_gen_inputs(reserve_provision_timeseries)
if reserve_provision_timeseries.empty is True:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
# Calculates interval step to correct for MWh of generation
interval_count = PlotDataHelper.get_sub_hour_interval_count(reserve_provision_timeseries)
# sum totals by fuel types
reserve_provision_timeseries = reserve_provision_timeseries/interval_count
reserve_provision = reserve_provision_timeseries.sum(axis=0)
reserve_provision.rename(scenario, inplace=True)
Total_Reserves_Out = pd.concat([Total_Reserves_Out, reserve_provision], axis=1, sort=False).fillna(0)
Total_Reserves_Out = self.create_categorical_tech_index(Total_Reserves_Out)
Total_Reserves_Out = Total_Reserves_Out.T
Total_Reserves_Out = Total_Reserves_Out.loc[:, (Total_Reserves_Out != 0).any(axis=0)]
if Total_Reserves_Out.empty:
out = MissingZoneData()
outputs[region] = out
continue
Total_Reserves_Out.index = Total_Reserves_Out.index.str.replace('_',' ')
Total_Reserves_Out.index = Total_Reserves_Out.index.str.wrap(5, break_long_words=False)
# Convert units
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(Total_Reserves_Out.sum()))
Total_Reserves_Out = Total_Reserves_Out/unitconversion['divisor']
data_table_out = Total_Reserves_Out.add_suffix(f" ({unitconversion['units']}h)")
# create figure
fig1, axs = plotlib.create_stacked_bar_plot(Total_Reserves_Out, self.PLEXOS_color_dict,
custom_tick_labels=self.custom_xticklabels)
# additional figure formatting
#fig1.set_ylabel(f"Total Reserve Provision ({unitconversion['units']}h)", color='black', rotation='vertical')
axs.set_ylabel(f"Total Reserve Provision ({unitconversion['units']}h)", color='black', rotation='vertical')
# create list of gen technologies
l1 = Total_Reserves_Out.columns.tolist()
unique_tech_names.extend(l1)
# create handles list of unique tech names then order
handles = np.unique(np.array(unique_tech_names)).tolist()
handles.sort(key = lambda i:self.ordered_gen.index(i))
handles = reversed(handles)
# create custom gen_tech legend
gen_tech_legend = []
for tech in handles:
legend_handles = [Patch(facecolor=self.PLEXOS_color_dict[tech],
alpha=1.0,label=tech)]
gen_tech_legend.extend(legend_handles)
# Add legend
axs.legend(handles=gen_tech_legend, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
if mconfig.parser("plot_title_as_region"):
axs.set_title(region)
outputs[region] = {'fig': fig1, 'data_table': data_table_out}
return outputs
def reg_reserve_shortage(self, **kwargs):
"""Creates a bar plot of reserve shortage for each region in MWh.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Shortage' argument is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Shortage", **kwargs)
return outputs
def reg_reserve_provision(self, **kwargs):
"""Creates a bar plot of reserve provision for each region in MWh.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Provision' argument is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Provision", **kwargs)
return outputs
def reg_reserve_shortage_hrs(self, **kwargs):
"""creates a bar plot of reserve shortage for each region in hrs.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Shortage' argument and count_hours=True is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Shortage", count_hours=True)
return outputs
def _reserve_bar_plots(self, data_set: str, count_hours: bool = False,
start_date_range: str = None,
end_date_range: str = None, **_):
"""internal _reserve_bar_plots method, creates 'Shortage', 'Provision' and 'Shortage' bar
plots
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
Args:
data_set (str): Identifies the reserve data set to use and pull
from the formatted h5 file.
count_hours (bool, optional): if True creates a 'Shortage' hours plot.
Defaults to False.
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True, f"reserve_{data_set}", self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
Data_Table_Out=pd.DataFrame()
reserve_total_chunk = []
for scenario in self.Scenarios:
self.logger.info(f'Scenario = {scenario}')
reserve_timeseries = self[f"reserve_{data_set}"].get(scenario)
# Check if zone has reserves, if not skips
try:
reserve_timeseries = reserve_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
interval_count = PlotDataHelper.get_sub_hour_interval_count(reserve_timeseries)
reserve_timeseries = reserve_timeseries.reset_index(["timestamp","Type","parent"],drop=False)
# Drop duplicates to remove double counting
reserve_timeseries.drop_duplicates(inplace=True)
# Set Type equal to parent value if Type equals '-'
reserve_timeseries['Type'] = reserve_timeseries['Type'].mask(reserve_timeseries['Type'] == '-', reserve_timeseries['parent'])
reserve_timeseries.set_index(["timestamp","Type","parent"],append=True,inplace=True)
# Groupby Type
if count_hours == False:
reserve_total = reserve_timeseries.groupby(["Type"]).sum()/interval_count
elif count_hours == True:
reserve_total = reserve_timeseries[reserve_timeseries[0]>0] #Filter for non zero values
reserve_total = reserve_total.groupby("Type").count()/interval_count
reserve_total.rename(columns={0:scenario},inplace=True)
reserve_total_chunk.append(reserve_total)
if reserve_total_chunk:
reserve_out = pd.concat(reserve_total_chunk,axis=1, sort='False')
reserve_out.columns = reserve_out.columns.str.replace('_',' ')
else:
reserve_out=pd.DataFrame()
# If no reserves return nothing
if reserve_out.empty:
out = MissingZoneData()
outputs[region] = out
continue
if count_hours == False:
# Convert units
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(reserve_out.sum()))
reserve_out = reserve_out/unitconversion['divisor']
Data_Table_Out = reserve_out.add_suffix(f" ({unitconversion['units']}h)")
else:
Data_Table_Out = reserve_out.add_suffix(" (hrs)")
# create color dictionary
color_dict = dict(zip(reserve_out.columns,self.color_list))
fig2,axs = plotlib.create_grouped_bar_plot(reserve_out, color_dict)
if count_hours == False:
axs.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, p: format(x, f',.{self.y_axes_decimalpt}f')))
axs.set_ylabel(f"Reserve {data_set} [{unitconversion['units']}h]", color='black', rotation='vertical')
elif count_hours == True:
axs.set_ylabel(f"Reserve {data_set} Hours", color='black', rotation='vertical')
handles, labels = axs.get_legend_handles_labels()
axs.legend(handles,labels, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
if mconfig.parser("plot_title_as_region"):
axs.set_title(region)
outputs[region] = {'fig': fig2,'data_table': Data_Table_Out}
return outputs
def reg_reserve_shortage_timeseries(self, figure_name: str = None,
timezone: str = "", start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a timeseries line plot of reserve shortage.
A line is plotted for each reserve type shortage.
The code will create either a facet plot or a single plot depending on
if the Facet argument is active.
If a facet plot is created, each scenario is plotted on a separate facet,
otherwise all scenarios are plotted on a single plot.
To make a facet plot, ensure the work 'Facet' is found in the figure_name.
Args:
figure_name (str, optional): User defined figure output name. Used here
to determine if a Facet plot should be created.
Defaults to None.
timezone (str, optional): The timezone to display on the x-axes.
Defaults to "".
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
facet=False
if 'Facet' in figure_name:
facet = True
# If not facet plot, only plot first scenario
if not facet:
Scenarios = [self.Scenarios[0]]
else:
Scenarios = self.Scenarios
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True, "reserve_Shortage", Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
xdimension, ydimension = self.setup_facet_xy_dimensions(facet,multi_scenario = Scenarios)
grid_size = xdimension*ydimension
excess_axs = grid_size - len(Scenarios)
fig3, axs = plotlib.setup_plot(xdimension,ydimension)
plt.subplots_adjust(wspace=0.05, hspace=0.2)
data_tables = []
unique_reserve_types = []
for n, scenario in enumerate(Scenarios):
self.logger.info(f'Scenario = {scenario}')
reserve_timeseries = self["reserve_Shortage"].get(scenario)
# Check if zone has reserves, if not skips
try:
reserve_timeseries = reserve_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
reserve_timeseries.reset_index(["timestamp","Type","parent"],drop=False,inplace=True)
reserve_timeseries = reserve_timeseries.drop_duplicates()
# Set Type equal to parent value if Type equals '-'
reserve_timeseries['Type'] = reserve_timeseries['Type'].mask(reserve_timeseries['Type'] == '-',
reserve_timeseries['parent'])
reserve_timeseries = reserve_timeseries.pivot(index='timestamp', columns='Type', values=0)
if pd.notna(start_date_range):
self.logger.info(f"Plotting specific date range: \
{str(start_date_range)} to {str(end_date_range)}")
reserve_timeseries = reserve_timeseries[start_date_range : end_date_range]
else:
self.logger.info("Plotting graph for entire timeperiod")
# create color dictionary
color_dict = dict(zip(reserve_timeseries.columns,self.color_list))
scenario_names = pd.Series([scenario] * len(reserve_timeseries),name = 'Scenario')
data_table = reserve_timeseries.add_suffix(" (MW)")
data_table = data_table.set_index([scenario_names],append = True)
data_tables.append(data_table)
for column in reserve_timeseries:
plotlib.create_line_plot(axs,reserve_timeseries,column,color_dict=color_dict,label=column, n=n)
axs[n].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, p: format(x, f',.{self.y_axes_decimalpt}f')))
axs[n].margins(x=0.01)
PlotDataHelper.set_plot_timeseries_format(axs,n=n,minticks=6, maxticks=12)
# scenario_names = pd.Series([scenario]*len(reserve_timeseries),name='Scenario')
# reserve_timeseries = reserve_timeseries.set_index([scenario_names],append=True)
# reserve_timeseries_chunk.append(reserve_timeseries)
# create list of gen technologies
l1 = reserve_timeseries.columns.tolist()
unique_reserve_types.extend(l1)
if not data_tables:
out = MissingZoneData()
outputs[region] = out
continue
# create handles list of unique reserve names
handles = np.unique(np.array(unique_reserve_types)).tolist()
# create color dictionary
color_dict = dict(zip(handles,self.color_list))
# create custom gen_tech legend
reserve_legend = []
for Type in handles:
legend_handles = [Line2D([0], [0], color=color_dict[Type], lw=2, label=Type)]
reserve_legend.extend(legend_handles)
axs[grid_size-1].legend(handles=reserve_legend, loc='lower left',
bbox_to_anchor=(1,0), facecolor='inherit',
frameon=True)
#Remove extra axes
if excess_axs != 0:
PlotDataHelper.remove_excess_axs(axs,excess_axs,grid_size)
# add facet labels
self.add_facet_labels(fig3)
fig3.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False,
left=False, right=False)
# plt.xlabel(timezone, color='black', rotation='horizontal',labelpad = 30)
plt.ylabel('Reserve Shortage [MW]', color='black',
rotation='vertical',labelpad = 40)
if mconfig.parser("plot_title_as_region"):
plt.title(region)
data_table_out = pd.concat(data_tables)
outputs[region] = {'fig': fig3, 'data_table': data_table_out}
return outputs
|
[
"logging.getLogger",
"marmot.plottingmodules.plotutils.plot_library.create_stackplot",
"matplotlib.pyplot.ylabel",
"numpy.array",
"marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count",
"datetime.timedelta",
"marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData",
"matplotlib.lines.Line2D",
"marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData",
"pandas.DataFrame",
"pandas.notna",
"matplotlib.pyplot.tick_params",
"marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.set_plot_timeseries_format",
"marmot.plottingmodules.plotutils.plot_library.create_line_plot",
"marmot.plottingmodules.plotutils.plot_library.create_grouped_bar_plot",
"matplotlib.patches.Patch",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots_adjust",
"marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.remove_excess_axs",
"marmot.plottingmodules.plotutils.plot_library.setup_plot",
"marmot.config.mconfig.parser",
"marmot.plottingmodules.plotutils.plot_library.create_stacked_bar_plot",
"pandas.concat"
] |
[((1826, 1870), 'logging.getLogger', 'logging.getLogger', (["('marmot_plot.' + __name__)"], {}), "('marmot_plot.' + __name__)\n", (1843, 1870), False, 'import logging\n'), ((1901, 1951), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""axes_options"""', '"""y_axes_decimalpt"""'], {}), "('axes_options', 'y_axes_decimalpt')\n", (1915, 1951), True, 'import marmot.config.mconfig as mconfig\n'), ((5253, 5271), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (5269, 5271), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((5580, 5622), 'marmot.plottingmodules.plotutils.plot_library.setup_plot', 'plotlib.setup_plot', (['xdimension', 'ydimension'], {}), '(xdimension, ydimension)\n', (5598, 5622), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((5634, 5678), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (5653, 5678), True, 'import matplotlib.pyplot as plt\n'), ((10420, 10508), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelcolor': '"""none"""', 'top': '(False)', 'bottom': '(False)', 'left': '(False)', 'right': '(False)'}), "(labelcolor='none', top=False, bottom=False, left=False,\n right=False)\n", (10435, 10508), True, 'import matplotlib.pyplot as plt\n'), ((10520, 10558), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (10534, 10558), True, 'import marmot.config.mconfig as mconfig\n'), ((10606, 10719), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Reserve Provision ({unitconversion[\'units\']})"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), '(f"Reserve Provision ({unitconversion[\'units\']})", color=\'black\',\n rotation=\'vertical\', labelpad=40)\n', (10616, 10719), True, 'import matplotlib.pyplot as plt\n'), ((10747, 10769), 'pandas.concat', 'pd.concat', (['data_tables'], {}), '(data_tables)\n', (10756, 10769), True, 'import pandas as pd\n'), ((12249, 12267), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (12265, 12267), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((12386, 12400), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (12398, 12400), True, 'import pandas as pd\n'), ((14810, 14933), 'marmot.plottingmodules.plotutils.plot_library.create_stacked_bar_plot', 'plotlib.create_stacked_bar_plot', (['Total_Reserves_Out', 'self.PLEXOS_color_dict'], {'custom_tick_labels': 'self.custom_xticklabels'}), '(Total_Reserves_Out, self.PLEXOS_color_dict,\n custom_tick_labels=self.custom_xticklabels)\n', (14841, 14933), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((16142, 16180), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (16156, 16180), True, 'import marmot.config.mconfig as mconfig\n'), ((19651, 19669), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (19667, 19669), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((19782, 19796), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (19794, 19796), True, 'import pandas as pd\n'), ((22546, 22602), 'marmot.plottingmodules.plotutils.plot_library.create_grouped_bar_plot', 'plotlib.create_grouped_bar_plot', (['reserve_out', 'color_dict'], {}), '(reserve_out, color_dict)\n', (22577, 22602), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((23238, 23276), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (23252, 23276), True, 'import marmot.config.mconfig as mconfig\n'), ((25756, 25774), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (25772, 25774), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((26094, 26136), 'marmot.plottingmodules.plotutils.plot_library.setup_plot', 'plotlib.setup_plot', (['xdimension', 'ydimension'], {}), '(xdimension, ydimension)\n', (26112, 26136), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((26148, 26192), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (26167, 26192), True, 'import matplotlib.pyplot as plt\n'), ((30139, 30227), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelcolor': '"""none"""', 'top': '(False)', 'bottom': '(False)', 'left': '(False)', 'right': '(False)'}), "(labelcolor='none', top=False, bottom=False, left=False,\n right=False)\n", (30154, 30227), True, 'import matplotlib.pyplot as plt\n'), ((30353, 30441), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Reserve Shortage [MW]"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), "('Reserve Shortage [MW]', color='black', rotation='vertical',\n labelpad=40)\n", (30363, 30441), True, 'import matplotlib.pyplot as plt\n'), ((30492, 30530), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (30506, 30530), True, 'import marmot.config.mconfig as mconfig\n'), ((30607, 30629), 'pandas.concat', 'pd.concat', (['data_tables'], {}), '(data_tables)\n', (30616, 30629), True, 'import pandas as pd\n'), ((8318, 8456), 'marmot.plottingmodules.plotutils.plot_library.create_stackplot', 'plotlib.create_stackplot', (['axs', 'reserve_provision_timeseries', 'self.PLEXOS_color_dict'], {'labels': 'reserve_provision_timeseries.columns', 'n': 'n'}), '(axs, reserve_provision_timeseries, self.\n PLEXOS_color_dict, labels=reserve_provision_timeseries.columns, n=n)\n', (8342, 8456), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((8467, 8542), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.set_plot_timeseries_format', 'PlotDataHelper.set_plot_timeseries_format', (['axs'], {'n': 'n', 'minticks': '(4)', 'maxticks': '(8)'}), '(axs, n=n, minticks=4, maxticks=8)\n', (8508, 8542), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((9301, 9318), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (9316, 9318), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((10227, 10287), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.remove_excess_axs', 'PlotDataHelper.remove_excess_axs', (['axs', 'excess_axs', 'grid_size'], {}), '(axs, excess_axs, grid_size)\n', (10259, 10287), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((10576, 10593), 'matplotlib.pyplot.title', 'plt.title', (['region'], {}), '(region)\n', (10585, 10593), True, 'import matplotlib.pyplot as plt\n'), ((13349, 13421), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count', 'PlotDataHelper.get_sub_hour_interval_count', (['reserve_provision_timeseries'], {}), '(reserve_provision_timeseries)\n', (13391, 13421), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((14135, 14152), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (14150, 14152), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((20359, 20421), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count', 'PlotDataHelper.get_sub_hour_interval_count', (['reserve_timeseries'], {}), '(reserve_timeseries)\n', (20401, 20421), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((21586, 21638), 'pandas.concat', 'pd.concat', (['reserve_total_chunk'], {'axis': '(1)', 'sort': '"""False"""'}), "(reserve_total_chunk, axis=1, sort='False')\n", (21595, 21638), True, 'import pandas as pd\n'), ((21763, 21777), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (21775, 21777), True, 'import pandas as pd\n'), ((21878, 21895), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (21893, 21895), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((27367, 27393), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (27375, 27393), True, 'import pandas as pd\n'), ((28506, 28582), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.set_plot_timeseries_format', 'PlotDataHelper.set_plot_timeseries_format', (['axs'], {'n': 'n', 'minticks': '(6)', 'maxticks': '(12)'}), '(axs, n=n, minticks=6, maxticks=12)\n', (28547, 28582), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((29070, 29087), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (29085, 29087), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((29946, 30006), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.remove_excess_axs', 'PlotDataHelper.remove_excess_axs', (['axs', 'excess_axs', 'grid_size'], {}), '(axs, excess_axs, grid_size)\n', (29978, 30006), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((30547, 30564), 'matplotlib.pyplot.title', 'plt.title', (['region'], {}), '(region)\n', (30556, 30564), True, 'import matplotlib.pyplot as plt\n'), ((9787, 9855), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': 'self.PLEXOS_color_dict[tech]', 'alpha': '(1.0)', 'label': 'tech'}), '(facecolor=self.PLEXOS_color_dict[tech], alpha=1.0, label=tech)\n', (9792, 9855), False, 'from matplotlib.patches import Patch\n'), ((15805, 15873), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': 'self.PLEXOS_color_dict[tech]', 'alpha': '(1.0)', 'label': 'tech'}), '(facecolor=self.PLEXOS_color_dict[tech], alpha=1.0, label=tech)\n', (15810, 15873), False, 'from matplotlib.patches import Patch\n'), ((28225, 28329), 'marmot.plottingmodules.plotutils.plot_library.create_line_plot', 'plotlib.create_line_plot', (['axs', 'reserve_timeseries', 'column'], {'color_dict': 'color_dict', 'label': 'column', 'n': 'n'}), '(axs, reserve_timeseries, column, color_dict=\n color_dict, label=column, n=n)\n', (28249, 28329), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((29542, 29600), 'matplotlib.lines.Line2D', 'Line2D', (['[0]', '[0]'], {'color': 'color_dict[Type]', 'lw': '(2)', 'label': 'Type'}), '([0], [0], color=color_dict[Type], lw=2, label=Type)\n', (29548, 29600), False, 'from matplotlib.lines import Line2D\n'), ((7141, 7165), 'datetime.timedelta', 'dt.timedelta', ([], {'days': 'start'}), '(days=start)\n', (7153, 7165), True, 'import datetime as dt\n'), ((7214, 7236), 'datetime.timedelta', 'dt.timedelta', ([], {'days': 'end'}), '(days=end)\n', (7226, 7236), True, 'import datetime as dt\n'), ((9497, 9524), 'numpy.array', 'np.array', (['unique_tech_names'], {}), '(unique_tech_names)\n', (9505, 9524), True, 'import numpy as np\n'), ((13736, 13806), 'pandas.concat', 'pd.concat', (['[Total_Reserves_Out, reserve_provision]'], {'axis': '(1)', 'sort': '(False)'}), '([Total_Reserves_Out, reserve_provision], axis=1, sort=False)\n', (13745, 13806), True, 'import pandas as pd\n'), ((15515, 15542), 'numpy.array', 'np.array', (['unique_tech_names'], {}), '(unique_tech_names)\n', (15523, 15542), True, 'import numpy as np\n'), ((29258, 29288), 'numpy.array', 'np.array', (['unique_reserve_types'], {}), '(unique_reserve_types)\n', (29266, 29288), True, 'import numpy as np\n'), ((8846, 8869), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(0.25)'}), '(days=0.25)\n', (8858, 8869), True, 'import datetime as dt\n')]
|
import numpy as np
import pandas as p
from datetime import datetime, timedelta
class PreprocessData():
def __init__(self, file_name):
self.file_name = file_name
#get only used feature parameters
def get_features(self, file_name):
data = p.read_csv(file_name, skiprows=7, sep=';', header=None)
data.drop(data.columns[len(data.columns)-1], axis=1, inplace=True)
data.columns = ['DateAndTime', 'T', 'Po', 'P', 'Pa', 'U', 'DD', 'Ff', 'ff10',
'ff3', 'N', 'WW', 'W1', 'W2', 'Tn', 'Tx', 'Cl', 'Nh', 'H', 'Cm', 'Ch',
'VV', 'Td', 'RRR', 'tR', 'E', 'Tg', 'E\'', 'sss']
data [['Date', 'Time']] = data.DateAndTime.str.split(expand = True)
data.Date = self.removeYear(data)
return data[['Date', 'Time', 'T', 'Po', 'P', 'Pa', 'DD', 'Ff', 'N', 'Tn', 'Tx', 'VV', 'Td']]
#preprocess data in case of trining model or generating data to run prediction
def preprocess(self, training_flag, predict_date):
data = self.get_features(self.file_name)
data_date = p.get_dummies(data.Date.to_frame())
data_time = p.get_dummies(data.Time.to_frame())
wind_direction = p.get_dummies(data.DD.to_frame())
cloud_rate = p.get_dummies(data.N.to_frame())
data_target = data[['T']];
name = "features.csv"
if training_flag:
temp_data = data.Date.to_frame().apply(lambda x: p.Series(self.training(x, data_target)), axis=1)
result = p.concat([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)
result.iloc[:len(result.index) - 365*8].to_csv("features.csv")
data_target.iloc[:len(data_target.index) - 365*8].to_csv("target.csv")
return "features.csv", "target.csv"
else:
temp_data = data.Date.to_frame().apply(lambda x: p.Series(self.predicting(x, data_target)), axis=1)
data_date = data_date.iloc[:8]
predict_date = datetime.strptime(predict_date, "%d.%m.%Y")
new_date_string = ("Date_%02d.%02d") % (predict_date.day, predict_date.month)
predict_date = predict_date - timedelta(days=1)
date_string = ("Date_%02d.%02d") % (predict_date.day, predict_date.month)
data_date[date_string] = 0
data_date[new_date_string] = 1
result = p.concat([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)
result.iloc[:8].to_csv("test_f.csv")
return "test_f.csv"
def removeYear(self, data):
data [['Day', 'Month', 'Year']] = data.Date.str.split(pat = '.', expand = True)
data.loc[:, 'Date'] = data[['Day', 'Month']].apply(lambda x: '.'.join(x), axis = 1)
return data.Date
def training(self, row, temperature_data):
after_drop = temperature_data.drop([row.name])
if row.name + 365*8 <= len(after_drop.index):
result = []
count = 0
for i in range(365):
count += 1
result = np.append(result, after_drop.iloc[row.name + i*8])
count = 0 if count == 8 else count
return result
return None
def predicting(self, row, temperature_data):
if row.name < 8:
result = []
count = 0
for i in range(365):
count += 1
result = np.append(result, temperature_data.iloc[row.name + i*8])
count = 0 if count == 8 else count
return result
return None
|
[
"pandas.read_csv",
"datetime.datetime.strptime",
"numpy.append",
"datetime.timedelta",
"pandas.concat"
] |
[((267, 322), 'pandas.read_csv', 'p.read_csv', (['file_name'], {'skiprows': '(7)', 'sep': '""";"""', 'header': 'None'}), "(file_name, skiprows=7, sep=';', header=None)\n", (277, 322), True, 'import pandas as p\n'), ((1485, 1564), 'pandas.concat', 'p.concat', (['[data_date, data_time, wind_direction, cloud_rate, temp_data]'], {'axis': '(1)'}), '([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)\n', (1493, 1564), True, 'import pandas as p\n'), ((1969, 2012), 'datetime.datetime.strptime', 'datetime.strptime', (['predict_date', '"""%d.%m.%Y"""'], {}), "(predict_date, '%d.%m.%Y')\n", (1986, 2012), False, 'from datetime import datetime, timedelta\n'), ((2353, 2432), 'pandas.concat', 'p.concat', (['[data_date, data_time, wind_direction, cloud_rate, temp_data]'], {'axis': '(1)'}), '([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)\n', (2361, 2432), True, 'import pandas as p\n'), ((2145, 2162), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (2154, 2162), False, 'from datetime import datetime, timedelta\n'), ((3041, 3093), 'numpy.append', 'np.append', (['result', 'after_drop.iloc[row.name + i * 8]'], {}), '(result, after_drop.iloc[row.name + i * 8])\n', (3050, 3093), True, 'import numpy as np\n'), ((3397, 3455), 'numpy.append', 'np.append', (['result', 'temperature_data.iloc[row.name + i * 8]'], {}), '(result, temperature_data.iloc[row.name + i * 8])\n', (3406, 3455), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Datasets
==================
Classes for dataset handling
Dataset - Base class
^^^^^^^^^^^^^^^^^^^^
This is the base class, and all the specialized datasets are inherited from it. One should never use base class itself.
Usage examples:
.. code-block:: python
:linenos:
# Create class
dataset = TUTAcousticScenes_2017_DevelopmentSet(data_path='data')
# Initialize dataset, this will make sure dataset is downloaded, packages are extracted, and needed meta files are created
dataset.initialize()
# Show meta data
dataset.meta.show()
# Get all evaluation setup folds
folds = dataset.folds()
# Get all evaluation setup folds
train_data_fold1 = dataset.train(fold=folds[0])
test_data_fold1 = dataset.test(fold=folds[0])
.. autosummary::
:toctree: generated/
Dataset
Dataset.initialize
Dataset.show_info
Dataset.audio_files
Dataset.audio_file_count
Dataset.meta
Dataset.meta_count
Dataset.error_meta
Dataset.error_meta_count
Dataset.fold_count
Dataset.scene_labels
Dataset.scene_label_count
Dataset.event_labels
Dataset.event_label_count
Dataset.audio_tags
Dataset.audio_tag_count
Dataset.download_packages
Dataset.extract
Dataset.train
Dataset.test
Dataset.eval
Dataset.folds
Dataset.file_meta
Dataset.file_error_meta
Dataset.file_error_meta
Dataset.relative_to_absolute_path
Dataset.absolute_to_relative
AcousticSceneDataset
^^^^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
AcousticSceneDataset
Specialized classes inherited AcousticSceneDataset:
.. autosummary::
:toctree: generated/
TUTAcousticScenes_2017_DevelopmentSet
TUTAcousticScenes_2016_DevelopmentSet
TUTAcousticScenes_2016_EvaluationSet
SoundEventDataset
^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
SoundEventDataset
SoundEventDataset.event_label_count
SoundEventDataset.event_labels
SoundEventDataset.train
SoundEventDataset.test
Specialized classes inherited SoundEventDataset:
.. autosummary::
:toctree: generated/
TUTRareSoundEvents_2017_DevelopmentSet
TUTSoundEvents_2016_DevelopmentSet
TUTSoundEvents_2016_EvaluationSet
AudioTaggingDataset
^^^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
AudioTaggingDataset
"""
from __future__ import print_function, absolute_import
import sys
import os
import logging
import socket
import zipfile
import tarfile
import collections
import csv
import numpy
import hashlib
import yaml
from tqdm import tqdm
from six import iteritems
from .utils import get_parameter_hash, get_class_inheritors
from .decorators import before_and_after_function_wrapper
from .files import TextFile, ParameterFile, ParameterListFile, AudioFile
from .containers import DottedDict
from .metadata import MetaDataContainer, MetaDataItem
def dataset_list(data_path, group=None):
"""List of datasets available
Parameters
----------
data_path : str
Base path for the datasets
group : str
Group label for the datasets, currently supported ['acoustic scene', 'sound event', 'audio tagging']
Returns
-------
str
Multi line string containing dataset table
"""
output = ''
output += ' Dataset list\n'
output += ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name='Class Name',
group='Group',
valid='Valid',
files='Files'
)
output += ' {class_name:<45s} + {group:20s} + {valid:5s} + {files:10s} +\n'.format(
class_name='-' * 45,
group='-' * 20,
valid='-'*5,
files='-'*10
)
def get_empty_row():
return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name='',
group='',
valid='',
files=''
)
def get_row(d):
file_count = 0
if d.meta_container.exists():
file_count = len(d.meta)
return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name=d.__class__.__name__,
group=d.dataset_group,
valid='Yes' if d.check_filelist() else 'No',
files=str(file_count) if file_count else ''
)
if not group or group == 'acoustic scene':
for dataset_class in get_class_inheritors(AcousticSceneDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
if not group or group == 'sound event':
for dataset_class in get_class_inheritors(SoundEventDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
if not group or group == 'audio tagging':
for dataset_class in get_class_inheritors(AudioTaggingDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
return output
def dataset_factory(*args, **kwargs):
"""Factory to get correct dataset class based on name
Parameters
----------
dataset_class_name : str
Class name
Default value "None"
Raises
------
NameError
Class does not exists
Returns
-------
Dataset class
"""
dataset_class_name = kwargs.get('dataset_class_name', None)
try:
return eval(dataset_class_name)(*args, **kwargs)
except NameError:
message = '{name}: No valid dataset given [{dataset_class_name}]'.format(
name='dataset_factory',
dataset_class_name=dataset_class_name
)
logging.getLogger('dataset_factory').exception(message)
raise NameError(message)
class Dataset(object):
"""Dataset base class
The specific dataset classes are inherited from this class, and only needed methods are reimplemented.
"""
def __init__(self, *args, **kwargs):
"""Constructor
Parameters
----------
name : str
storage_name : str
data_path : str
Basepath where the dataset is stored.
(Default value='data')
logger : logger
Instance of logging
Default value "none"
show_progress_in_console : bool
Show progress in console.
Default value "True"
log_system_progress : bool
Show progress in log.
Default value "False"
use_ascii_progress_bar : bool
Show progress bar using ASCII characters. Use this if your console does not support UTF-8 characters.
Default value "False"
"""
self.logger = kwargs.get('logger') or logging.getLogger(__name__)
self.disable_progress_bar = not kwargs.get('show_progress_in_console', True)
self.log_system_progress = kwargs.get('log_system_progress', False)
self.use_ascii_progress_bar = kwargs.get('use_ascii_progress_bar', True)
# Dataset name
self.name = kwargs.get('name', 'dataset')
# Folder name for dataset
self.storage_name = kwargs.get('storage_name', 'dataset')
# Path to the dataset
self.local_path = os.path.join(kwargs.get('data_path', 'data'), self.storage_name)
# Evaluation setup folder
self.evaluation_setup_folder = kwargs.get('evaluation_setup_folder', 'evaluation_setup')
# Path to the folder containing evaluation setup files
self.evaluation_setup_path = os.path.join(self.local_path, self.evaluation_setup_folder)
# Meta data file, csv-format
self.meta_filename = kwargs.get('meta_filename', 'meta.txt')
# Path to meta data file
self.meta_container = MetaDataContainer(filename=os.path.join(self.local_path, self.meta_filename))
if self.meta_container.exists():
self.meta_container.load()
# Error meta data file, csv-format
self.error_meta_filename = kwargs.get('error_meta_filename', 'error.txt')
# Path to error meta data file
self.error_meta_file = os.path.join(self.local_path, self.error_meta_filename)
# Hash file to detect removed or added files
self.filelisthash_filename = kwargs.get('filelisthash_filename', 'filelist.python.hash')
# Dirs to be excluded when calculating filelist hash
self.filelisthash_exclude_dirs = kwargs.get('filelisthash_exclude_dirs', [])
# Number of evaluation folds
self.crossvalidation_folds = 1
# List containing dataset package items
# Define this in the inherited class.
# Format:
# {
# 'remote_package': download_url,
# 'local_package': os.path.join(self.local_path, 'name_of_downloaded_package'),
# 'local_audio_path': os.path.join(self.local_path, 'name_of_folder_containing_audio_files'),
# }
self.package_list = []
# List of audio files
self.files = None
# List of audio error meta data dict
self.error_meta_data = None
# Training meta data for folds
self.crossvalidation_data_train = {}
# Testing meta data for folds
self.crossvalidation_data_test = {}
# Evaluation meta data for folds
self.crossvalidation_data_eval = {}
# Recognized audio extensions
self.audio_extensions = {'wav', 'flac'}
self.default_audio_extension = 'wav'
# Reference data presence flag, by default dataset should have reference data present.
# However, some evaluation dataset might not have
self.reference_data_present = True
# Info fields for dataset
self.authors = ''
self.name_remote = ''
self.url = ''
self.audio_source = ''
self.audio_type = ''
self.recording_device_model = ''
self.microphone_model = ''
def initialize(self):
# Create the dataset path if does not exist
if not os.path.isdir(self.local_path):
os.makedirs(self.local_path)
if not self.check_filelist():
self.download_packages()
self.extract()
self._save_filelist_hash()
return self
def show_info(self):
DottedDict(self.dataset_meta).show()
@property
def audio_files(self):
"""Get all audio files in the dataset
Parameters
----------
Returns
-------
filelist : list
File list with absolute paths
"""
if self.files is None:
self.files = []
for item in self.package_list:
path = item['local_audio_path']
if path:
l = os.listdir(path)
for f in l:
file_name, file_extension = os.path.splitext(f)
if file_extension[1:] in self.audio_extensions:
if os.path.abspath(os.path.join(path, f)) not in self.files:
self.files.append(os.path.abspath(os.path.join(path, f)))
self.files.sort()
return self.files
@property
def audio_file_count(self):
"""Get number of audio files in dataset
Parameters
----------
Returns
-------
filecount : int
Number of audio files
"""
return len(self.audio_files)
@property
def meta(self):
"""Get meta data for dataset. If not already read from disk, data is read and returned.
Parameters
----------
Returns
-------
meta_container : list
List containing meta data as dict.
Raises
-------
IOError
meta file not found.
"""
if self.meta_container.empty():
if self.meta_container.exists():
self.meta_container.load()
else:
message = '{name}: Meta file not found [{filename}]'.format(
name=self.__class__.__name__,
filename=self.meta_container.filename
)
self.logger.exception(message)
raise IOError(message)
return self.meta_container
@property
def meta_count(self):
"""Number of meta data items.
Parameters
----------
Returns
-------
meta_item_count : int
Meta data item count
"""
return len(self.meta_container)
@property
def error_meta(self):
"""Get audio error meta data for dataset. If not already read from disk, data is read and returned.
Parameters
----------
Raises
-------
IOError:
audio error meta file not found.
Returns
-------
error_meta_data : list
List containing audio error meta data as dict.
"""
if self.error_meta_data is None:
self.error_meta_data = MetaDataContainer(filename=self.error_meta_file)
if self.error_meta_data.exists():
self.error_meta_data.load()
else:
message = '{name}: Error meta file not found [{filename}]'.format(name=self.__class__.__name__,
filename=self.error_meta_file)
self.logger.exception(message)
raise IOError(message)
return self.error_meta_data
def error_meta_count(self):
"""Number of error meta data items.
Parameters
----------
Returns
-------
meta_item_count : int
Meta data item count
"""
return len(self.error_meta)
@property
def fold_count(self):
"""Number of fold in the evaluation setup.
Parameters
----------
Returns
-------
fold_count : int
Number of folds
"""
return self.crossvalidation_folds
@property
def scene_labels(self):
"""List of unique scene labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of scene labels in alphabetical order.
"""
return self.meta_container.unique_scene_labels
@property
def scene_label_count(self):
"""Number of unique scene labels in the meta data.
Parameters
----------
Returns
-------
scene_label_count : int
Number of unique scene labels.
"""
return self.meta_container.scene_label_count
def event_labels(self):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
return self.meta_container.unique_event_labels
@property
def event_label_count(self):
"""Number of unique event labels in the meta data.
Parameters
----------
Returns
-------
event_label_count : int
Number of unique event labels
"""
return self.meta_container.event_label_count
@property
def audio_tags(self):
"""List of unique audio tags in the meta data.
Parameters
----------
Returns
-------
labels : list
List of audio tags in alphabetical order.
"""
tags = []
for item in self.meta:
if 'tags' in item:
for tag in item['tags']:
if tag and tag not in tags:
tags.append(tag)
tags.sort()
return tags
@property
def audio_tag_count(self):
"""Number of unique audio tags in the meta data.
Parameters
----------
Returns
-------
audio_tag_count : int
Number of unique audio tags
"""
return len(self.audio_tags)
def __getitem__(self, i):
"""Getting meta data item
Parameters
----------
i : int
item id
Returns
-------
meta_data : dict
Meta data item
"""
if i < len(self.meta_container):
return self.meta_container[i]
else:
return None
def __iter__(self):
"""Iterator for meta data items
Parameters
----------
Nothing
Returns
-------
Nothing
"""
i = 0
meta = self[i]
# yield window while it's valid
while meta is not None:
yield meta
# get next item
i += 1
meta = self[i]
def download_packages(self):
"""Download dataset packages over the internet to the local path
Parameters
----------
Returns
-------
Nothing
Raises
-------
IOError
Download failed.
"""
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
# Set socket timeout
socket.setdefaulttimeout(120)
item_progress = tqdm(self.package_list,
desc="{0: <25s}".format('Download package list'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item in item_progress:
try:
if item['remote_package'] and not os.path.isfile(item['local_package']):
def progress_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks just transferred [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
remote_file = item['remote_package']
tmp_file = os.path.join(self.local_path, 'tmp_file')
with tqdm(desc="{0: >25s}".format(os.path.splitext(remote_file.split('/')[-1])[0]),
file=sys.stdout,
unit='B',
unit_scale=True,
miniters=1,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar) as t:
local_filename, headers = urlretrieve(
remote_file,
filename=tmp_file,
reporthook=progress_hook(t),
data=None
)
os.rename(tmp_file, item['local_package'])
except Exception as e:
message = '{name}: Download failed [{filename}] [{errno}: {strerror}]'.format(
name=self.__class__.__name__,
filename=item['remote_package'],
errno=e.errno if hasattr(e, 'errno') else '',
strerror=e.strerror if hasattr(e, 'strerror') else '',
)
self.logger.exception(message)
raise
@before_and_after_function_wrapper
def extract(self):
"""Extract the dataset packages
Parameters
----------
Returns
-------
Nothing
"""
item_progress = tqdm(self.package_list,
desc="{0: <25s}".format('Extract packages'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {package:<30s}'.format(
title='Extract packages ',
item_id=item_id,
total=len(item_progress),
package=item['local_package'])
)
if item['local_package'] and os.path.isfile(item['local_package']):
if item['local_package'].endswith('.zip'):
with zipfile.ZipFile(item['local_package'], "r") as z:
# Trick to omit first level folder
parts = []
for name in z.namelist():
if not name.endswith('/'):
parts.append(name.split('/')[:-1])
prefix = os.path.commonprefix(parts) or ''
if prefix:
if len(prefix) > 1:
prefix_ = list()
prefix_.append(prefix[0])
prefix = prefix_
prefix = '/'.join(prefix) + '/'
offset = len(prefix)
# Start extraction
members = z.infolist()
file_count = 1
progress = tqdm(members,
desc="{0: <25s}".format('Extract'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for i, member in enumerate(progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Extract ',
item_id=i,
total=len(progress),
file=member.filename)
)
if len(member.filename) > offset:
member.filename = member.filename[offset:]
progress.set_description("{0: >35s}".format(member.filename.split('/')[-1]))
progress.update()
if not os.path.isfile(os.path.join(self.local_path, member.filename)):
try:
z.extract(member, self.local_path)
except KeyboardInterrupt:
# Delete latest file, since most likely it was not extracted fully
os.remove(os.path.join(self.local_path, member.filename))
# Quit
sys.exit()
file_count += 1
elif item['local_package'].endswith('.tar.gz'):
tar = tarfile.open(item['local_package'], "r:gz")
progress = tqdm(tar,
desc="{0: <25s}".format('Extract'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for i, tar_info in enumerate(progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Extract ',
item_id=i,
total=len(progress),
file=tar_info.name)
)
if not os.path.isfile(os.path.join(self.local_path, tar_info.name)):
tar.extract(tar_info, self.local_path)
tar.members = []
tar.close()
def _get_filelist(self, exclude_dirs=None):
"""List of files under local_path
Parameters
----------
exclude_dirs : list of str
List of directories to be excluded
Default value "[]"
Returns
-------
filelist: list
File list
"""
if exclude_dirs is None:
exclude_dirs = []
filelist = []
for path, subdirs, files in os.walk(self.local_path):
for name in files:
if os.path.splitext(name)[1] != os.path.splitext(self.filelisthash_filename)[1] and os.path.split(path)[1] not in exclude_dirs:
filelist.append(os.path.join(path, name))
return sorted(filelist)
def check_filelist(self):
"""Generates hash from file list and check does it matches with one saved in filelist.hash.
If some files have been deleted or added, checking will result False.
Parameters
----------
Returns
-------
result: bool
Result
"""
if os.path.isfile(os.path.join(self.local_path, self.filelisthash_filename)):
old_hash_value = TextFile(filename=os.path.join(self.local_path, self.filelisthash_filename)).load()[0]
file_list = self._get_filelist(exclude_dirs=self.filelisthash_exclude_dirs)
new_hash_value = get_parameter_hash(file_list)
if old_hash_value != new_hash_value:
return False
else:
return True
else:
return False
def _save_filelist_hash(self):
"""Generates file list hash, and saves it as filelist.hash under local_path.
Parameters
----------
Nothing
Returns
-------
Nothing
"""
filelist = self._get_filelist()
hash_value = get_parameter_hash(filelist)
TextFile([hash_value], filename=os.path.join(self.local_path, self.filelisthash_filename)).save()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='train', fold=fold)).load()
else:
self.crossvalidation_data_train[0] = self.meta_container
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_train[fold]
def test(self, fold=0):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = []
if fold > 0:
self.crossvalidation_data_test[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='test', fold=fold)).load()
for item in self.crossvalidation_data_test[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
else:
self.crossvalidation_data_test[fold] = self.meta_container
for item in self.crossvalidation_data_test[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_test[fold]
def eval(self, fold=0):
"""List of evaluation items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_eval:
self.crossvalidation_data_eval[fold] = []
if fold > 0:
self.crossvalidation_data_eval[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='evaluate', fold=fold)).load()
else:
self.crossvalidation_data_eval[fold] = self.meta_container
for item in self.crossvalidation_data_eval[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_eval[fold]
def folds(self, mode='folds'):
"""List of fold ids
Parameters
----------
mode : str {'folds','full'}
Fold setup type, possible values are 'folds' and 'full'. In 'full' mode fold number is set 0 and all data is used for training.
(Default value=folds)
Returns
-------
list : list of integers
Fold ids
"""
if mode == 'folds':
return range(1, self.crossvalidation_folds + 1)
elif mode == 'full':
return [0]
def file_meta(self, filename):
"""Meta data for given file
Parameters
----------
filename : str
File name
Returns
-------
list : list of dicts
List containing all meta data related to given file.
"""
return self.meta_container.filter(filename=self.absolute_to_relative(filename))
def file_error_meta(self, filename):
"""Error meta data for given file
Parameters
----------
filename : str
File name
Returns
-------
list : list of dicts
List containing all error meta data related to given file.
"""
return self.error_meta.filter(file=self.absolute_to_relative(filename))
def relative_to_absolute_path(self, path):
"""Converts relative path into absolute path.
Parameters
----------
path : str
Relative path
Returns
-------
path : str
Absolute path
"""
return os.path.abspath(os.path.expanduser(os.path.join(self.local_path, path)))
def absolute_to_relative(self, path):
"""Converts absolute path into relative path.
Parameters
----------
path : str
Absolute path
Returns
-------
path : str
Relative path
"""
if path.startswith(os.path.abspath(self.local_path)):
return os.path.relpath(path, self.local_path)
else:
return path
def _get_evaluation_setup_filename(self, setup_part='train', fold=None, scene_label=None, file_extension='txt'):
parts = []
if scene_label:
parts.append(scene_label)
if fold:
parts.append('fold' + str(fold))
if setup_part == 'train':
parts.append('train')
elif setup_part == 'test':
parts.append('test')
elif setup_part == 'evaluate':
parts.append('evaluate')
return os.path.join(self.evaluation_setup_path, '_'.join(parts) + '.' + file_extension)
class AcousticSceneDataset(Dataset):
def __init__(self, *args, **kwargs):
super(AcousticSceneDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
class SoundEventDataset(Dataset):
def __init__(self, *args, **kwargs):
super(SoundEventDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
def event_label_count(self, scene_label=None):
"""Number of unique scene labels in the meta data.
Parameters
----------
scene_label : str
Scene label
Default value "None"
Returns
-------
scene_label_count : int
Number of unique scene labels.
"""
return len(self.event_labels(scene_label=scene_label))
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
scene_label : str
Scene label
Default value "None"
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
if scene_label is not None:
labels = self.meta_container.filter(scene_label=scene_label).unique_event_labels
else:
labels = self.meta_container.unique_event_labels
labels.sort()
return labels
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='train', fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
def test(self, fold=0, scene_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
else:
self.crossvalidation_data_test[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_test[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_test[fold][scene_label_]
return data
class SyntheticSoundEventDataset(SoundEventDataset):
def __init__(self, *args, **kwargs):
super(SyntheticSoundEventDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
def initialize(self):
# Create the dataset path if does not exist
if not os.path.isdir(self.local_path):
os.makedirs(self.local_path)
if not self.check_filelist():
self.download_packages()
self.extract()
self._save_filelist_hash()
self.synthesize()
return self
@before_and_after_function_wrapper
def synthesize(self):
pass
class AudioTaggingDataset(Dataset):
def __init__(self, *args, **kwargs):
super(AudioTaggingDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
# =====================================================
# DCASE 2017
# =====================================================
class TUTAcousticScenes_2017_DevelopmentSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2017 development dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2017-development')
super(TUTAcousticScenes_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2017, development dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.error.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.error.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.9.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.9.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.10.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.10.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = collections.OrderedDict()
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
fold_data += MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_evaluate.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
item['identifier'] = location_id
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
location_id = raw_filename.split('_')[0]
item['identifier'] = location_id
else:
self.crossvalidation_data_train[0] = self.meta_container
return self.crossvalidation_data_train[fold]
class TUTAcousticScenes_2017_EvaluationSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2017-evaluation')
super(TUTAcousticScenes_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = False
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2017, development dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = collections.OrderedDict()
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_test.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0):
return []
def test(self, fold=0):
return []
class TUTRareSoundEvents_2017_DevelopmentSet(SyntheticSoundEventDataset):
"""TUT Acoustic scenes 2017 development dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-rare-sound-events-2017-development')
kwargs['filelisthash_exclude_dirs'] = kwargs.get('filelisthash_exclude_dirs', ['generated_data'])
self.synth_parameters = DottedDict({
'train': {
'seed': 42,
'mixture': {
'fs': 44100,
'bitdepth': 24,
'length_seconds': 30.0,
'anticlipping_factor': 0.2,
},
'event_presence_prob': 0.5,
'mixtures_per_class': 500,
'ebr_list': [-6, 0, 6],
},
'test': {
'seed': 42,
'mixture': {
'fs': 44100,
'bitdepth': 24,
'length_seconds': 30.0,
'anticlipping_factor': 0.2,
},
'event_presence_prob': 0.5,
'mixtures_per_class': 500,
'ebr_list': [-6, 0, 6],
}
})
# Override synth parameters
if kwargs.get('synth_parameters'):
self.synth_parameters.merge(kwargs.get('synth_parameters'))
# Meta filename depends on synth parameters
meta_filename = 'meta_'+self.synth_parameters.get_hash_for_path()+'.txt'
kwargs['meta_filename'] = kwargs.get('meta_filename', os.path.join('generated_data', meta_filename))
# Initialize baseclass
super(TUTRareSoundEvents_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Rare Sound Events 2017, development dataset',
'url': None,
'audio_source': 'Synthetic',
'audio_type': 'Natural',
'recording_device_model': 'Unknown',
'microphone_model': 'Unknown',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.code.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.code.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_events.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_events.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
@property
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
labels = ['babycry', 'glassbreak', 'gunshot']
labels.sort()
return labels
def train(self, fold=0, event_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][event_label_] = MetaDataContainer()
if fold == 1:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
self.crossvalidation_data_train[fold][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
elif fold == 0:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
# Load train files
self.crossvalidation_data_train[0][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtest_' + event_label_ + '.csv'
)
# Load test files
self.crossvalidation_data_train[0][event_label_] += MetaDataContainer(
filename=event_list_filename).load()
for item in self.crossvalidation_data_train[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_train[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_train[fold][event_label_]
return data
def test(self, fold=0, event_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer()
if fold == 1:
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer(
filename=event_list_filename
).load()
elif fold == 0:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
# Load train files
self.crossvalidation_data_test[0][event_label_] = MetaDataContainer(
filename=event_list_filename
).load()
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtest_' + event_label_ + '.csv'
)
# Load test files
self.crossvalidation_data_test[0][event_label_] += MetaDataContainer(
filename=event_list_filename
).load()
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_test[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_test[fold][event_label_]
return data
@before_and_after_function_wrapper
def synthesize(self):
subset_map = {'train': 'devtrain',
'test': 'devtest'}
background_audio_path = os.path.join(self.local_path, 'data', 'source_data', 'bgs')
event_audio_path = os.path.join(self.local_path, 'data', 'source_data', 'events')
cv_setup_path = os.path.join(self.local_path, 'data', 'source_data', 'cv_setup')
set_progress = tqdm(['train', 'test'],
desc="{0: <25s}".format('Set'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for subset_label in set_progress:
if self.log_system_progress:
self.logger.info(' {title:<15s} [{subset_label:<30s}]'.format(
title='Set ',
subset_label=subset_label)
)
subset_name_on_disk = subset_map[subset_label]
background_meta = ParameterListFile().load(filename=os.path.join(cv_setup_path, 'bgs_' + subset_name_on_disk + '.yaml'))
event_meta = ParameterFile().load(
filename=os.path.join(cv_setup_path, 'events_' + subset_name_on_disk + '.yaml')
)
params = self.synth_parameters.get_path(subset_label)
params_hash = self.synth_parameters.get_hash_for_path(subset_label)
r = numpy.random.RandomState(params.get('seed', 42))
mixture_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash
)
mixture_audio_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'audio'
)
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'meta'
)
# Make sure folder exists
if not os.path.isdir(mixture_path):
os.makedirs(mixture_path)
if not os.path.isdir(mixture_audio_path):
os.makedirs(mixture_audio_path)
if not os.path.isdir(mixture_meta_path):
os.makedirs(mixture_meta_path)
class_progress = tqdm(self.event_labels,
desc="{0: <25s}".format('Class'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for class_label in class_progress:
if self.log_system_progress:
self.logger.info(' {title:<15s} [{class_label:<30s}]'.format(
title='Class ',
class_label=class_label)
)
mixture_recipes_filename = os.path.join(
mixture_meta_path,
'mixture_recipes_' + subset_name_on_disk + '_' + class_label + '.yaml'
)
# Generate recipes if not exists
if not os.path.isfile(mixture_recipes_filename):
self._generate_mixture_recipes(
params=params,
class_label=class_label,
subset=subset_name_on_disk,
mixture_recipes_filename=mixture_recipes_filename,
background_meta=background_meta,
event_meta=event_meta[class_label],
background_audio_path=background_audio_path,
event_audio_path=event_audio_path,
r=r
)
mixture_meta = ParameterListFile().load(filename=mixture_recipes_filename)
# Generate mixture signals
item_progress = tqdm(mixture_meta,
desc="{0: <25s}".format('Generate mixture'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Generate mixture ',
item_id=item_id,
total=len(item_progress),
file=item['mixture_audio_filename'])
)
mixture_file = os.path.join(mixture_audio_path, item['mixture_audio_filename'])
if not os.path.isfile(mixture_file):
mixture = self._synthesize_mixture(
mixture_recipe=item,
params=params,
background_audio_path=background_audio_path,
event_audio_path=event_audio_path
)
audio_container = AudioFile(
data=mixture,
fs=params['mixture']['fs']
)
audio_container.save(
filename=mixture_file,
bitdepth=params['mixture']['bitdepth']
)
# Generate event lists
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_' + subset_name_on_disk + '_' + class_label + '.csv'
)
event_list = MetaDataContainer(filename=event_list_filename)
if not event_list.exists():
item_progress = tqdm(mixture_meta,
desc="{0: <25s}".format('Event list'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Event list ',
item_id=item_id,
total=len(item_progress),
file=item['mixture_audio_filename'])
)
event_list_item = {
'file': os.path.join(
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'audio',
item['mixture_audio_filename']
),
}
if item['event_present']:
event_list_item['event_label'] = item['event_class']
event_list_item['event_onset'] = float(item['event_start_in_mixture_seconds'])
event_list_item['event_offset'] = float(item['event_start_in_mixture_seconds'] + item['event_length_seconds'])
event_list.append(MetaDataItem(event_list_item))
event_list.save()
mixture_parameters = os.path.join(mixture_path, 'parameters.yaml')
# Save parameters
if not os.path.isfile(mixture_parameters):
ParameterFile(params).save(filename=mixture_parameters)
if not self.meta_container.exists():
# Collect meta data
meta_data = MetaDataContainer()
for class_label in self.event_labels:
for subset_label, subset_name_on_disk in iteritems(subset_map):
params_hash = self.synth_parameters.get_hash_for_path(subset_label)
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_' + subset_name_on_disk + '_' + class_label + '.csv'
)
meta_data += MetaDataContainer(filename=event_list_filename).load()
self.meta_container.update(meta_data)
self.meta_container.save()
def _generate_mixture_recipes(self, params, subset, class_label, mixture_recipes_filename, background_meta,
event_meta, background_audio_path, event_audio_path, r):
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
def get_event_amplitude_scaling_factor(signal, noise, target_snr_db):
"""Get amplitude scaling factor
Different lengths for signal and noise allowed: longer noise assumed to be stationary enough,
and rmse is calculated over the whole signal
Parameters
----------
signal : numpy.ndarray
noise : numpy.ndarray
target_snr_db : float
Returns
-------
float > 0.0
"""
def rmse(y):
"""RMSE"""
return numpy.sqrt(numpy.mean(numpy.abs(y) ** 2, axis=0, keepdims=False))
original_sn_rmse_ratio = rmse(signal) / rmse(noise)
target_sn_rmse_ratio = 10 ** (target_snr_db / float(20))
signal_scaling_factor = target_sn_rmse_ratio / original_sn_rmse_ratio
return signal_scaling_factor
# Internal variables
fs = float(params.get('mixture').get('fs', 44100))
current_class_events = []
# Inject fields to meta data
for event in event_meta:
event['classname'] = class_label
event['audio_filepath'] = os.path.join(class_label, event['audio_filename'])
event['length_seconds'] = numpy.diff(event['segment'])[0]
current_class_events.append(event)
# Randomize order of event and background
events = r.choice(current_class_events,
int(round(params.get('mixtures_per_class') * params.get('event_presence_prob'))))
bgs = r.choice(background_meta, params.get('mixtures_per_class'))
# Event presence flags
event_presence_flags = (numpy.hstack((numpy.ones(len(events)), numpy.zeros(len(bgs) - len(events))))).astype(bool)
event_presence_flags = r.permutation(event_presence_flags)
# Event instance IDs, by default event id set to nan: no event. fill it later with actual event ids when needed
event_instance_ids = numpy.nan * numpy.ones(len(bgs)).astype(int)
event_instance_ids[event_presence_flags] = numpy.arange(len(events))
# Randomize event position inside background
for event in events:
event['offset_seconds'] = (params.get('mixture').get('length_seconds') - event['length_seconds']) * r.rand()
# Get offsets for all mixtures, If no event present, use nans
event_offsets_seconds = numpy.nan * numpy.ones(len(bgs))
event_offsets_seconds[event_presence_flags] = [event['offset_seconds'] for event in events]
# Double-check that we didn't shuffle things wrongly: check that the offset never exceeds bg_len-event_len
checker = [offset + events[int(event_instance_id)]['length_seconds'] for offset, event_instance_id in
zip(event_offsets_seconds[event_presence_flags], event_instance_ids[event_presence_flags])]
assert numpy.max(numpy.array(checker)) < params.get('mixture').get('length_seconds')
# Target EBRs
target_ebrs = -numpy.inf * numpy.ones(len(bgs))
target_ebrs[event_presence_flags] = r.choice(params.get('ebr_list'), size=numpy.sum(event_presence_flags))
# For recipes, we got to provide amplitude scaling factors instead of SNRs: the latter are more ambiguous
# so, go through files, measure levels, calculate scaling factors
mixture_recipes = ParameterListFile()
for mixture_id, (bg, event_presence_flag, event_start_in_mixture_seconds, ebr, event_instance_id) in tqdm(
enumerate(zip(bgs, event_presence_flags, event_offsets_seconds, target_ebrs, event_instance_ids)),
desc="{0: <25s}".format('Generate recipe'),
file=sys.stdout,
leave=False,
total=len(bgs),
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar):
# Read the bgs and events, measure their energies, find amplitude scaling factors
mixture_recipe = {
'bg_path': bg['filepath'],
'bg_classname': bg['classname'],
'event_present': bool(event_presence_flag),
'ebr': float(ebr)
}
if event_presence_flag:
# We have an event assigned
assert not numpy.isnan(event_instance_id)
# Load background and event audio in
bg_audio, fs_bg = AudioFile(fs=params.get('mixture').get('fs')).load(
filename=os.path.join(background_audio_path, bg['filepath'])
)
event_audio, fs_event = AudioFile(fs=params.get('mixture').get('fs')).load(
filename=os.path.join(event_audio_path, events[int(event_instance_id)]['audio_filepath'])
)
assert fs_bg == fs_event, 'Fs mismatch! Expected resampling taken place already'
# Segment onset and offset in samples
segment_start_samples = int(events[int(event_instance_id)]['segment'][0] * fs)
segment_end_samples = int(events[int(event_instance_id)]['segment'][1] * fs)
# Cut event audio
event_audio = event_audio[segment_start_samples:segment_end_samples]
# Let's calculate the levels of bgs also at the location of the event only
eventful_part_of_bg = bg_audio[int(event_start_in_mixture_seconds * fs):int(event_start_in_mixture_seconds * fs + len(event_audio))]
if eventful_part_of_bg.shape[0] == 0:
message = '{name}: Background segment having an event has zero length.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise ValueError(message)
scaling_factor = get_event_amplitude_scaling_factor(event_audio, eventful_part_of_bg, target_snr_db=ebr)
# Store information
mixture_recipe['event_path'] = events[int(event_instance_id)]['audio_filepath']
mixture_recipe['event_class'] = events[int(event_instance_id)]['classname']
mixture_recipe['event_start_in_mixture_seconds'] = float(event_start_in_mixture_seconds)
mixture_recipe['event_length_seconds'] = float(events[int(event_instance_id)]['length_seconds'])
mixture_recipe['scaling_factor'] = float(scaling_factor)
mixture_recipe['segment_start_seconds'] = events[int(event_instance_id)]['segment'][0]
mixture_recipe['segment_end_seconds'] = events[int(event_instance_id)]['segment'][1]
# Generate mixture filename
mixing_param_hash = hashlib.md5(yaml.dump(mixture_recipe)).hexdigest()
mixture_recipe['mixture_audio_filename'] = 'mixture' + '_' + subset + '_' + class_label + '_' + '%03d' % mixture_id + '_' + mixing_param_hash + '.' + self.default_audio_extension
# Generate mixture annotation
if event_presence_flag:
mixture_recipe['annotation_string'] = \
mixture_recipe['mixture_audio_filename'] + '\t' + \
"{0:.14f}".format(mixture_recipe['event_start_in_mixture_seconds']) + '\t' + \
"{0:.14f}".format(mixture_recipe['event_start_in_mixture_seconds'] + mixture_recipe['event_length_seconds']) + '\t' + \
mixture_recipe['event_class']
else:
mixture_recipe['annotation_string'] = mixture_recipe['mixture_audio_filename'] + '\t' + 'None' + '\t0\t30'
# Store mixture recipe
mixture_recipes.append(mixture_recipe)
# Save mixture recipe
mixture_recipes.save(filename=mixture_recipes_filename)
def _synthesize_mixture(self, mixture_recipe, params, background_audio_path, event_audio_path):
background_audiofile = os.path.join(background_audio_path, mixture_recipe['bg_path'])
# Load background audio
bg_audio_data, fs_bg = AudioFile().load(filename=background_audiofile,
fs=params['mixture']['fs'],
mono=True)
if mixture_recipe['event_present']:
event_audiofile = os.path.join(event_audio_path, mixture_recipe['event_path'])
# Load event audio
event_audio_data, fs_event = AudioFile().load(filename=event_audiofile,
fs=params['mixture']['fs'],
mono=True)
if fs_bg != fs_event:
message = '{name}: Sampling frequency mismatch. Material should be resampled.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise ValueError(message)
# Slice event audio
segment_start_samples = int(mixture_recipe['segment_start_seconds'] * params['mixture']['fs'])
segment_end_samples = int(mixture_recipe['segment_end_seconds'] * params['mixture']['fs'])
event_audio_data = event_audio_data[segment_start_samples:segment_end_samples]
event_start_in_mixture_samples = int(mixture_recipe['event_start_in_mixture_seconds'] * params['mixture']['fs'])
scaling_factor = mixture_recipe['scaling_factor']
# Mix event into background audio
mixture = self._mix(bg_audio_data=bg_audio_data,
event_audio_data=event_audio_data,
event_start_in_mixture_samples=event_start_in_mixture_samples,
scaling_factor=scaling_factor,
magic_anticlipping_factor=params['mixture']['anticlipping_factor'])
else:
mixture = params['mixture']['anticlipping_factor'] * bg_audio_data
return mixture
def _mix(self, bg_audio_data, event_audio_data, event_start_in_mixture_samples, scaling_factor, magic_anticlipping_factor):
"""Mix numpy arrays of background and event audio (mono, non-matching lengths supported, sampling frequency
better be the same, no operation in terms of seconds is performed though)
Parameters
----------
bg_audio_data : numpy.array
event_audio_data : numpy.array
event_start_in_mixture_samples : float
scaling_factor : float
magic_anticlipping_factor : float
Returns
-------
numpy.array
"""
# Store current event audio max value
event_audio_original_max = numpy.max(numpy.abs(event_audio_data))
# Adjust SNRs
event_audio_data *= scaling_factor
# Check that the offset is not too long
longest_possible_offset = len(bg_audio_data) - len(event_audio_data)
if event_start_in_mixture_samples > longest_possible_offset:
message = '{name}: Wrongly generated event offset: event tries to go outside the boundaries of the bg.'.format(name=self.__class__.__name__)
self.logger.exception(message)
raise AssertionError(message)
# Measure how much to pad from the right
tail_length = len(bg_audio_data) - len(event_audio_data) - event_start_in_mixture_samples
# Pad zeros at the beginning of event signal
padded_event = numpy.pad(event_audio_data,
pad_width=((event_start_in_mixture_samples, tail_length)),
mode='constant',
constant_values=0)
if not len(padded_event) == len(bg_audio_data):
message = '{name}: Mixing yielded a signal of different length than bg! Should not happen.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise AssertionError(message)
mixture = magic_anticlipping_factor * (padded_event + bg_audio_data)
# Also nice to make sure that we did not introduce clipping
if numpy.max(numpy.abs(mixture)) >= 1:
normalisation_factor = 1 / float(numpy.max(numpy.abs(mixture)))
print('Attention! Had to normalise the mixture by [{factor}]'.format(factor=normalisation_factor))
print('I.e. bg max: {bg_max:2.4f}, event max: {event_max:2.4f}, sum max: {sum_max:2.4f}'.format(
bg_max=numpy.max(numpy.abs(bg_audio_data)),
event_max=numpy.max(numpy.abs(padded_event)),
sum_max=numpy.max(numpy.abs(mixture)))
)
print('The scaling factor for the event was [{factor}]'.format(factor=scaling_factor))
print('The event before scaling was max [{max}]'.format(max=event_audio_original_max))
mixture /= numpy.max(numpy.abs(mixture))
return mixture
class TUTRareSoundEvents_2017_EvaluationSet(SyntheticSoundEventDataset):
"""TUT Acoustic scenes 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-rare-sound-events-2017-evaluation')
kwargs['filelisthash_exclude_dirs'] = kwargs.get('filelisthash_exclude_dirs', ['generated_data'])
# Initialize baseclass
super(TUTRareSoundEvents_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = True
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Rare Sound Events 2017, evaluation dataset',
'url': None,
'audio_source': 'Synthetic',
'audio_type': 'Natural',
'recording_device_model': 'Unknown',
'microphone_model': 'Unknown',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
@property
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
labels = ['babycry', 'glassbreak', 'gunshot']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for event_label_ in self.event_labels:
event_list_filename = os.path.join(
self.local_path,
'meta',
'event_list_evaltest_' + event_label_ + '.csv'
)
if os.path.isfile(event_list_filename):
# Load train files
current_meta = MetaDataContainer(filename=event_list_filename).load()
# Fix path
for item in current_meta:
item['file'] = os.path.join('audio', item['file'])
meta_data += current_meta
else:
current_meta = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
base_filename, file_extension = os.path.splitext(raw_filename)
if event_label_ in base_filename:
current_meta.append(MetaDataItem({'file': os.path.join(relative_path, raw_filename)}))
self.meta_container.update(meta_data)
self.meta_container.save()
def train(self, fold=0, event_label=None):
return []
def test(self, fold=0, event_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer()
if fold == 0:
event_list_filename = os.path.join(
self.local_path,
'meta',
'event_list_evaltest_' + event_label_ + '.csv'
)
if os.path.isfile(event_list_filename):
# Load train files
self.crossvalidation_data_test[0][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
# Fix file paths
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = os.path.join('audio', item['file'])
else:
# Recover files from audio files
meta = MetaDataContainer()
for item in self.meta:
if event_label_ in item.file:
meta.append(item)
# Change file paths to absolute
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_test[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_test[fold][event_label_]
return data
class TUTSoundEvents_2017_DevelopmentSet(SoundEventDataset):
"""TUT Sound events 2017 development dataset
This dataset is used in DCASE2017 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2017-development')
super(TUTSoundEvents_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'street'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
self.meta_container.update(meta_data)
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='train',
fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
class TUTSoundEvents_2017_EvaluationSet(SoundEventDataset):
"""TUT Sound events 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2017-evaluation')
super(TUTSoundEvents_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = True
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'street'),
},
]
@property
def scene_labels(self):
labels = ['street']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(self.local_path, relative_path.replace('audio', 'meta'),
base_filename + '.ann')
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
meta_data.save(filename=self.meta_container.filename)
else:
self.meta_container.load()
def train(self, fold=0, scene_label=None):
return []
def test(self, fold=0, scene_label=None):
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
else:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_test[fold][scene_label_]
return data
class DCASE2017_Task4tagging_DevelopmentSet(SoundEventDataset):
"""DCASE 2017 Large-scale weakly supervised sound event detection for smart cars
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'DCASE2017-task4-development')
super(DCASE2017_Task4tagging_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'audio tagging'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>',
'name_remote': 'Task 4 Large-scale weakly supervised sound event detection for smart cars',
'url': 'https://github.com/ankitshah009/Task-4-Large-scale-weakly-supervised-sound-event-detection-for-smart-cars',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': None,
'microphone_model': None,
}
self.crossvalidation_folds = 1
self.default_audio_extension = 'flac'
github_url = 'https://raw.githubusercontent.com/ankitshah009/Task-4-Large-scale-weakly-supervised-sound-event-detection-for-smart-cars/master/'
self.package_list = [
{
'remote_package': github_url + 'training_set.csv',
'local_package': os.path.join(self.local_path, 'training_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'testing_set.csv',
'local_package': os.path.join(self.local_path, 'testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_weak_label_training_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_weak_label_training_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_weak_label_testing_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_weak_label_testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'APACHE_LICENSE.txt',
'local_package': os.path.join(self.local_path, 'APACHE_LICENSE.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'README.txt',
'local_package': os.path.join(self.local_path, 'README.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'sound_event_list_17_classes.txt',
'local_package': os.path.join(self.local_path, 'sound_event_list_17_classes.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_strong_label_testing_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_strong_label_testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
@property
def scene_labels(self):
labels = ['youtube']
labels.sort()
return labels
def _after_extract(self, to_return=None):
import csv
from httplib import BadStatusLine
from dcase_framework.files import AudioFile
def progress_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
"""
def inner(total, recvd, ratio, rate, eta):
t.total = int(total / 1024.0)
t.update(int(recvd / 1024.0))
return inner
# Collect file ids
files = []
with open(os.path.join(self.local_path, 'testing_set.csv'), 'rb') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
files.append({
'query_id': row[0],
'segment_start': row[1],
'segment_end': row[2]}
)
with open(os.path.join(self.local_path, 'training_set.csv'), 'rb') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
files.append({
'query_id': row[0],
'segment_start': row[1],
'segment_end': row[2]}
)
# Make sure audio directory exists
if not os.path.isdir(os.path.join(self.local_path, 'audio')):
os.makedirs(os.path.join(self.local_path, 'audio'))
file_progress = tqdm(files,
desc="{0: <25s}".format('Files'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
non_existing_videos = []
# Check that audio files exists
for file_data in file_progress:
audio_filename = os.path.join(self.local_path,
'audio',
'Y{query_id}_{segment_start}_{segment_end}.{extension}'.format(
query_id=file_data['query_id'],
segment_start=file_data['segment_start'],
segment_end=file_data['segment_end'],
extension=self.default_audio_extension
)
)
# Download segment if it does not exists
if not os.path.isfile(audio_filename):
import pafy
#
try:
# Access youtube video and get best quality audio stream
youtube_audio = pafy.new(
url='https://www.youtube.com/watch?v={query_id}'.format(query_id=file_data['query_id']),
basic=False,
gdata=False,
size=False
).getbestaudio()
# Get temp file
tmp_file = os.path.join(self.local_path, 'tmp_file.{extension}'.format(
extension=youtube_audio.extension)
)
# Create download progress bar
download_progress_bar = tqdm(
desc="{0: <25s}".format('Download youtube item '),
file=sys.stdout,
unit='B',
unit_scale=True,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar
)
# Download audio
youtube_audio.download(
filepath=tmp_file,
quiet=True,
callback=progress_hook(download_progress_bar)
)
# Close progress bar
download_progress_bar.close()
# Create audio processing progress bar
audio_processing_progress_bar = tqdm(
desc="{0: <25s}".format('Processing '),
initial=0,
total=4,
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar
)
# Load audio
audio_file = AudioFile()
audio_file.load(
filename=tmp_file,
mono=True,
fs=44100,
res_type='kaiser_best',
start=float(file_data['segment_start']),
stop=float(file_data['segment_end'])
)
audio_processing_progress_bar.update(1)
# Save the segment
audio_file.save(
filename=audio_filename,
bitdepth=16
)
audio_processing_progress_bar.update(3)
# Remove temporal file
os.remove(tmp_file)
audio_processing_progress_bar.close()
except (IOError, BadStatusLine) as e:
# Store files with errors
file_data['error'] = str(e.message)
non_existing_videos.append(file_data)
except (KeyboardInterrupt, SystemExit):
# Remove temporal file and current audio file.
os.remove(tmp_file)
os.remove(audio_filename)
raise
log_filename = os.path.join(self.local_path, 'item_access_error.log')
with open(log_filename, 'wb') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
for item in non_existing_videos:
csv_writer.writerow(
(item['query_id'], item['error'].replace('\n', ' '))
)
# Make sure evaluation_setup directory exists
if not os.path.isdir(os.path.join(self.local_path, self.evaluation_setup_folder)):
os.makedirs(os.path.join(self.local_path, self.evaluation_setup_folder))
# Check that evaluation setup exists
evaluation_setup_exists = True
train_filename = self._get_evaluation_setup_filename(
setup_part='train',
fold=1,
scene_label='youtube',
file_extension='txt'
)
test_filename = self._get_evaluation_setup_filename(
setup_part='test',
fold=1,
scene_label='youtube',
file_extension='txt'
)
evaluate_filename = self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=1,
scene_label='youtube',
file_extension='txt'
)
if not os.path.isfile(train_filename) or not os.path.isfile(test_filename) or not os.path.isfile(
evaluate_filename):
evaluation_setup_exists = False
# Evaluation setup was not found generate
if not evaluation_setup_exists:
fold = 1
train_meta = MetaDataContainer()
for item in MetaDataContainer().load(
os.path.join(self.local_path, 'groundtruth_weak_label_training_set.csv')):
if not item['file'].endswith('flac'):
item['file'] = os.path.join('audio', 'Y' + os.path.splitext(item['file'])[
0] + '.' + self.default_audio_extension)
# Set scene label
item['scene_label'] = 'youtube'
# Translate event onset and offset, weak labels
item['event_offset'] -= item['event_onset']
item['event_onset'] -= item['event_onset']
# Only collect items which exists
if os.path.isfile(os.path.join(self.local_path, item['file'])):
train_meta.append(item)
train_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='train',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
evaluate_meta = MetaDataContainer()
for item in MetaDataContainer().load(
os.path.join(self.local_path, 'groundtruth_strong_label_testing_set.csv')):
if not item['file'].endswith('flac'):
item['file'] = os.path.join('audio', 'Y' + os.path.splitext(item['file'])[
0] + '.' + self.default_audio_extension)
# Set scene label
item['scene_label'] = 'youtube'
# Only collect items which exists
if os.path.isfile(os.path.join(self.local_path, item['file'])):
evaluate_meta.append(item)
evaluate_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
test_meta = MetaDataContainer()
for item in evaluate_meta:
test_meta.append(MetaDataItem({'file': item['file']}))
test_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='test',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
if not self.meta_container.exists():
fold = 1
meta_data = MetaDataContainer()
meta_data += MetaDataContainer().load(self._get_evaluation_setup_filename(
setup_part='train',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
meta_data += MetaDataContainer().load(self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
self.meta_container.update(meta_data)
self.meta_container.save()
else:
self.meta_container.load()
# =====================================================
# DCASE 2016
# =====================================================
class TUTAcousticScenes_2016_DevelopmentSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2016 development dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2016-development')
super(TUTAcousticScenes_2016_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2016, development dataset',
'url': 'https://zenodo.org/record/45739',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.error.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.error.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = {}
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
fold_data += MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_evaluate.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
item['identifier'] = location_id
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
location_id = raw_filename.split('_')[0]
item['identifier'] = location_id
else:
self.crossvalidation_data_train[0] = self.meta_container
return self.crossvalidation_data_train[fold]
class TUTAcousticScenes_2016_EvaluationSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2016 evaluation dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2016-evaluation')
super(TUTAcousticScenes_2016_EvaluationSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2016, evaluation dataset',
'url': 'https://zenodo.org/record/165995',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
eval_file = MetaDataContainer(filename=os.path.join(self.evaluation_setup_path, 'evaluate.txt'))
if not self.meta_container.exists() and eval_file.exists():
eval_data = eval_file.load()
meta_data = {}
for item in eval_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
item['file'] = os.path.join(relative_path, raw_filename)
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
def train(self, fold=0):
return []
def test(self, fold=0):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = []
if fold > 0:
with open(os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_test.txt'), 'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold].append({'file': self.relative_to_absolute_path(row[0])})
else:
data = []
files = []
for item in self.audio_files:
if self.relative_to_absolute_path(item) not in files:
data.append({'file': self.relative_to_absolute_path(item)})
files.append(self.relative_to_absolute_path(item))
self.crossvalidation_data_test[fold] = data
return self.crossvalidation_data_test[fold]
class TUTSoundEvents_2016_DevelopmentSet(SoundEventDataset):
"""TUT Sound events 2016 development dataset
This dataset is used in DCASE2016 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2016-development')
super(TUTSoundEvents_2016_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'residential_area'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'home'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.audio.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.audio.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
meta_data.save(filename=self.meta_container.filename)
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='train', fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
class TUTSoundEvents_2016_EvaluationSet(SoundEventDataset):
"""TUT Sound events 2016 evaluation dataset
This dataset is used in DCASE2016 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2016-evaluation')
super(TUTSoundEvents_2016_EvaluationSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, evaluation dataset',
'url': 'http://www.cs.tut.fi/sgn/arg/dcase2016/download/',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'home'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'residential_area'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.audio.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.audio.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
@property
def scene_labels(self):
labels = ['home', 'residential_area']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists() and os.path.isdir(os.path.join(self.local_path, 'meta')):
meta_file_handle = open(self.meta_container.filename, 'wt')
try:
writer = csv.writer(meta_file_handle, delimiter='\t')
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
if os.path.isfile(annotation_filename):
annotation_file_handle = open(annotation_filename, 'rt')
try:
annotation_file_reader = csv.reader(annotation_file_handle, delimiter='\t')
for annotation_file_row in annotation_file_reader:
writer.writerow((os.path.join(relative_path, raw_filename),
scene_label,
float(annotation_file_row[0].replace(',', '.')),
float(annotation_file_row[1].replace(',', '.')),
annotation_file_row[2], 'm'))
finally:
annotation_file_handle.close()
finally:
meta_file_handle.close()
def train(self, fold=0, scene_label=None):
return []
def test(self, fold=0, scene_label=None):
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = []
if fold > 0:
with open(
os.path.join(self.evaluation_setup_path, scene_label_ + '_fold' + str(fold) + '_test.txt'),
'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold][scene_label_].append(
{'file': self.relative_to_absolute_path(row[0])}
)
else:
with open(os.path.join(self.evaluation_setup_path, scene_label_ + '_test.txt'), 'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold][scene_label_].append(
{'file': self.relative_to_absolute_path(row[0])}
)
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = []
for scene_label_ in self.scene_labels:
for item in self.crossvalidation_data_test[fold][scene_label_]:
data.append(item)
return data
|
[
"logging.getLogger",
"tarfile.open",
"zipfile.ZipFile",
"numpy.array",
"itertools.izip",
"sys.exit",
"socket.setdefaulttimeout",
"os.walk",
"os.remove",
"os.listdir",
"numpy.diff",
"os.path.split",
"os.path.isdir",
"csv.reader",
"os.path.relpath",
"numpy.abs",
"collections.OrderedDict",
"yaml.dump",
"os.rename",
"csv.writer",
"os.path.splitext",
"os.path.isfile",
"numpy.isnan",
"os.makedirs",
"os.path.join",
"numpy.sum",
"os.path.commonprefix",
"os.path.abspath",
"dcase_framework.files.AudioFile",
"numpy.pad",
"six.iteritems"
] |
[((7552, 7611), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (7564, 7611), False, 'import os\n'), ((8138, 8193), 'os.path.join', 'os.path.join', (['self.local_path', 'self.error_meta_filename'], {}), '(self.local_path, self.error_meta_filename)\n', (8150, 8193), False, 'import os\n'), ((17431, 17460), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(120)'], {}), '(120)\n', (17455, 17460), False, 'import socket\n'), ((25813, 25837), 'os.walk', 'os.walk', (['self.local_path'], {}), '(self.local_path)\n', (25820, 25837), False, 'import os\n'), ((64473, 64532), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""bgs"""'], {}), "(self.local_path, 'data', 'source_data', 'bgs')\n", (64485, 64532), False, 'import os\n'), ((64560, 64622), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""events"""'], {}), "(self.local_path, 'data', 'source_data', 'events')\n", (64572, 64622), False, 'import os\n'), ((64647, 64711), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""cv_setup"""'], {}), "(self.local_path, 'data', 'source_data', 'cv_setup')\n", (64659, 64711), False, 'import os\n'), ((81868, 81930), 'os.path.join', 'os.path.join', (['background_audio_path', "mixture_recipe['bg_path']"], {}), "(background_audio_path, mixture_recipe['bg_path'])\n", (81880, 81930), False, 'import os\n'), ((85424, 85548), 'numpy.pad', 'numpy.pad', (['event_audio_data'], {'pad_width': '(event_start_in_mixture_samples, tail_length)', 'mode': '"""constant"""', 'constant_values': '(0)'}), "(event_audio_data, pad_width=(event_start_in_mixture_samples,\n tail_length), mode='constant', constant_values=0)\n", (85433, 85548), False, 'import numpy\n'), ((112519, 112573), 'os.path.join', 'os.path.join', (['self.local_path', '"""item_access_error.log"""'], {}), "(self.local_path, 'item_access_error.log')\n", (112531, 112573), False, 'import os\n'), ((6751, 6778), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (6768, 6778), False, 'import logging\n'), ((10056, 10086), 'os.path.isdir', 'os.path.isdir', (['self.local_path'], {}), '(self.local_path)\n', (10069, 10086), False, 'import os\n'), ((10100, 10128), 'os.makedirs', 'os.makedirs', (['self.local_path'], {}), '(self.local_path)\n', (10111, 10128), False, 'import os\n'), ((26470, 26527), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (26482, 26527), False, 'import os\n'), ((32478, 32510), 'os.path.abspath', 'os.path.abspath', (['self.local_path'], {}), '(self.local_path)\n', (32493, 32510), False, 'import os\n'), ((32532, 32570), 'os.path.relpath', 'os.path.relpath', (['path', 'self.local_path'], {}), '(path, self.local_path)\n', (32547, 32570), False, 'import os\n'), ((38369, 38399), 'os.path.isdir', 'os.path.isdir', (['self.local_path'], {}), '(self.local_path)\n', (38382, 38399), False, 'import os\n'), ((38413, 38441), 'os.makedirs', 'os.makedirs', (['self.local_path'], {}), '(self.local_path)\n', (38424, 38441), False, 'import os\n'), ((45002, 45027), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (45025, 45027), False, 'import collections\n'), ((48831, 48856), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (48854, 48856), False, 'import collections\n'), ((51483, 51528), 'os.path.join', 'os.path.join', (['"""generated_data"""', 'meta_filename'], {}), "('generated_data', meta_filename)\n", (51495, 51528), False, 'import os\n'), ((65887, 65993), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)"], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash)\n", (65899, 65993), False, 'import os\n'), ((66086, 66201), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""audio"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'audio')\n", (66098, 66201), False, 'import os\n'), ((66309, 66423), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'meta')\n", (66321, 66423), False, 'import os\n'), ((75075, 75125), 'os.path.join', 'os.path.join', (['class_label', "event['audio_filename']"], {}), "(class_label, event['audio_filename'])\n", (75087, 75125), False, 'import os\n'), ((82253, 82313), 'os.path.join', 'os.path.join', (['event_audio_path', "mixture_recipe['event_path']"], {}), "(event_audio_path, mixture_recipe['event_path'])\n", (82265, 82313), False, 'import os\n'), ((84671, 84698), 'numpy.abs', 'numpy.abs', (['event_audio_data'], {}), '(event_audio_data)\n', (84680, 84698), False, 'import numpy\n'), ((107246, 107281), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (107256, 107281), False, 'import csv\n'), ((107608, 107643), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (107618, 107643), False, 'import csv\n'), ((112650, 112685), 'csv.writer', 'csv.writer', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (112660, 112685), False, 'import csv\n'), ((7810, 7859), 'os.path.join', 'os.path.join', (['self.local_path', 'self.meta_filename'], {}), '(self.local_path, self.meta_filename)\n', (7822, 7859), False, 'import os\n'), ((21406, 21443), 'os.path.isfile', 'os.path.isfile', (["item['local_package']"], {}), "(item['local_package'])\n", (21420, 21443), False, 'import os\n'), ((32140, 32175), 'os.path.join', 'os.path.join', (['self.local_path', 'path'], {}), '(self.local_path, path)\n', (32152, 32175), False, 'import os\n'), ((40134, 40172), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40146, 40172), False, 'import os\n'), ((40357, 40434), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.doc.zip')\n", (40369, 40434), False, 'import os\n'), ((40472, 40510), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40484, 40510), False, 'import os\n'), ((40696, 40774), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.meta.zip')\n", (40708, 40774), False, 'import os\n'), ((40812, 40850), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40824, 40850), False, 'import os\n'), ((41037, 41116), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.error.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.error.zip')\n", (41049, 41116), False, 'import os\n'), ((41154, 41192), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41166, 41192), False, 'import os\n'), ((41381, 41466), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.1.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.1.zip')\n", (41393, 41466), False, 'import os\n'), ((41500, 41538), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41512, 41538), False, 'import os\n'), ((41727, 41812), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.2.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.2.zip')\n", (41739, 41812), False, 'import os\n'), ((41846, 41884), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41858, 41884), False, 'import os\n'), ((42073, 42158), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.3.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.3.zip')\n", (42085, 42158), False, 'import os\n'), ((42192, 42230), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42204, 42230), False, 'import os\n'), ((42419, 42504), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.4.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.4.zip')\n", (42431, 42504), False, 'import os\n'), ((42538, 42576), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42550, 42576), False, 'import os\n'), ((42765, 42850), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.5.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.5.zip')\n", (42777, 42850), False, 'import os\n'), ((42884, 42922), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42896, 42922), False, 'import os\n'), ((43111, 43196), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.6.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.6.zip')\n", (43123, 43196), False, 'import os\n'), ((43230, 43268), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43242, 43268), False, 'import os\n'), ((43457, 43542), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.7.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.7.zip')\n", (43469, 43542), False, 'import os\n'), ((43576, 43614), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43588, 43614), False, 'import os\n'), ((43803, 43888), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.8.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.8.zip')\n", (43815, 43888), False, 'import os\n'), ((43922, 43960), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43934, 43960), False, 'import os\n'), ((44149, 44234), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.9.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.9.zip')\n", (44161, 44234), False, 'import os\n'), ((44268, 44306), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (44280, 44306), False, 'import os\n'), ((44496, 44582), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.10.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.10.zip')\n", (44508, 44582), False, 'import os\n'), ((44616, 44654), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (44628, 44654), False, 'import os\n'), ((48445, 48483), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (48457, 48483), False, 'import os\n'), ((52266, 52304), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (52278, 52304), False, 'import os\n'), ((52535, 52614), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-rare-sound-events-2017-development.doc.zip')\n", (52547, 52614), False, 'import os\n'), ((52652, 52690), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (52664, 52690), False, 'import os\n'), ((52922, 53007), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.code.zip"""'], {}), "(self.local_path, 'TUT-rare-sound-events-2017-development.code.zip'\n )\n", (52934, 53007), False, 'import os\n'), ((53040, 53078), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53052, 53078), False, 'import os\n'), ((53335, 53444), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip')\n", (53347, 53444), False, 'import os\n'), ((53478, 53516), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53490, 53516), False, 'import os\n'), ((53773, 53882), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip')\n", (53785, 53882), False, 'import os\n'), ((53916, 53954), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53928, 53954), False, 'import os\n'), ((54211, 54320), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip')\n", (54223, 54320), False, 'import os\n'), ((54354, 54392), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (54366, 54392), False, 'import os\n'), ((54649, 54758), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip')\n", (54661, 54758), False, 'import os\n'), ((54792, 54830), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (54804, 54830), False, 'import os\n'), ((55087, 55196), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip')\n", (55099, 55196), False, 'import os\n'), ((55230, 55268), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (55242, 55268), False, 'import os\n'), ((55525, 55634), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip')\n", (55537, 55634), False, 'import os\n'), ((55668, 55706), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (55680, 55706), False, 'import os\n'), ((55963, 56072), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip')\n", (55975, 56072), False, 'import os\n'), ((56106, 56144), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56118, 56144), False, 'import os\n'), ((56401, 56510), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip')\n", (56413, 56510), False, 'import os\n'), ((56544, 56582), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56556, 56582), False, 'import os\n'), ((56828, 56926), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_events.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_events.zip')\n", (56840, 56926), False, 'import os\n'), ((56960, 56998), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56972, 56998), False, 'import os\n'), ((66556, 66583), 'os.path.isdir', 'os.path.isdir', (['mixture_path'], {}), '(mixture_path)\n', (66569, 66583), False, 'import os\n'), ((66601, 66626), 'os.makedirs', 'os.makedirs', (['mixture_path'], {}), '(mixture_path)\n', (66612, 66626), False, 'import os\n'), ((66647, 66680), 'os.path.isdir', 'os.path.isdir', (['mixture_audio_path'], {}), '(mixture_audio_path)\n', (66660, 66680), False, 'import os\n'), ((66698, 66729), 'os.makedirs', 'os.makedirs', (['mixture_audio_path'], {}), '(mixture_audio_path)\n', (66709, 66729), False, 'import os\n'), ((66750, 66782), 'os.path.isdir', 'os.path.isdir', (['mixture_meta_path'], {}), '(mixture_meta_path)\n', (66763, 66782), False, 'import os\n'), ((66800, 66830), 'os.makedirs', 'os.makedirs', (['mixture_meta_path'], {}), '(mixture_meta_path)\n', (66811, 66830), False, 'import os\n'), ((67520, 67627), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('mixture_recipes_' + subset_name_on_disk + '_' + class_label + '.yaml')"], {}), "(mixture_meta_path, 'mixture_recipes_' + subset_name_on_disk +\n '_' + class_label + '.yaml')\n", (67532, 67627), False, 'import os\n'), ((70254, 70355), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_' + subset_name_on_disk + '_' + class_label + '.csv')"], {}), "(mixture_meta_path, 'event_list_' + subset_name_on_disk + '_' +\n class_label + '.csv')\n", (70266, 70355), False, 'import os\n'), ((72336, 72381), 'os.path.join', 'os.path.join', (['mixture_path', '"""parameters.yaml"""'], {}), "(mixture_path, 'parameters.yaml')\n", (72348, 72381), False, 'import os\n'), ((72781, 72802), 'six.iteritems', 'iteritems', (['subset_map'], {}), '(subset_map)\n', (72790, 72802), False, 'from six import iteritems\n'), ((75164, 75192), 'numpy.diff', 'numpy.diff', (["event['segment']"], {}), "(event['segment'])\n", (75174, 75192), False, 'import numpy\n'), ((76703, 76798), 'itertools.izip', 'zip', (['event_offsets_seconds[event_presence_flags]', 'event_instance_ids[event_presence_flags]'], {}), '(event_offsets_seconds[event_presence_flags], event_instance_ids[\n event_presence_flags])\n', (76706, 76798), True, 'from itertools import izip as zip\n'), ((76820, 76840), 'numpy.array', 'numpy.array', (['checker'], {}), '(checker)\n', (76831, 76840), False, 'import numpy\n'), ((77049, 77080), 'numpy.sum', 'numpy.sum', (['event_presence_flags'], {}), '(event_presence_flags)\n', (77058, 77080), False, 'import numpy\n'), ((77458, 77548), 'itertools.izip', 'zip', (['bgs', 'event_presence_flags', 'event_offsets_seconds', 'target_ebrs', 'event_instance_ids'], {}), '(bgs, event_presence_flags, event_offsets_seconds, target_ebrs,\n event_instance_ids)\n', (77461, 77548), True, 'from itertools import izip as zip\n'), ((81995, 82006), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (82004, 82006), False, 'from dcase_framework.files import AudioFile\n'), ((86128, 86146), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86137, 86146), False, 'import numpy\n'), ((86872, 86890), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86881, 86890), False, 'import numpy\n'), ((88157, 88195), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (88169, 88195), False, 'import os\n'), ((89034, 89123), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""', "('event_list_evaltest_' + event_label_ + '.csv')"], {}), "(self.local_path, 'meta', 'event_list_evaltest_' + event_label_ +\n '.csv')\n", (89046, 89123), False, 'import os\n'), ((89218, 89253), 'os.path.isfile', 'os.path.isfile', (['event_list_filename'], {}), '(event_list_filename)\n', (89232, 89253), False, 'import os\n'), ((93738, 93776), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (93750, 93776), False, 'import os\n'), ((93922, 93970), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""street"""'], {}), "(self.local_path, 'audio', 'street')\n", (93934, 93970), False, 'import os\n'), ((94152, 94226), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.doc.zip')\n", (94164, 94226), False, 'import os\n'), ((94264, 94302), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94276, 94302), False, 'import os\n'), ((94485, 94560), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.meta.zip')\n", (94497, 94560), False, 'import os\n'), ((94598, 94636), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94610, 94636), False, 'import os\n'), ((94822, 94900), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.audio.1.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.audio.1.zip')\n", (94834, 94900), False, 'import os\n'), ((94938, 94976), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94950, 94976), False, 'import os\n'), ((95162, 95240), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.audio.2.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.audio.2.zip')\n", (95174, 95240), False, 'import os\n'), ((95278, 95316), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (95290, 95316), False, 'import os\n'), ((95772, 95795), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (95785, 95795), False, 'import os\n'), ((95981, 96011), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (95997, 96011), False, 'import os\n'), ((99926, 99964), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (99938, 99964), False, 'import os\n'), ((100110, 100158), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""street"""'], {}), "(self.local_path, 'audio', 'street')\n", (100122, 100158), False, 'import os\n'), ((100729, 100752), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (100742, 100752), False, 'import os\n'), ((100938, 100968), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (100954, 100968), False, 'import os\n'), ((104316, 104365), 'os.path.join', 'os.path.join', (['self.local_path', '"""training_set.csv"""'], {}), "(self.local_path, 'training_set.csv')\n", (104328, 104365), False, 'import os\n'), ((104403, 104441), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104415, 104441), False, 'import os\n'), ((104571, 104619), 'os.path.join', 'os.path.join', (['self.local_path', '"""testing_set.csv"""'], {}), "(self.local_path, 'testing_set.csv')\n", (104583, 104619), False, 'import os\n'), ((104657, 104695), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104669, 104695), False, 'import os\n'), ((104849, 104921), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_training_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_training_set.csv')\n", (104861, 104921), False, 'import os\n'), ((104959, 104997), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104971, 104997), False, 'import os\n'), ((105150, 105221), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_testing_set.csv')\n", (105162, 105221), False, 'import os\n'), ((105259, 105297), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105271, 105297), False, 'import os\n'), ((105430, 105481), 'os.path.join', 'os.path.join', (['self.local_path', '"""APACHE_LICENSE.txt"""'], {}), "(self.local_path, 'APACHE_LICENSE.txt')\n", (105442, 105481), False, 'import os\n'), ((105519, 105557), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105531, 105557), False, 'import os\n'), ((105682, 105725), 'os.path.join', 'os.path.join', (['self.local_path', '"""README.txt"""'], {}), "(self.local_path, 'README.txt')\n", (105694, 105725), False, 'import os\n'), ((105763, 105801), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105775, 105801), False, 'import os\n'), ((105947, 106011), 'os.path.join', 'os.path.join', (['self.local_path', '"""sound_event_list_17_classes.txt"""'], {}), "(self.local_path, 'sound_event_list_17_classes.txt')\n", (105959, 106011), False, 'import os\n'), ((106049, 106087), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (106061, 106087), False, 'import os\n'), ((106242, 106315), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_strong_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_strong_label_testing_set.csv')\n", (106254, 106315), False, 'import os\n'), ((106353, 106391), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (106365, 106391), False, 'import os\n'), ((107152, 107200), 'os.path.join', 'os.path.join', (['self.local_path', '"""testing_set.csv"""'], {}), "(self.local_path, 'testing_set.csv')\n", (107164, 107200), False, 'import os\n'), ((107513, 107562), 'os.path.join', 'os.path.join', (['self.local_path', '"""training_set.csv"""'], {}), "(self.local_path, 'training_set.csv')\n", (107525, 107562), False, 'import os\n'), ((107929, 107967), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (107941, 107967), False, 'import os\n'), ((107994, 108032), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (108006, 108032), False, 'import os\n'), ((109177, 109207), 'os.path.isfile', 'os.path.isfile', (['audio_filename'], {}), '(audio_filename)\n', (109191, 109207), False, 'import os\n'), ((112943, 113002), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (112955, 113002), False, 'import os\n'), ((113029, 113088), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (113041, 113088), False, 'import os\n'), ((113773, 113803), 'os.path.isfile', 'os.path.isfile', (['train_filename'], {}), '(train_filename)\n', (113787, 113803), False, 'import os\n'), ((113811, 113840), 'os.path.isfile', 'os.path.isfile', (['test_filename'], {}), '(test_filename)\n', (113825, 113840), False, 'import os\n'), ((113848, 113881), 'os.path.isfile', 'os.path.isfile', (['evaluate_filename'], {}), '(evaluate_filename)\n', (113862, 113881), False, 'import os\n'), ((114172, 114244), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_training_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_training_set.csv')\n", (114184, 114244), False, 'import os\n'), ((115250, 115323), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_strong_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_strong_label_testing_set.csv')\n", (115262, 115323), False, 'import os\n'), ((118445, 118483), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (118457, 118483), False, 'import os\n'), ((118667, 118744), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.doc.zip')\n", (118679, 118744), False, 'import os\n'), ((118782, 118820), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (118794, 118820), False, 'import os\n'), ((119005, 119083), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.meta.zip')\n", (119017, 119083), False, 'import os\n'), ((119121, 119159), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119133, 119159), False, 'import os\n'), ((119345, 119424), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.error.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.error.zip')\n", (119357, 119424), False, 'import os\n'), ((119462, 119500), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119474, 119500), False, 'import os\n'), ((119688, 119773), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.1.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.1.zip')\n", (119700, 119773), False, 'import os\n'), ((119807, 119845), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119819, 119845), False, 'import os\n'), ((120033, 120118), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.2.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.2.zip')\n", (120045, 120118), False, 'import os\n'), ((120152, 120190), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120164, 120190), False, 'import os\n'), ((120378, 120463), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.3.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.3.zip')\n", (120390, 120463), False, 'import os\n'), ((120497, 120535), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120509, 120535), False, 'import os\n'), ((120723, 120808), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.4.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.4.zip')\n", (120735, 120808), False, 'import os\n'), ((120842, 120880), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120854, 120880), False, 'import os\n'), ((121068, 121153), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.5.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.5.zip')\n", (121080, 121153), False, 'import os\n'), ((121187, 121225), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121199, 121225), False, 'import os\n'), ((121413, 121498), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.6.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.6.zip')\n", (121425, 121498), False, 'import os\n'), ((121532, 121570), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121544, 121570), False, 'import os\n'), ((121758, 121843), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.7.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.7.zip')\n", (121770, 121843), False, 'import os\n'), ((121877, 121915), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121889, 121915), False, 'import os\n'), ((122103, 122188), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.8.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.8.zip')\n", (122115, 122188), False, 'import os\n'), ((122222, 122260), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (122234, 122260), False, 'import os\n'), ((125955, 125993), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (125967, 125993), False, 'import os\n'), ((126177, 126253), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.doc.zip')\n", (126189, 126253), False, 'import os\n'), ((126291, 126329), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126303, 126329), False, 'import os\n'), ((126517, 126602), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.1.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.1.zip'\n )\n", (126529, 126602), False, 'import os\n'), ((126635, 126673), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126647, 126673), False, 'import os\n'), ((126861, 126946), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.2.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.2.zip'\n )\n", (126873, 126946), False, 'import os\n'), ((126979, 127017), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126991, 127017), False, 'import os\n'), ((127205, 127290), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.3.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.3.zip'\n )\n", (127217, 127290), False, 'import os\n'), ((127323, 127361), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (127335, 127361), False, 'import os\n'), ((127546, 127623), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.meta.zip')\n", (127558, 127623), False, 'import os\n'), ((127661, 127699), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (127673, 127699), False, 'import os\n'), ((128025, 128081), 'os.path.join', 'os.path.join', (['self.evaluation_setup_path', '"""evaluate.txt"""'], {}), "(self.evaluation_setup_path, 'evaluate.txt')\n", (128037, 128081), False, 'import os\n'), ((131123, 131161), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (131135, 131161), False, 'import os\n'), ((131307, 131365), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""residential_area"""'], {}), "(self.local_path, 'audio', 'residential_area')\n", (131319, 131365), False, 'import os\n'), ((131511, 131557), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""home"""'], {}), "(self.local_path, 'audio', 'home')\n", (131523, 131557), False, 'import os\n'), ((131738, 131812), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.doc.zip')\n", (131750, 131812), False, 'import os\n'), ((131850, 131888), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (131862, 131888), False, 'import os\n'), ((132070, 132145), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.meta.zip')\n", (132082, 132145), False, 'import os\n'), ((132183, 132221), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (132195, 132221), False, 'import os\n'), ((132404, 132480), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.audio.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.audio.zip')\n", (132416, 132480), False, 'import os\n'), ((132518, 132556), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (132530, 132556), False, 'import os\n'), ((133012, 133035), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (133025, 133035), False, 'import os\n'), ((133221, 133251), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (133237, 133251), False, 'import os\n'), ((137032, 137070), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (137044, 137070), False, 'import os\n'), ((137216, 137262), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""home"""'], {}), "(self.local_path, 'audio', 'home')\n", (137228, 137262), False, 'import os\n'), ((137408, 137466), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""residential_area"""'], {}), "(self.local_path, 'audio', 'residential_area')\n", (137420, 137466), False, 'import os\n'), ((137663, 137736), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.doc.zip')\n", (137675, 137736), False, 'import os\n'), ((137774, 137812), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (137786, 137812), False, 'import os\n'), ((138010, 138084), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.meta.zip')\n", (138022, 138084), False, 'import os\n'), ((138122, 138160), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (138134, 138160), False, 'import os\n'), ((138359, 138434), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.audio.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.audio.zip')\n", (138371, 138434), False, 'import os\n'), ((138472, 138510), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (138484, 138510), False, 'import os\n'), ((138986, 139023), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""'], {}), "(self.local_path, 'meta')\n", (138998, 139023), False, 'import os\n'), ((139140, 139184), 'csv.writer', 'csv.writer', (['meta_file_handle'], {'delimiter': '"""\t"""'}), "(meta_file_handle, delimiter='\\t')\n", (139150, 139184), False, 'import csv\n'), ((5687, 5723), 'logging.getLogger', 'logging.getLogger', (['"""dataset_factory"""'], {}), "('dataset_factory')\n", (5704, 5723), False, 'import logging\n'), ((10802, 10818), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (10812, 10818), False, 'import os\n'), ((19128, 19169), 'os.path.join', 'os.path.join', (['self.local_path', '"""tmp_file"""'], {}), "(self.local_path, 'tmp_file')\n", (19140, 19169), False, 'import os\n'), ((19923, 19965), 'os.rename', 'os.rename', (['tmp_file', "item['local_package']"], {}), "(tmp_file, item['local_package'])\n", (19932, 19965), False, 'import os\n'), ((47008, 47035), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (47021, 47035), False, 'import os\n'), ((58375, 58470), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (58387, 58470), False, 'import os\n'), ((58628, 58707), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (58640, 58707), False, 'import os\n'), ((61820, 61914), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (61832, 61914), False, 'import os\n'), ((62072, 62150), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (62084, 62150), False, 'import os\n'), ((65420, 65487), 'os.path.join', 'os.path.join', (['cv_setup_path', "('bgs_' + subset_name_on_disk + '.yaml')"], {}), "(cv_setup_path, 'bgs_' + subset_name_on_disk + '.yaml')\n", (65432, 65487), False, 'import os\n'), ((65561, 65631), 'os.path.join', 'os.path.join', (['cv_setup_path', "('events_' + subset_name_on_disk + '.yaml')"], {}), "(cv_setup_path, 'events_' + subset_name_on_disk + '.yaml')\n", (65573, 65631), False, 'import os\n'), ((67755, 67795), 'os.path.isfile', 'os.path.isfile', (['mixture_recipes_filename'], {}), '(mixture_recipes_filename)\n', (67769, 67795), False, 'import os\n'), ((69372, 69436), 'os.path.join', 'os.path.join', (['mixture_audio_path', "item['mixture_audio_filename']"], {}), "(mixture_audio_path, item['mixture_audio_filename'])\n", (69384, 69436), False, 'import os\n'), ((72439, 72473), 'os.path.isfile', 'os.path.isfile', (['mixture_parameters'], {}), '(mixture_parameters)\n', (72453, 72473), False, 'import os\n'), ((72932, 73046), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'meta')\n", (72944, 73046), False, 'import os\n'), ((73204, 73305), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_' + subset_name_on_disk + '_' + class_label + '.csv')"], {}), "(mixture_meta_path, 'event_list_' + subset_name_on_disk + '_' +\n class_label + '.csv')\n", (73216, 73305), False, 'import os\n'), ((78239, 78269), 'numpy.isnan', 'numpy.isnan', (['event_instance_id'], {}), '(event_instance_id)\n', (78250, 78269), False, 'import numpy\n'), ((82387, 82398), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (82396, 82398), False, 'from dcase_framework.files import AudioFile\n'), ((91162, 91251), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""', "('event_list_evaltest_' + event_label_ + '.csv')"], {}), "(self.local_path, 'meta', 'event_list_evaltest_' + event_label_ +\n '.csv')\n", (91174, 91251), False, 'import os\n'), ((91366, 91401), 'os.path.isfile', 'os.path.isfile', (['event_list_filename'], {}), '(event_list_filename)\n', (91380, 91401), False, 'import os\n'), ((96370, 96411), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (96382, 96411), False, 'import os\n'), ((98301, 98328), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (98314, 98328), False, 'import os\n'), ((101299, 101340), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (101311, 101340), False, 'import os\n'), ((111241, 111252), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (111250, 111252), False, 'from dcase_framework.files import AudioFile\n'), ((111966, 111985), 'os.remove', 'os.remove', (['tmp_file'], {}), '(tmp_file)\n', (111975, 111985), False, 'import os\n'), ((114812, 114855), 'os.path.join', 'os.path.join', (['self.local_path', "item['file']"], {}), "(self.local_path, item['file'])\n", (114824, 114855), False, 'import os\n'), ((115707, 115750), 'os.path.join', 'os.path.join', (['self.local_path', "item['file']"], {}), "(self.local_path, item['file'])\n", (115719, 115750), False, 'import os\n'), ((124534, 124561), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (124547, 124561), False, 'import os\n'), ((128349, 128376), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (128362, 128376), False, 'import os\n'), ((128484, 128525), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (128496, 128525), False, 'import os\n'), ((129381, 129410), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (129391, 129410), False, 'import csv\n'), ((133610, 133651), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (133622, 133651), False, 'import os\n'), ((135436, 135463), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (135449, 135463), False, 'import os\n'), ((139280, 139303), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (139293, 139303), False, 'import os\n'), ((139501, 139531), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (139517, 139531), False, 'import os\n'), ((139787, 139822), 'os.path.isfile', 'os.path.isfile', (['annotation_filename'], {}), '(annotation_filename)\n', (139801, 139822), False, 'import os\n'), ((10903, 10922), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (10919, 10922), False, 'import os\n'), ((17908, 17945), 'os.path.isfile', 'os.path.isfile', (["item['local_package']"], {}), "(item['local_package'])\n", (17922, 17945), False, 'import os\n'), ((21530, 21573), 'zipfile.ZipFile', 'zipfile.ZipFile', (["item['local_package']", '"""r"""'], {}), "(item['local_package'], 'r')\n", (21545, 21573), False, 'import zipfile\n'), ((24275, 24318), 'tarfile.open', 'tarfile.open', (["item['local_package']", '"""r:gz"""'], {}), "(item['local_package'], 'r:gz')\n", (24287, 24318), False, 'import tarfile\n'), ((26050, 26074), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (26062, 26074), False, 'import os\n'), ((27327, 27384), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (27339, 27384), False, 'import os\n'), ((45596, 45623), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (45609, 45623), False, 'import os\n'), ((45804, 45845), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (45816, 45845), False, 'import os\n'), ((49259, 49286), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (49272, 49286), False, 'import os\n'), ((49467, 49508), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (49479, 49508), False, 'import os\n'), ((59089, 59184), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (59101, 59184), False, 'import os\n'), ((59342, 59421), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (59354, 59421), False, 'import os\n'), ((59806, 59900), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (59818, 59900), False, 'import os\n'), ((60057, 60135), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (60069, 60135), False, 'import os\n'), ((62482, 62577), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (62494, 62577), False, 'import os\n'), ((62735, 62814), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (62747, 62814), False, 'import os\n'), ((63219, 63313), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (63231, 63313), False, 'import os\n'), ((63471, 63549), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (63483, 63549), False, 'import os\n'), ((69465, 69493), 'os.path.isfile', 'os.path.isfile', (['mixture_file'], {}), '(mixture_file)\n', (69479, 69493), False, 'import os\n'), ((69851, 69902), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {'data': 'mixture', 'fs': "params['mixture']['fs']"}), "(data=mixture, fs=params['mixture']['fs'])\n", (69860, 69902), False, 'from dcase_framework.files import AudioFile\n'), ((78439, 78490), 'os.path.join', 'os.path.join', (['background_audio_path', "bg['filepath']"], {}), "(background_audio_path, bg['filepath'])\n", (78451, 78490), False, 'import os\n'), ((80686, 80711), 'yaml.dump', 'yaml.dump', (['mixture_recipe'], {}), '(mixture_recipe)\n', (80695, 80711), False, 'import yaml\n'), ((86209, 86227), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86218, 86227), False, 'import numpy\n'), ((89500, 89535), 'os.path.join', 'os.path.join', (['"""audio"""', "item['file']"], {}), "('audio', item['file'])\n", (89512, 89535), False, 'import os\n'), ((89764, 89787), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (89777, 89787), False, 'import os\n'), ((89920, 89950), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (89936, 89950), False, 'import os\n'), ((96507, 96537), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (96523, 96537), False, 'import os\n'), ((98370, 98400), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (98386, 98400), False, 'import os\n'), ((101436, 101466), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (101452, 101466), False, 'import os\n'), ((112403, 112422), 'os.remove', 'os.remove', (['tmp_file'], {}), '(tmp_file)\n', (112412, 112422), False, 'import os\n'), ((112443, 112468), 'os.remove', 'os.remove', (['audio_filename'], {}), '(audio_filename)\n', (112452, 112468), False, 'import os\n'), ((123176, 123203), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (123189, 123203), False, 'import os\n'), ((123384, 123425), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (123396, 123425), False, 'import os\n'), ((133747, 133777), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (133763, 133777), False, 'import os\n'), ((135505, 135535), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (135521, 135535), False, 'import os\n'), ((141383, 141412), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (141393, 141412), False, 'import csv\n'), ((141781, 141810), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (141791, 141810), False, 'import csv\n'), ((21879, 21906), 'os.path.commonprefix', 'os.path.commonprefix', (['parts'], {}), '(parts)\n', (21899, 21906), False, 'import os\n'), ((25889, 25911), 'os.path.splitext', 'os.path.splitext', (['name'], {}), '(name)\n', (25905, 25911), False, 'import os\n'), ((25918, 25962), 'os.path.splitext', 'os.path.splitext', (['self.filelisthash_filename'], {}), '(self.filelisthash_filename)\n', (25934, 25962), False, 'import os\n'), ((25970, 25989), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (25983, 25989), False, 'import os\n'), ((71497, 71627), 'os.path.join', 'os.path.join', (['"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""audio"""', "item['mixture_audio_filename']"], {}), "('generated_data', 'mixtures_' + subset_name_on_disk + '_' +\n params_hash, 'audio', item['mixture_audio_filename'])\n", (71509, 71627), False, 'import os\n'), ((74497, 74509), 'numpy.abs', 'numpy.abs', (['y'], {}), '(y)\n', (74506, 74509), False, 'import numpy\n'), ((86483, 86507), 'numpy.abs', 'numpy.abs', (['bg_audio_data'], {}), '(bg_audio_data)\n', (86492, 86507), False, 'import numpy\n'), ((86546, 86569), 'numpy.abs', 'numpy.abs', (['padded_event'], {}), '(padded_event)\n', (86555, 86569), False, 'import numpy\n'), ((86606, 86624), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86615, 86624), False, 'import numpy\n'), ((91777, 91812), 'os.path.join', 'os.path.join', (['"""audio"""', "item['file']"], {}), "('audio', item['file'])\n", (91789, 91812), False, 'import os\n'), ((139987, 140037), 'csv.reader', 'csv.reader', (['annotation_file_handle'], {'delimiter': '"""\t"""'}), "(annotation_file_handle, delimiter='\\t')\n", (139997, 140037), False, 'import csv\n'), ((141664, 141732), 'os.path.join', 'os.path.join', (['self.evaluation_setup_path', "(scene_label_ + '_test.txt')"], {}), "(self.evaluation_setup_path, scene_label_ + '_test.txt')\n", (141676, 141732), False, 'import os\n'), ((26577, 26634), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (26589, 26634), False, 'import os\n'), ((11042, 11063), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (11054, 11063), False, 'import os\n'), ((25170, 25214), 'os.path.join', 'os.path.join', (['self.local_path', 'tar_info.name'], {}), '(self.local_path, tar_info.name)\n', (25182, 25214), False, 'import os\n'), ((11150, 11171), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (11162, 11171), False, 'import os\n'), ((23604, 23650), 'os.path.join', 'os.path.join', (['self.local_path', 'member.filename'], {}), '(self.local_path, member.filename)\n', (23616, 23650), False, 'import os\n'), ((90079, 90120), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (90091, 90120), False, 'import os\n'), ((114364, 114394), 'os.path.splitext', 'os.path.splitext', (["item['file']"], {}), "(item['file'])\n", (114380, 114394), False, 'import os\n'), ((115443, 115473), 'os.path.splitext', 'os.path.splitext', (["item['file']"], {}), "(item['file'])\n", (115459, 115473), False, 'import os\n'), ((140166, 140207), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (140178, 140207), False, 'import os\n'), ((24124, 24134), 'sys.exit', 'sys.exit', ([], {}), '()\n', (24132, 24134), False, 'import sys\n'), ((23988, 24034), 'os.path.join', 'os.path.join', (['self.local_path', 'member.filename'], {}), '(self.local_path, member.filename)\n', (24000, 24034), False, 'import os\n')]
|
#!/usr/bin/env python3
from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling import Fittable2DModel, Parameter
import sys
import logging
import argparse
import warnings
from datetime import datetime
from glob import glob
import numpy as np
import scipy.ndimage as nd
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.stats import sigma_clipped_stats
from astropy.wcs import WCS
from astropy.table import Table
from astropy.wcs import FITSFixedWarning
import photutils as pu
import sep
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*', help='files to process')
parser.add_argument('--reprocess', action='store_true')
parser.add_argument('--verbose', '-v', action='store_true',
help='verbose logging')
args = parser.parse_args()
######################################################################
class GaussianConst2D(Fittable2DModel):
"""A model for a 2D Gaussian plus a constant.
Code from photutils (Copyright (c) 2011, Photutils developers).
Parameters
----------
constant : float
Value of the constant.
amplitude : float
Amplitude of the Gaussian.
x_mean : float
Mean of the Gaussian in x.
y_mean : float
Mean of the Gaussian in y.
x_stddev : float
Standard deviation of the Gaussian in x. ``x_stddev`` and
``y_stddev`` must be specified unless a covariance matrix
(``cov_matrix``) is input.
y_stddev : float
Standard deviation of the Gaussian in y. ``x_stddev`` and
``y_stddev`` must be specified unless a covariance matrix
(``cov_matrix``) is input.
theta : float, optional
Rotation angle in radians. The rotation angle increases
counterclockwise.
"""
constant = Parameter(default=1)
amplitude = Parameter(default=1)
x_mean = Parameter(default=0)
y_mean = Parameter(default=0)
x_stddev = Parameter(default=1)
y_stddev = Parameter(default=1)
theta = Parameter(default=0)
@staticmethod
def evaluate(x, y, constant, amplitude, x_mean, y_mean, x_stddev,
y_stddev, theta):
"""Two dimensional Gaussian plus constant function."""
model = Const2D(constant)(x, y) + Gaussian2D(amplitude, x_mean,
y_mean, x_stddev,
y_stddev, theta)(x, y)
return model
def fit_2dgaussian(data):
"""Fit a 2D Gaussian plus a constant to a 2D image.
Based on code from photutils (Copyright (c) 2011, Photutils developers).
Parameters
----------
data : array_like
The 2D array of the image.
Returns
-------
result : A `GaussianConst2D` model instance.
The best-fitting Gaussian 2D model.
"""
if np.ma.count(data) < 7:
raise ValueError('Input data must have a least 7 unmasked values to '
'fit a 2D Gaussian plus a constant.')
data.fill_value = 0.
data = data.filled()
# Subtract the minimum of the data as a rough background estimate.
# This will also make the data values positive, preventing issues with
# the moment estimation in data_properties. Moments from negative data
# values can yield undefined Gaussian parameters, e.g., x/y_stddev.
data = data - np.min(data)
guess_y, guess_x = np.array(data.shape) / 2
init_amplitude = np.ptp(data)
g_init = GaussianConst2D(constant=0, amplitude=init_amplitude,
x_mean=guess_x,
y_mean=guess_y,
x_stddev=3,
y_stddev=3,
theta=0)
fitter = LevMarLSQFitter()
y, x = np.indices(data.shape)
gfit = fitter(g_init, x, y, data)
return gfit
######################################################################
# setup logging
logger = logging.Logger('LMI Add Catalog')
logger.setLevel(logging.DEBUG)
# this allows logging to work when lmi-add-cat is run multiple times from
# ipython
if len(logger.handlers) == 0:
formatter = logging.Formatter('%(levelname)s: %(message)s')
level = logging.DEBUG if args.verbose else logging.INFO
console = logging.StreamHandler(sys.stdout)
console.setLevel(level)
console.setFormatter(formatter)
logger.addHandler(console)
logfile = logging.FileHandler('lmi-add-cat.log')
logfile.setLevel(level)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
logger.info('#' * 70)
logger.info(datetime.now().isoformat())
logger.info('Command line: ' + ' '.join(sys.argv[1:]))
######################################################################
# suppress unnecessary warnings
warnings.simplefilter('ignore', FITSFixedWarning)
######################################################################
def show_objects(im, objects):
# plot background-subtracted image
fig, ax = plt.subplots()
m, s = np.mean(im), np.std(im)
im = ax.imshow(im, interpolation='nearest', cmap='gray',
vmin=m-s, vmax=m+s, origin='lower')
# plot an ellipse for each object
for i in range(len(objects)):
e = Ellipse(xy=(objects['x'][i], objects['y'][i]),
width=6*objects['a'][i],
height=6*objects['b'][i],
angle=objects['theta'][i] * 180. / np.pi)
e.set_facecolor('none')
e.set_edgecolor('red')
ax.add_artist(e)
for f in args.files:
if fits.getheader(f)['IMAGETYP'] != 'OBJECT':
continue
logger.debug(f)
with fits.open(f, mode='update') as hdu:
im = hdu[0].data + 0
h = hdu[0].header
if h['IMAGETYP'].upper() != 'OBJECT':
logger.warning(
f'Refusing to measure {f} with image type {h["imagetyp"]}.')
continue
if 'MASK' in hdu:
mask = hdu['MASK'].data.astype(bool)
else:
mask = np.zeros_like(im, bool)
if 'cat' in hdu:
if not args.reprocess:
continue
else:
del hdu['cat']
det = np.zeros_like(mask)
for iteration in range(3):
bkg = sep.Background(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)
# mask potential sources
det = ((im - bkg) / bkg.globalrms) > 3
# remove isolated pixels
det = nd.binary_closing(det)
bkg = sep.Background(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)
if 'bg' in hdu:
del hdu['bg']
hdu.append(fits.ImageHDU(bkg.back(), name='bg'))
hdu['bg'].header['bg'] = bkg.globalback
hdu['bg'].header['rms'] = bkg.globalrms
data = im - bkg
data[mask] = 0
try:
objects, labels = sep.extract(data, 3, err=bkg.globalrms,
segmentation_map=True)
except Exception as e:
logger.error(f'{f}: Object detection failed - {str(e)}')
continue
hdu[0].header['ncat'] = len(objects), 'number of objects in catalog'
if len(objects) == 0:
continue
#show_objects(data, objects)
# estimate seeing
fwhms = []
segmap = pu.SegmentationImage(labels)
for i in np.random.choice(len(segmap.segments), 50):
obj = segmap.segments[i].make_cutout(data, masked_array=True)
try:
g = fit_2dgaussian(obj)
except:
continue
fwhm = np.mean((g.x_stddev.value, g.y_stddev.value)) * 2.35
if fwhm < 1:
continue
fwhms.append(fwhm)
fwhm = sigma_clipped_stats(fwhms)[1]
rap = fwhm * 2 if np.isfinite(fwhm) else 10
flux, fluxerr, flag = sep.sum_circle(
data, objects['x'], objects['y'], rap, err=bkg.globalrms,
gain=h['gain'])
kronrad, krflag = sep.kron_radius(data, objects['x'], objects['y'],
objects['a'], objects['b'],
objects['theta'], 6.0)
krflux, krfluxerr, _flag = sep.sum_ellipse(
data, objects['x'], objects['y'], objects['a'], objects['b'],
np.minimum(objects['theta'], np.pi / 2.00001),
2.5 * kronrad, subpix=1, err=bkg.globalrms,
gain=h['gain'])
krflag |= _flag # combine flags
wcs = WCS(h)
ra, dec = wcs.all_pix2world(objects['x'], objects['y'], 0)
tab = Table((objects['x'], objects['y'], ra, dec, flux, fluxerr,
flag, objects['a'], objects['b'], objects['theta'],
kronrad, krflux, krfluxerr, krflag),
names=('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag',
'a', 'b', 'theta', 'kronrad', 'krflux',
'krfluxerr', 'krflag'))
if 'cat' in hdu:
del hdu['cat']
hdu.append(fits.BinTableHDU(tab, name='cat'))
hdu['cat'].header['FWHM'] = fwhm, 'estimated median FWHM'
hdu['cat'].header['RADIUS'] = 2 * fwhm, 'aperture photometry radius'
logger.info(f"{f}: {len(tab)} objects, seeing = {fwhm:.1f}, background mean/rms = "
f"{hdu['bg'].header['bg']:.1f}/{hdu['bg'].header['rms']:.1f}")
|
[
"numpy.ptp",
"sep.kron_radius",
"logging.StreamHandler",
"astropy.table.Table",
"numpy.array",
"sep.Background",
"numpy.isfinite",
"astropy.io.fits.open",
"astropy.modeling.models.Const2D",
"numpy.mean",
"argparse.ArgumentParser",
"numpy.ma.count",
"astropy.modeling.Parameter",
"astropy.wcs.WCS",
"logging.FileHandler",
"numpy.min",
"warnings.simplefilter",
"numpy.indices",
"astropy.modeling.models.Gaussian2D",
"numpy.std",
"matplotlib.patches.Ellipse",
"astropy.stats.sigma_clipped_stats",
"astropy.modeling.fitting.LevMarLSQFitter",
"astropy.io.fits.getheader",
"numpy.minimum",
"logging.Formatter",
"sep.sum_circle",
"sep.extract",
"astropy.io.fits.BinTableHDU",
"datetime.datetime.now",
"photutils.SegmentationImage",
"logging.Logger",
"scipy.ndimage.binary_closing",
"numpy.zeros_like",
"matplotlib.pyplot.subplots"
] |
[((658, 683), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (681, 683), False, 'import argparse\n'), ((4104, 4137), 'logging.Logger', 'logging.Logger', (['"""LMI Add Catalog"""'], {}), "('LMI Add Catalog')\n", (4118, 4137), False, 'import logging\n'), ((4923, 4972), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'FITSFixedWarning'], {}), "('ignore', FITSFixedWarning)\n", (4944, 4972), False, 'import warnings\n'), ((1942, 1962), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (1951, 1962), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((1979, 1999), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (1988, 1999), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2013, 2033), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2022, 2033), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2047, 2067), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2056, 2067), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2083, 2103), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (2092, 2103), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2119, 2139), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (2128, 2139), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2152, 2172), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2161, 2172), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((3596, 3608), 'numpy.ptp', 'np.ptp', (['data'], {}), '(data)\n', (3602, 3608), True, 'import numpy as np\n'), ((3899, 3916), 'astropy.modeling.fitting.LevMarLSQFitter', 'LevMarLSQFitter', ([], {}), '()\n', (3914, 3916), False, 'from astropy.modeling.fitting import LevMarLSQFitter\n'), ((3928, 3950), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (3938, 3950), True, 'import numpy as np\n'), ((4300, 4347), 'logging.Formatter', 'logging.Formatter', (['"""%(levelname)s: %(message)s"""'], {}), "('%(levelname)s: %(message)s')\n", (4317, 4347), False, 'import logging\n'), ((4423, 4456), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (4444, 4456), False, 'import logging\n'), ((4567, 4605), 'logging.FileHandler', 'logging.FileHandler', (['"""lmi-add-cat.log"""'], {}), "('lmi-add-cat.log')\n", (4586, 4605), False, 'import logging\n'), ((5131, 5145), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5143, 5145), True, 'import matplotlib.pyplot as plt\n'), ((2986, 3003), 'numpy.ma.count', 'np.ma.count', (['data'], {}), '(data)\n', (2997, 3003), True, 'import numpy as np\n'), ((3513, 3525), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (3519, 3525), True, 'import numpy as np\n'), ((3549, 3569), 'numpy.array', 'np.array', (['data.shape'], {}), '(data.shape)\n', (3557, 3569), True, 'import numpy as np\n'), ((5157, 5168), 'numpy.mean', 'np.mean', (['im'], {}), '(im)\n', (5164, 5168), True, 'import numpy as np\n'), ((5170, 5180), 'numpy.std', 'np.std', (['im'], {}), '(im)\n', (5176, 5180), True, 'import numpy as np\n'), ((5382, 5530), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': "(objects['x'][i], objects['y'][i])", 'width': "(6 * objects['a'][i])", 'height': "(6 * objects['b'][i])", 'angle': "(objects['theta'][i] * 180.0 / np.pi)"}), "(xy=(objects['x'][i], objects['y'][i]), width=6 * objects['a'][i],\n height=6 * objects['b'][i], angle=objects['theta'][i] * 180.0 / np.pi)\n", (5389, 5530), False, 'from matplotlib.patches import Ellipse\n'), ((5791, 5818), 'astropy.io.fits.open', 'fits.open', (['f'], {'mode': '"""update"""'}), "(f, mode='update')\n", (5800, 5818), False, 'from astropy.io import fits\n'), ((6338, 6357), 'numpy.zeros_like', 'np.zeros_like', (['mask'], {}), '(mask)\n', (6351, 6357), True, 'import numpy as np\n'), ((6657, 6718), 'sep.Background', 'sep.Background', (['im'], {'mask': '(det | mask)', 'bw': '(64)', 'bh': '(64)', 'fw': '(3)', 'fh': '(3)'}), '(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)\n', (6671, 6718), False, 'import sep\n'), ((7470, 7498), 'photutils.SegmentationImage', 'pu.SegmentationImage', (['labels'], {}), '(labels)\n', (7490, 7498), True, 'import photutils as pu\n'), ((8019, 8111), 'sep.sum_circle', 'sep.sum_circle', (['data', "objects['x']", "objects['y']", 'rap'], {'err': 'bkg.globalrms', 'gain': "h['gain']"}), "(data, objects['x'], objects['y'], rap, err=bkg.globalrms,\n gain=h['gain'])\n", (8033, 8111), False, 'import sep\n'), ((8160, 8265), 'sep.kron_radius', 'sep.kron_radius', (['data', "objects['x']", "objects['y']", "objects['a']", "objects['b']", "objects['theta']", '(6.0)'], {}), "(data, objects['x'], objects['y'], objects['a'], objects['b'\n ], objects['theta'], 6.0)\n", (8175, 8265), False, 'import sep\n'), ((8670, 8676), 'astropy.wcs.WCS', 'WCS', (['h'], {}), '(h)\n', (8673, 8676), False, 'from astropy.wcs import WCS\n'), ((8759, 9040), 'astropy.table.Table', 'Table', (["(objects['x'], objects['y'], ra, dec, flux, fluxerr, flag, objects['a'],\n objects['b'], objects['theta'], kronrad, krflux, krfluxerr, krflag)"], {'names': "('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag', 'a', 'b', 'theta',\n 'kronrad', 'krflux', 'krfluxerr', 'krflag')"}), "((objects['x'], objects['y'], ra, dec, flux, fluxerr, flag, objects[\n 'a'], objects['b'], objects['theta'], kronrad, krflux, krfluxerr,\n krflag), names=('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag', 'a',\n 'b', 'theta', 'kronrad', 'krflux', 'krfluxerr', 'krflag'))\n", (8764, 9040), False, 'from astropy.table import Table\n'), ((4736, 4750), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4748, 4750), False, 'from datetime import datetime\n'), ((5700, 5717), 'astropy.io.fits.getheader', 'fits.getheader', (['f'], {}), '(f)\n', (5714, 5717), False, 'from astropy.io import fits\n'), ((6164, 6187), 'numpy.zeros_like', 'np.zeros_like', (['im', 'bool'], {}), '(im, bool)\n', (6177, 6187), True, 'import numpy as np\n'), ((6411, 6472), 'sep.Background', 'sep.Background', (['im'], {'mask': '(det | mask)', 'bw': '(64)', 'bh': '(64)', 'fw': '(3)', 'fh': '(3)'}), '(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)\n', (6425, 6472), False, 'import sep\n'), ((6619, 6641), 'scipy.ndimage.binary_closing', 'nd.binary_closing', (['det'], {}), '(det)\n', (6636, 6641), True, 'import scipy.ndimage as nd\n'), ((7014, 7076), 'sep.extract', 'sep.extract', (['data', '(3)'], {'err': 'bkg.globalrms', 'segmentation_map': '(True)'}), '(data, 3, err=bkg.globalrms, segmentation_map=True)\n', (7025, 7076), False, 'import sep\n'), ((7906, 7932), 'astropy.stats.sigma_clipped_stats', 'sigma_clipped_stats', (['fwhms'], {}), '(fwhms)\n', (7925, 7932), False, 'from astropy.stats import sigma_clipped_stats\n'), ((7962, 7979), 'numpy.isfinite', 'np.isfinite', (['fwhm'], {}), '(fwhm)\n', (7973, 7979), True, 'import numpy as np\n'), ((8483, 8528), 'numpy.minimum', 'np.minimum', (["objects['theta']", '(np.pi / 2.00001)'], {}), "(objects['theta'], np.pi / 2.00001)\n", (8493, 8528), True, 'import numpy as np\n'), ((9215, 9248), 'astropy.io.fits.BinTableHDU', 'fits.BinTableHDU', (['tab'], {'name': '"""cat"""'}), "(tab, name='cat')\n", (9231, 9248), False, 'from astropy.io import fits\n'), ((2377, 2394), 'astropy.modeling.models.Const2D', 'Const2D', (['constant'], {}), '(constant)\n', (2384, 2394), False, 'from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D\n'), ((2403, 2467), 'astropy.modeling.models.Gaussian2D', 'Gaussian2D', (['amplitude', 'x_mean', 'y_mean', 'x_stddev', 'y_stddev', 'theta'], {}), '(amplitude, x_mean, y_mean, x_stddev, y_stddev, theta)\n', (2413, 2467), False, 'from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D\n'), ((7756, 7801), 'numpy.mean', 'np.mean', (['(g.x_stddev.value, g.y_stddev.value)'], {}), '((g.x_stddev.value, g.y_stddev.value))\n', (7763, 7801), True, 'import numpy as np\n')]
|
# Some of the implementation inspired by:
# REF: https://github.com/fchen365/epca
import time
from abc import abstractmethod
import numpy as np
from factor_analyzer import Rotator
from sklearn.base import BaseEstimator
from sklearn.preprocessing import StandardScaler
from sklearn.utils import check_array
from graspologic.embed import selectSVD
from ..utils import calculate_explained_variance_ratio, soft_threshold
from scipy.linalg import orthogonal_procrustes
def _varimax(X):
return Rotator(normalize=False).fit_transform(X)
def _polar(X):
# REF: https://en.wikipedia.org/wiki/Polar_decomposition#Relation_to_the_SVD
U, D, Vt = selectSVD(X, n_components=X.shape[1], algorithm="full")
return U @ Vt
def _polar_rotate_shrink(X, gamma=0.1):
# Algorithm 1 from the paper
U, _, _ = selectSVD(X, n_components=X.shape[1], algorithm="full")
# U = _polar(X)
# R, _ = orthogonal_procrustes(U_old, U)
# print(np.linalg.norm(U_old @ R - U))
U_rot = _varimax(U)
U_thresh = soft_threshold(U_rot, gamma)
return U_thresh
def _reorder_components(X, Z_hat, Y_hat):
score_norms = np.linalg.norm(X @ Y_hat, axis=0)
sort_inds = np.argsort(-score_norms)
return Z_hat[:, sort_inds], Y_hat[:, sort_inds]
# import abc
# class SuperclassMeta(type):
# def __new__(mcls, classname, bases, cls_dict):
# cls = super().__new__(mcls, classname, bases, cls_dict)
# for name, member in cls_dict.items():
# if not getattr(member, "__doc__"):
# member.__doc__ = getattr(bases[-1], name).__doc__
# return cls
class BaseSparseDecomposition(BaseEstimator):
def __init__(
self,
n_components=2,
gamma=None,
max_iter=10,
scale=False,
center=False,
tol=1e-4,
verbose=0,
):
"""Sparse matrix decomposition model.
Parameters
----------
n_components : int, optional (default=2)
Number of components or embedding dimensions.
gamma : float, int or None, optional (default=None)
Sparsity parameter, must be nonnegative. Lower values lead to more sparsity
in the estimated components. If ``None``, will be set to
``sqrt(n_components * X.shape[1])`` where ``X`` is the matrix passed to
``fit``.
max_iter : int, optional (default=10)
Maximum number of iterations allowed, must be nonnegative.
scale : bool, optional
[description], by default False
center : bool, optional
[description], by default False
tol : float or int, optional (default=1e-4)
Tolerance for stopping iterative optimization. If the relative difference in
score is less than this amount the algorithm will terminate.
verbose : int, optional (default=0)
Verbosity level. Higher values will result in more messages.
"""
self.n_components = n_components
self.gamma = gamma
self.max_iter = max_iter
self.scale = scale
self.center = center
self.tol = tol
self.verbose = verbose
# TODO add random state
def _initialize(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
U, D, Vt = selectSVD(X, n_components=self.n_components)
score = np.linalg.norm(D)
return U, Vt.T, score
def _validate_parameters(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
"""
if not self.gamma:
gamma = np.sqrt(self.n_components * X.shape[1])
else:
gamma = self.gamma
self.gamma_ = gamma
def _preprocess_data(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
if self.scale or self.center:
X = StandardScaler(
with_mean=self.center, with_std=self.scale
).fit_transform(X)
return X
# def _compute_matrix_difference(X, metric='max'):
# TODO better convergence criteria
def fit_transform(self, X, y=None):
"""[summary]
Parameters
----------
X : [type]
[description]
y : [type], optional
[description], by default None
Returns
-------
[type]
[description]
"""
self._validate_parameters(X)
self._validate_data(X, copy=True, ensure_2d=True) # from sklearn BaseEstimator
Z_hat, Y_hat, score = self._initialize(X)
if self.gamma == np.inf:
max_iter = 0
else:
max_iter = self.max_iter
# for keeping track of progress over iteration
Z_diff = np.inf
Y_diff = np.inf
norm_score_diff = np.inf
last_score = 0
# main loop
i = 0
while (i < max_iter) and (norm_score_diff > self.tol):
if self.verbose > 0:
print(f"Iteration: {i}")
iter_time = time.time()
Z_hat_new, Y_hat_new = self._update_estimates(X, Z_hat, Y_hat)
# Z_hat_new, Y_hat_new = _reorder_components(X, Z_hat_new, Y_hat_new)
Z_diff = np.linalg.norm(Z_hat_new - Z_hat)
Y_diff = np.linalg.norm(Y_hat_new - Y_hat)
norm_Z_diff = Z_diff / np.linalg.norm(Z_hat_new)
norm_Y_diff = Y_diff / np.linalg.norm(Y_hat_new)
Z_hat = Z_hat_new
Y_hat = Y_hat_new
B_hat = Z_hat.T @ X @ Y_hat
score = np.linalg.norm(B_hat)
norm_score_diff = np.abs(score - last_score) / score
last_score = score
if self.verbose > 1:
print(f"{time.time() - iter_time:.3f} seconds elapsed for iteration.")
if self.verbose > 0:
print(f"Difference in Z_hat: {Z_diff}")
print(f"Difference in Y_hat: {Z_diff}")
print(f"Normalized difference in Z_hat: {norm_Z_diff}")
print(f"Normalized difference in Y_hat: {norm_Y_diff}")
print(f"Total score: {score}")
print(f"Normalized difference in score: {norm_score_diff}")
print()
i += 1
Z_hat, Y_hat = _reorder_components(X, Z_hat, Y_hat)
# save attributes
self.n_iter_ = i
self.components_ = Y_hat.T
# TODO this should not be cumulative by the sklearn definition
self.explained_variance_ratio_ = calculate_explained_variance_ratio(X, Y_hat)
self.score_ = score
return Z_hat
def fit(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
self.fit_transform(X)
return self
def transform(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
# TODO input checking
return X @ self.components_.T
@abstractmethod
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
pass
class SparseComponentAnalysis(BaseSparseDecomposition):
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
Returns
-------
[type]
[description]
"""
Y_hat = _polar_rotate_shrink(X.T @ Z_hat, gamma=self.gamma)
Z_hat = _polar(X @ Y_hat)
return Z_hat, Y_hat
def _save_attributes(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
pass
class SparseMatrixApproximation(BaseSparseDecomposition):
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
Returns
-------
[type]
[description]
"""
Z_hat = _polar_rotate_shrink(X @ Y_hat)
Y_hat = _polar_rotate_shrink(X.T @ Z_hat)
return Z_hat, Y_hat
def _save_attributes(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
B = Z_hat.T @ X @ Y_hat
self.score_ = B
self.right_latent_ = Y_hat
self.left_latent_ = Z_hat
|
[
"factor_analyzer.Rotator",
"numpy.abs",
"numpy.sqrt",
"graspologic.embed.selectSVD",
"numpy.argsort",
"sklearn.preprocessing.StandardScaler",
"numpy.linalg.norm",
"time.time"
] |
[((654, 709), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'X.shape[1]', 'algorithm': '"""full"""'}), "(X, n_components=X.shape[1], algorithm='full')\n", (663, 709), False, 'from graspologic.embed import selectSVD\n'), ((817, 872), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'X.shape[1]', 'algorithm': '"""full"""'}), "(X, n_components=X.shape[1], algorithm='full')\n", (826, 872), False, 'from graspologic.embed import selectSVD\n'), ((1131, 1164), 'numpy.linalg.norm', 'np.linalg.norm', (['(X @ Y_hat)'], {'axis': '(0)'}), '(X @ Y_hat, axis=0)\n', (1145, 1164), True, 'import numpy as np\n'), ((1181, 1205), 'numpy.argsort', 'np.argsort', (['(-score_norms)'], {}), '(-score_norms)\n', (1191, 1205), True, 'import numpy as np\n'), ((3454, 3498), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'self.n_components'}), '(X, n_components=self.n_components)\n', (3463, 3498), False, 'from graspologic.embed import selectSVD\n'), ((3515, 3532), 'numpy.linalg.norm', 'np.linalg.norm', (['D'], {}), '(D)\n', (3529, 3532), True, 'import numpy as np\n'), ((499, 523), 'factor_analyzer.Rotator', 'Rotator', ([], {'normalize': '(False)'}), '(normalize=False)\n', (506, 523), False, 'from factor_analyzer import Rotator\n'), ((3767, 3806), 'numpy.sqrt', 'np.sqrt', (['(self.n_components * X.shape[1])'], {}), '(self.n_components * X.shape[1])\n', (3774, 3806), True, 'import numpy as np\n'), ((5327, 5338), 'time.time', 'time.time', ([], {}), '()\n', (5336, 5338), False, 'import time\n'), ((5519, 5552), 'numpy.linalg.norm', 'np.linalg.norm', (['(Z_hat_new - Z_hat)'], {}), '(Z_hat_new - Z_hat)\n', (5533, 5552), True, 'import numpy as np\n'), ((5574, 5607), 'numpy.linalg.norm', 'np.linalg.norm', (['(Y_hat_new - Y_hat)'], {}), '(Y_hat_new - Y_hat)\n', (5588, 5607), True, 'import numpy as np\n'), ((5852, 5873), 'numpy.linalg.norm', 'np.linalg.norm', (['B_hat'], {}), '(B_hat)\n', (5866, 5873), True, 'import numpy as np\n'), ((5643, 5668), 'numpy.linalg.norm', 'np.linalg.norm', (['Z_hat_new'], {}), '(Z_hat_new)\n', (5657, 5668), True, 'import numpy as np\n'), ((5704, 5729), 'numpy.linalg.norm', 'np.linalg.norm', (['Y_hat_new'], {}), '(Y_hat_new)\n', (5718, 5729), True, 'import numpy as np\n'), ((5904, 5930), 'numpy.abs', 'np.abs', (['(score - last_score)'], {}), '(score - last_score)\n', (5910, 5930), True, 'import numpy as np\n'), ((4161, 4219), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': 'self.center', 'with_std': 'self.scale'}), '(with_mean=self.center, with_std=self.scale)\n', (4175, 4219), False, 'from sklearn.preprocessing import StandardScaler\n'), ((6029, 6040), 'time.time', 'time.time', ([], {}), '()\n', (6038, 6040), False, 'import time\n')]
|
"""
Generate download locations within a country and download them.
Written by <NAME>.
5/2020
"""
import os
import configparser
import math
import pandas as pd
import numpy as np
import random
import geopandas as gpd
from shapely.geometry import Point
import requests
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
from tqdm import tqdm
import logging
import time
BASE_DIR = '.'
# repo imports
import sys
sys.path.append(BASE_DIR)
from utils import PlanetDownloader
from config import VIS_CONFIG, RANDOM_SEED
COUNTRY_ABBRV = VIS_CONFIG['COUNTRY_ABBRV']
COUNTRIES_DIR = os.path.join(BASE_DIR, 'data', 'countries')
GRID_DIR = os.path.join(COUNTRIES_DIR, COUNTRY_ABBRV, 'grid')
IMAGE_DIR = os.path.join(COUNTRIES_DIR, COUNTRY_ABBRV, 'images')
ACCESS_TOKEN_DIR = os.path.join(BASE_DIR, 'planet_api_key.txt')
ACCESS_TOKEN = None
with open(ACCESS_TOKEN_DIR, 'r') as f:
ACCESS_TOKEN = f.readlines()[0]
assert ACCESS_TOKEN is not None, print("Access token is not valid")
def create_folders():
"""
Function to create new folders.
"""
os.makedirs(IMAGE_DIR, exist_ok=True)
def get_polygon_download_locations(polygon, number, seed=7):
"""
Samples NUMBER points evenly but randomly from a polygon. Seed is set for
reproducibility.
At first tries to create sub-grid of size n x n where n = sqrt(number)
It checks these coordinates and if they are in the polygon it uses them
If the number of points found is still less than the desired number,
samples are taken randomly from the polygon until the required number
is achieved.
"""
random.seed(seed)
min_x, min_y, max_x, max_y = polygon.bounds
edge_num = math.floor(math.sqrt(number))
lats = np.linspace(min_y, max_y, edge_num)
lons = np.linspace(min_x, max_x, edge_num)
# performs cartesian product
evenly_spaced_points = np.transpose(
[np.tile(lats, len(lons)), np.repeat(lons, len(lats))])
assert len(evenly_spaced_points) <= number
# tries using evenly spaced points
points = []
for proposed_lat, proposed_lon in evenly_spaced_points:
point = Point(proposed_lon, proposed_lat)
if polygon.contains(point):
points.append([proposed_lat, proposed_lon])
# fills the remainder with random points
while len(points) < number:
point = Point(random.uniform(min_x, max_x),
random.uniform(min_y, max_y))
if polygon.contains(point):
points.append([point.y, point.x])
return points # returns list of lat/lon pairs
def generate_country_download_locations(min_population=100, num_per_grid=4):
"""
Generates a defined number of download locations (NUM_PER_GRID) for each
grid with at least the minimum number of specified residents (MIN_
POPULATION).
"""
grid = gpd.read_file(os.path.join(GRID_DIR, 'grid.shp'))
grid = grid[grid['population'] >= min_population]
lat_lon_pairs = grid['geometry'].apply(
lambda polygon: get_polygon_download_locations(
polygon, number=num_per_grid))
centroids = grid['geometry'].centroid
columns = [
'centroid_lat', 'centroid_lon', 'image_lat', 'image_lon', 'image_name'
]
with open(os.path.join(GRID_DIR, 'image_download_locs.csv'), 'w') as f:
f.write(','.join(columns) + '\n')
for lat_lons, centroid in zip(lat_lon_pairs, centroids):
for lat, lon in lat_lons:
name = str(lat) + '_' + str(lon) + '.png'
to_write = [
str(centroid.y), str(centroid.x), str(lat), str(lon), name]
f.write(','.join(to_write) + '\n')
print('Generated image download locations and saved at {}'.format(
os.path.join(GRID_DIR, 'image_download_locs.csv')))
def download_images(df):
"""
Download images using a pandas DataFrame that has "image_lat", "image_lon",
"image_name" as columns.
"""
imd = PlanetDownloader(ACCESS_TOKEN)
zoom = 16
NUM_RETRIES = 20
WAIT_TIME = 0.1 # seconds
# drops what is already downloaded
already_downloaded = os.listdir(IMAGE_DIR)
print('Already downloaded ' + str(len(already_downloaded)))
df = df.set_index('image_name').drop(already_downloaded).reset_index()
print('Need to download ' + str(len(df)))
# use three years of images to find one that matches search critera
min_year = 2014
min_month = 1
max_year = 2016
max_month = 12
for _, r in tqdm(df.iterrows(), total=df.shape[0]):
lat = r.image_lat
lon = r.image_lon
name = r.image_name
try:
im = imd.download_image(lat, lon, min_year, min_month, max_year, max_month)
if im is None:
resolved = False
for _ in range(num_retries):
time.sleep(wait_time)
im = imd.download_image(lat, lon, min_year, min_month, max_year, max_month)
if im is None:
continue
else:
plt.imsave(image_save_path, im)
resolved = True
break
if not resolved:
# print(f'Could not download {lat}, {lon} despite several retries and waiting')
continue
else:
pass
else:
# no issues, save according to naming convention
plt.imsave(os.path.join(IMAGE_DIR, name), im)
except Exception as e:
# logging.error(f"Error-could not download {lat}, {lon}", exc_info=True)
continue
return
if __name__ == '__main__':
create_folders()
arg = '--all'
if len(sys.argv) >= 2:
arg = sys.argv[1]
assert arg in ['--all', '--generate-download-locations', '--download-images']
if arg == '--all':
print('Generating download locations...')
generate_country_download_locations()
df_download = pd.read_csv(os.path.join(GRID_DIR, 'image_download_locs.csv'))
print('Downloading images. Might take a while...')
download_images(df_download)
elif arg == '--generate-download-locations':
print('Generating download locations...')
generate_country_download_locations()
elif arg == '--download-images':
df_download = pd.read_csv(os.path.join(GRID_DIR, 'image_download_locs.csv'))
print('Downloading images. Might take a while...')
download_images(df_download)
else:
raise ValueError('Args not handled correctly')
|
[
"random.uniform",
"os.listdir",
"os.makedirs",
"matplotlib.pyplot.imsave",
"os.path.join",
"math.sqrt",
"random.seed",
"shapely.geometry.Point",
"time.sleep",
"numpy.linspace",
"utils.PlanetDownloader",
"sys.path.append"
] |
[((437, 462), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (452, 462), False, 'import sys\n'), ((602, 645), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""data"""', '"""countries"""'], {}), "(BASE_DIR, 'data', 'countries')\n", (614, 645), False, 'import os\n'), ((657, 707), 'os.path.join', 'os.path.join', (['COUNTRIES_DIR', 'COUNTRY_ABBRV', '"""grid"""'], {}), "(COUNTRIES_DIR, COUNTRY_ABBRV, 'grid')\n", (669, 707), False, 'import os\n'), ((720, 772), 'os.path.join', 'os.path.join', (['COUNTRIES_DIR', 'COUNTRY_ABBRV', '"""images"""'], {}), "(COUNTRIES_DIR, COUNTRY_ABBRV, 'images')\n", (732, 772), False, 'import os\n'), ((793, 837), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""planet_api_key.txt"""'], {}), "(BASE_DIR, 'planet_api_key.txt')\n", (805, 837), False, 'import os\n'), ((1081, 1118), 'os.makedirs', 'os.makedirs', (['IMAGE_DIR'], {'exist_ok': '(True)'}), '(IMAGE_DIR, exist_ok=True)\n', (1092, 1118), False, 'import os\n'), ((1618, 1635), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1629, 1635), False, 'import random\n'), ((1741, 1776), 'numpy.linspace', 'np.linspace', (['min_y', 'max_y', 'edge_num'], {}), '(min_y, max_y, edge_num)\n', (1752, 1776), True, 'import numpy as np\n'), ((1788, 1823), 'numpy.linspace', 'np.linspace', (['min_x', 'max_x', 'edge_num'], {}), '(min_x, max_x, edge_num)\n', (1799, 1823), True, 'import numpy as np\n'), ((3975, 4005), 'utils.PlanetDownloader', 'PlanetDownloader', (['ACCESS_TOKEN'], {}), '(ACCESS_TOKEN)\n', (3991, 4005), False, 'from utils import PlanetDownloader\n'), ((4136, 4157), 'os.listdir', 'os.listdir', (['IMAGE_DIR'], {}), '(IMAGE_DIR)\n', (4146, 4157), False, 'import os\n'), ((1711, 1728), 'math.sqrt', 'math.sqrt', (['number'], {}), '(number)\n', (1720, 1728), False, 'import math\n'), ((2142, 2175), 'shapely.geometry.Point', 'Point', (['proposed_lon', 'proposed_lat'], {}), '(proposed_lon, proposed_lat)\n', (2147, 2175), False, 'from shapely.geometry import Point\n'), ((2861, 2895), 'os.path.join', 'os.path.join', (['GRID_DIR', '"""grid.shp"""'], {}), "(GRID_DIR, 'grid.shp')\n", (2873, 2895), False, 'import os\n'), ((2369, 2397), 'random.uniform', 'random.uniform', (['min_x', 'max_x'], {}), '(min_x, max_x)\n', (2383, 2397), False, 'import random\n'), ((2411, 2439), 'random.uniform', 'random.uniform', (['min_y', 'max_y'], {}), '(min_y, max_y)\n', (2425, 2439), False, 'import random\n'), ((3255, 3304), 'os.path.join', 'os.path.join', (['GRID_DIR', '"""image_download_locs.csv"""'], {}), "(GRID_DIR, 'image_download_locs.csv')\n", (3267, 3304), False, 'import os\n'), ((3761, 3810), 'os.path.join', 'os.path.join', (['GRID_DIR', '"""image_download_locs.csv"""'], {}), "(GRID_DIR, 'image_download_locs.csv')\n", (3773, 3810), False, 'import os\n'), ((6061, 6110), 'os.path.join', 'os.path.join', (['GRID_DIR', '"""image_download_locs.csv"""'], {}), "(GRID_DIR, 'image_download_locs.csv')\n", (6073, 6110), False, 'import os\n'), ((4857, 4878), 'time.sleep', 'time.sleep', (['wait_time'], {}), '(wait_time)\n', (4867, 4878), False, 'import time\n'), ((5514, 5543), 'os.path.join', 'os.path.join', (['IMAGE_DIR', 'name'], {}), '(IMAGE_DIR, name)\n', (5526, 5543), False, 'import os\n'), ((6427, 6476), 'os.path.join', 'os.path.join', (['GRID_DIR', '"""image_download_locs.csv"""'], {}), "(GRID_DIR, 'image_download_locs.csv')\n", (6439, 6476), False, 'import os\n'), ((5093, 5124), 'matplotlib.pyplot.imsave', 'plt.imsave', (['image_save_path', 'im'], {}), '(image_save_path, im)\n', (5103, 5124), True, 'import matplotlib.pyplot as plt\n')]
|
# -*- coding: utf-8 -*-
""" The Neural Network classifier for IRIS. """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import urllib
import numpy as np
import tensorflow as tf
# Data sets
IRIS_TRAINING = "IRIS_data/iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"
IRIS_TEST = "IRIS_data/iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
def main():
# If the training and test sets aren't stored locally, download them.
if not os.path.exists(IRIS_TRAINING):
raw = urllib.request.urlopen(IRIS_TRAINING_URL).read().decode()
with open(IRIS_TRAINING, "w") as f:
f.write(raw)
if not os.path.exists(IRIS_TEST):
raw = urllib.request.urlopen(IRIS_TEST_URL).read().decode()
with open(IRIS_TEST, "w") as f:
f.write(raw)
# Load datasets
training_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TRAINING,
target_dtype=np.int,
features_dtype=np.float)
test_set = tf.contrib.learn.datasets.base.load_csv_with_header(
filename=IRIS_TEST,
target_dtype=np.int,
features_dtype=np.float)
# Specify that all features have real-value data
feature_columns = [tf.feature_column.numeric_column("x", shape=[4])]
# Build 3 layers DNN with 10,20,10 units respectively
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[10,20,10],
n_classes=3,
model_dir="IRIS/iris_model")
# Define the training inputs
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(training_set.data)},
y=np.array(training_set.target),
num_epochs=None,
shuffle=True
)
# Train model
classifier.train(input_fn=train_input_fn, steps=2000)
# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": np.array(test_set.data)},
y=np.array(test_set.target),
num_epochs=1,
shuffle=False
)
# Evaluate accuracy
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
# Classify two new flower samples.
new_samples = np.array(
[[6.4, 3.2, 4.5, 1.5],
[5.8, 3.1, 5.0, 1.7]], dtype=np.float
)
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
x={"x": new_samples},
num_epochs=1,
shuffle=False
)
predictions = list(classifier.predict(input_fn=predict_input_fn))
predicted_classes = [p["classes"] for p in predictions]
print(
"New samples, Class Predictions: {}\n"
.format(predicted_classes)
)
if __name__ == "__main__":
main()
|
[
"os.path.exists",
"tensorflow.estimator.DNNClassifier",
"tensorflow.contrib.learn.datasets.base.load_csv_with_header",
"tensorflow.estimator.inputs.numpy_input_fn",
"tensorflow.feature_column.numeric_column",
"numpy.array",
"urllib.request.urlopen"
] |
[((982, 1107), 'tensorflow.contrib.learn.datasets.base.load_csv_with_header', 'tf.contrib.learn.datasets.base.load_csv_with_header', ([], {'filename': 'IRIS_TRAINING', 'target_dtype': 'np.int', 'features_dtype': 'np.float'}), '(filename=IRIS_TRAINING,\n target_dtype=np.int, features_dtype=np.float)\n', (1033, 1107), True, 'import tensorflow as tf\n'), ((1144, 1265), 'tensorflow.contrib.learn.datasets.base.load_csv_with_header', 'tf.contrib.learn.datasets.base.load_csv_with_header', ([], {'filename': 'IRIS_TEST', 'target_dtype': 'np.int', 'features_dtype': 'np.float'}), '(filename=IRIS_TEST,\n target_dtype=np.int, features_dtype=np.float)\n', (1195, 1265), True, 'import tensorflow as tf\n'), ((1490, 1623), 'tensorflow.estimator.DNNClassifier', 'tf.estimator.DNNClassifier', ([], {'feature_columns': 'feature_columns', 'hidden_units': '[10, 20, 10]', 'n_classes': '(3)', 'model_dir': '"""IRIS/iris_model"""'}), "(feature_columns=feature_columns, hidden_units=[\n 10, 20, 10], n_classes=3, model_dir='IRIS/iris_model')\n", (1516, 1623), True, 'import tensorflow as tf\n'), ((2492, 2562), 'numpy.array', 'np.array', (['[[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]]'], {'dtype': 'np.float'}), '([[6.4, 3.2, 4.5, 1.5], [5.8, 3.1, 5.0, 1.7]], dtype=np.float)\n', (2500, 2562), True, 'import numpy as np\n'), ((2608, 2697), 'tensorflow.estimator.inputs.numpy_input_fn', 'tf.estimator.inputs.numpy_input_fn', ([], {'x': "{'x': new_samples}", 'num_epochs': '(1)', 'shuffle': '(False)'}), "(x={'x': new_samples}, num_epochs=1,\n shuffle=False)\n", (2642, 2697), True, 'import tensorflow as tf\n'), ((590, 619), 'os.path.exists', 'os.path.exists', (['IRIS_TRAINING'], {}), '(IRIS_TRAINING)\n', (604, 619), False, 'import os\n'), ((778, 803), 'os.path.exists', 'os.path.exists', (['IRIS_TEST'], {}), '(IRIS_TEST)\n', (792, 803), False, 'import os\n'), ((1364, 1412), 'tensorflow.feature_column.numeric_column', 'tf.feature_column.numeric_column', (['"""x"""'], {'shape': '[4]'}), "('x', shape=[4])\n", (1396, 1412), True, 'import tensorflow as tf\n'), ((1895, 1924), 'numpy.array', 'np.array', (['training_set.target'], {}), '(training_set.target)\n', (1903, 1924), True, 'import numpy as np\n'), ((2193, 2218), 'numpy.array', 'np.array', (['test_set.target'], {}), '(test_set.target)\n', (2201, 2218), True, 'import numpy as np\n'), ((1855, 1882), 'numpy.array', 'np.array', (['training_set.data'], {}), '(training_set.data)\n', (1863, 1882), True, 'import numpy as np\n'), ((2157, 2180), 'numpy.array', 'np.array', (['test_set.data'], {}), '(test_set.data)\n', (2165, 2180), True, 'import numpy as np\n'), ((635, 676), 'urllib.request.urlopen', 'urllib.request.urlopen', (['IRIS_TRAINING_URL'], {}), '(IRIS_TRAINING_URL)\n', (657, 676), False, 'import urllib\n'), ((819, 856), 'urllib.request.urlopen', 'urllib.request.urlopen', (['IRIS_TEST_URL'], {}), '(IRIS_TEST_URL)\n', (841, 856), False, 'import urllib\n')]
|
#!/usr/bin/env python
"""
nearest_cloud.py - Version 1.0 2013-07-28
Compute the COG of the nearest object in x-y-z space and publish as a PoseStamped message.
Relies on PCL ROS nodelets in the launch file to pre-filter the
cloud on the x, y and z dimensions.
Based on the follower application by <NAME> at:
http://ros.org/wiki/turtlebot_follower
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2013 <NAME>. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details at:
http://www.gnu.org/licenses/gpl.html
"""
import rospy
from roslib import message
from sensor_msgs.msg import PointCloud2
from sensor_msgs import point_cloud2
from geometry_msgs.msg import Point, PoseStamped, Quaternion
from tf.transformations import quaternion_from_euler
import numpy as np
import cv2
from math import pi, radians
class NearestCloud():
def __init__(self):
rospy.init_node("nearest_cloud")
self.min_points = rospy.get_param("~min_points", 25)
self.z_percentile = rospy.get_param("~z_percentile", 100)
# Define the target publisher
self.target_pub = rospy.Publisher('target_pose', PoseStamped)
rospy.Subscriber('point_cloud', PointCloud2, self.get_nearest_cloud)
# Wait for the pointcloud topic to become available
rospy.wait_for_message('point_cloud', PointCloud2)
def get_nearest_cloud(self, msg):
points = list()
points_xy = list()
# Get all the points in the visible cloud (may be prefiltered by other nodes)
for point in point_cloud2.read_points(msg, skip_nans=True):
points.append(point[:3])
points_xy.append(point[:2])
# Convert to a numpy array
points_arr = np.float32([p for p in points]).reshape(-1, 1, 3)
# Compute the COG
cog = np.mean(points_arr, 0)
# Convert to a Point
cog_point = Point()
cog_point.x = cog[0][0]
cog_point.y = cog[0][1]
cog_point.z = cog[0][2]
#cog_point.z = 0.35
# Abort if we get an NaN in any component
if np.isnan(np.sum(cog)):
return
# If we have enough points, find the best fit ellipse around them
try:
if len(points_xy) > 6:
points_xy_arr = np.float32([p for p in points_xy]).reshape(-1, 1, 2)
track_box = cv2.fitEllipse(points_xy_arr)
else:
# Otherwise, find the best fitting rectangle
track_box = cv2.boundingRect(points_xy_arr)
angle = pi - radians(track_box[2])
except:
return
#print angle
# Convert the rotation angle to a quaternion
q_angle = quaternion_from_euler(0, angle, 0, axes='sxyz')
q = Quaternion(*q_angle)
q.x = 0.707
q.y = 0
q.z = 0.707
q.w = 0
# Publish the COG and orientation
target = PoseStamped()
target.header.stamp = rospy.Time.now()
target.header.frame_id = msg.header.frame_id
target.pose.position = cog_point
target.pose.orientation = q
# Publish the movement command
self.target_pub.publish(target)
if __name__ == '__main__':
try:
NearestCloud()
rospy.spin()
except rospy.ROSInterruptException:
rospy.loginfo("Nearest cloud node terminated.")
|
[
"rospy.init_node",
"cv2.fitEllipse",
"sensor_msgs.point_cloud2.read_points",
"numpy.mean",
"geometry_msgs.msg.Quaternion",
"rospy.spin",
"rospy.Subscriber",
"rospy.get_param",
"math.radians",
"rospy.Time.now",
"geometry_msgs.msg.Point",
"rospy.Publisher",
"rospy.loginfo",
"rospy.wait_for_message",
"numpy.sum",
"tf.transformations.quaternion_from_euler",
"geometry_msgs.msg.PoseStamped",
"numpy.float32",
"cv2.boundingRect"
] |
[((1422, 1454), 'rospy.init_node', 'rospy.init_node', (['"""nearest_cloud"""'], {}), "('nearest_cloud')\n", (1437, 1454), False, 'import rospy\n'), ((1490, 1524), 'rospy.get_param', 'rospy.get_param', (['"""~min_points"""', '(25)'], {}), "('~min_points', 25)\n", (1505, 1524), False, 'import rospy\n'), ((1553, 1590), 'rospy.get_param', 'rospy.get_param', (['"""~z_percentile"""', '(100)'], {}), "('~z_percentile', 100)\n", (1568, 1590), False, 'import rospy\n'), ((1657, 1700), 'rospy.Publisher', 'rospy.Publisher', (['"""target_pose"""', 'PoseStamped'], {}), "('target_pose', PoseStamped)\n", (1672, 1700), False, 'import rospy\n'), ((1718, 1786), 'rospy.Subscriber', 'rospy.Subscriber', (['"""point_cloud"""', 'PointCloud2', 'self.get_nearest_cloud'], {}), "('point_cloud', PointCloud2, self.get_nearest_cloud)\n", (1734, 1786), False, 'import rospy\n'), ((1864, 1914), 'rospy.wait_for_message', 'rospy.wait_for_message', (['"""point_cloud"""', 'PointCloud2'], {}), "('point_cloud', PointCloud2)\n", (1886, 1914), False, 'import rospy\n'), ((2129, 2174), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['msg'], {'skip_nans': '(True)'}), '(msg, skip_nans=True)\n', (2153, 2174), False, 'from sensor_msgs import point_cloud2\n'), ((2423, 2445), 'numpy.mean', 'np.mean', (['points_arr', '(0)'], {}), '(points_arr, 0)\n', (2430, 2445), True, 'import numpy as np\n'), ((2504, 2511), 'geometry_msgs.msg.Point', 'Point', ([], {}), '()\n', (2509, 2511), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((3368, 3415), 'tf.transformations.quaternion_from_euler', 'quaternion_from_euler', (['(0)', 'angle', '(0)'], {'axes': '"""sxyz"""'}), "(0, angle, 0, axes='sxyz')\n", (3389, 3415), False, 'from tf.transformations import quaternion_from_euler\n'), ((3428, 3448), 'geometry_msgs.msg.Quaternion', 'Quaternion', (['*q_angle'], {}), '(*q_angle)\n', (3438, 3448), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((3590, 3603), 'geometry_msgs.msg.PoseStamped', 'PoseStamped', ([], {}), '()\n', (3601, 3603), False, 'from geometry_msgs.msg import Point, PoseStamped, Quaternion\n'), ((3634, 3650), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (3648, 3650), False, 'import rospy\n'), ((3968, 3980), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (3978, 3980), False, 'import rospy\n'), ((2715, 2726), 'numpy.sum', 'np.sum', (['cog'], {}), '(cog)\n', (2721, 2726), True, 'import numpy as np\n'), ((4029, 4076), 'rospy.loginfo', 'rospy.loginfo', (['"""Nearest cloud node terminated."""'], {}), "('Nearest cloud node terminated.')\n", (4042, 4076), False, 'import rospy\n'), ((2322, 2353), 'numpy.float32', 'np.float32', (['[p for p in points]'], {}), '([p for p in points])\n', (2332, 2353), True, 'import numpy as np\n'), ((2994, 3023), 'cv2.fitEllipse', 'cv2.fitEllipse', (['points_xy_arr'], {}), '(points_xy_arr)\n', (3008, 3023), False, 'import cv2\n'), ((3131, 3162), 'cv2.boundingRect', 'cv2.boundingRect', (['points_xy_arr'], {}), '(points_xy_arr)\n', (3147, 3162), False, 'import cv2\n'), ((3201, 3222), 'math.radians', 'radians', (['track_box[2]'], {}), '(track_box[2])\n', (3208, 3222), False, 'from math import pi, radians\n'), ((2911, 2945), 'numpy.float32', 'np.float32', (['[p for p in points_xy]'], {}), '([p for p in points_xy])\n', (2921, 2945), True, 'import numpy as np\n')]
|
import torch
from data import get_diff
import editdistance
import re
from data import chars
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import matplotlib.pyplot as plt
from matplotlib import pylab
import numpy as np
char_to_idx = {ch: i for i, ch in enumerate(chars)}
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(0) # for reproducibility
torch.backends.cudnn.deterministic = True # for reproducibility
torch.backends.cudnn.benchmark = False
def bashRun(args):
"""
When bash running, convert string arguments to an appropriate type.
"""
if type(args.lr) is str:
args.lr = float(args.lr)
if type(args.gru_lr_down) is str:
args.gru_lr_down = float(args.gru_lr_down)
if type(args.step_lr) is str:
args.step_lr = float(args.step_lr)
if type(args.seed) is str:
args.seed = int(args.seed)
if type(args.test_seed) is str:
args.test_seed = int(args.test_seed)
if type(args.epoch) is str:
args.epoch = int(args.epoch)
if type(args.case) is str:
args.case = int(args.case)
if type(args.nhid) is str:
args.nhid = int(args.nhid)
if type(args.nhead) is str:
args.nhead = int(args.nhead)
if type(args.nlayers) is str:
args.nlayers = int(args.nlayers)
if type(args.batch_size) is str:
args.batch_size = int(args.batch_size)
if str(args.excessive_output) == 'True':
args.excessive_output = True
else:
args.excessive_output = False
if str(args.intermediate_loss) == 'True':
args.intermediate_loss = True
else:
args.intermediate_loss = False
if str(args.augment) == 'True':
args.augment = True
else:
args.augment = False
if str(args.multi_gpu) == 'True':
args.multi_gpu = True
else:
args.multi_gpu = False
return args
def evaluate(dataloader, predictor, criterion, args, state='val', pretrained=None, print_result=False):
"""
compute and print loss and accuracy
If long_term or semantic, print (input, prediction, label) pair.
"""
if pretrained is not None:
predictor.load_state_dict(pretrained.state_dict())
predictor.eval()
total = 0.0
correct = 0
step = 0
total_loss = 0.
accuracy = 0
semantic = True
with torch.no_grad():
for x_batch, y_batch, input_len in dataloader:
step += 1
x_batch = x_batch.to(device)
y_batch = y_batch.to(device)
if args.sa_ncd:
output_stat, output, all_hidden_states = predictor(x_batch, input_len)
else:
output = predictor(x_batch, input_len)
if args.ikeyboard:
loss = criterion(output[1].permute(0, 2, 1), y_batch)
loss += criterion(output[0].permute(0, 2, 1), y_batch)
_, top_k = torch.topk(output[1].permute(0, 2, 1), 3, dim=1)
top1_predicted = top_k[:, 0, :]
top2_predicted = top_k[:, 1, :]
top3_predicted = top_k[:, 2, :]
else:
loss = criterion(output, y_batch)
_, top_k = torch.topk(output, 3, dim=1)
top1_predicted = top_k[:, 0, :]
top2_predicted = top_k[:, 1, :]
top3_predicted = top_k[:, 2, :]
if args.various_length:
total += sum(input_len)
correct_packed = pack_padded_sequence(top1_predicted == y_batch, input_len, batch_first=True,
enforce_sorted=False)
correct += correct_packed.data.sum()
else:
pass
accuracy = 100 * correct / total
total_loss += loss
avg_loss = total_loss / step
if print_result:
if semantic:
if len(x_batch.size()) == 3:
print("Input typo:" + idx2chars(x_batch[0, :, 0].long()))
else:
print("Input typo:" + idx2chars(x_batch[0, :].long()))
pred_idx = top1_predicted[0]
label = y_batch[0]
print("original sentence:" + idx2chars(label))
print("top1_predicted sentence:" + idx2chars(pred_idx))
print("top2_predicted sentence:" + idx2chars(top2_predicted[0]))
print("top3_predicted sentence:" + idx2chars(top3_predicted[0]) + '\n')
if print_result:
print('Accuracy on the ' + state + ' data: {:2.2f} % \n'.format(accuracy))
return avg_loss, accuracy
def three_hot_encoder(output, cls=False):
# output : [batch_size, vocab_size, length]
if cls:
output = output[:, :, 1:]
else:
output = output
zero_tensor = torch.zeros(output.shape)
_, topk = torch.topk(output, 3, dim=1)
top1_predicted = topk[:, 0, :]
top2_predicted = topk[:, 1, :]
top3_predicted = topk[:, 2, :]
one_hot1 = (torch.arange(output.shape[1]) == top1_predicted[..., None]).long()
one_hot2 = (torch.arange(output.shape[1]) == top2_predicted[..., None]).long()
one_hot3 = (torch.arange(output.shape[1]) == top3_predicted[..., None]).long()
return one_hot1 + one_hot2 + one_hot3
def save_model(state_dict_model, path):
torch.save(state_dict_model, path, _use_new_zipfile_serialization=False)
def load_model(init_model, path, evaluate_mode=False):
if torch.cuda.is_available():
init_model.load_state_dict(torch.load(path))
else:
init_model.load_state_dict(torch.load(path, map_location=torch.device('cpu')))
if evaluate_mode:
init_model.eval()
return init_model
def idx2chars(indices):
'''
chars_from_indices = ''
for idx in indices:
chars_from_indices = chars_from_indices + chars[idx]
'''
chars_from_indices = ''.join([chars[ind] for ind in indices])
return chars_from_indices
def remove_non_silence_noises(input_text):
"""
Removes non_silence noises from a transcript
"""
non_silence_noises = ["noise", "um", "ah", "er", "umm", "uh", "mm", "mn", "mhm", "mnh", "<START>", "<END>"]
re_non_silence_noises = re.compile(r"\b({})\b".format("|".join(non_silence_noises)))
return re.sub(re_non_silence_noises, '', input_text)
def wer(ref, hyp, remove_nsns=False):
"""
Calculate word error rate between two string or time_aligned_text objects
>>> wer("this is a cat", "this is a dog")
25.0
"""
# remove tagged noises
# ref = re.sub(re_tagged_noises, ' ', ref)
# hyp = re.sub(re_tagged_noises, ' ', hyp)
ref = re.sub('^<START>|<EOS>$', '', ref)
hyp = re.sub('^<START>|<EOS>$', '', hyp)
# optionally, remove non silence noises
if remove_nsns:
ref = remove_non_silence_noises(ref)
hyp = remove_non_silence_noises(hyp)
# clean punctuation, etc.
# ref = clean_up(ref)
# hyp = clean_up(hyp)
# calculate WER
return editdistance.eval(ref.split(' '), hyp.split(' ')), len(ref.split(' '))
def cer(ref, hyp, remove_nsns=False):
"""
Calculate character error rate between two strings or time_aligned_text objects
>>> cer("this cat", "this bad")
25.0
"""
ref = re.sub('^<START>|<EOS>$', '', ref)
hyp = re.sub('^<START>|<EOS>$', '', hyp)
if remove_nsns:
ref = remove_non_silence_noises(ref)
hyp = remove_non_silence_noises(hyp)
# ref = clean_up(ref)
# hyp = clean_up(hyp)
# calculate per line CER
return editdistance.eval(ref, hyp), len(ref)
def test_plot(x_batch, label, save_path):
x_dic = {}
y_dic = {}
width = x_batch[0, 0, 3]
height = x_batch[0, 0, 4]
for i, char in enumerate(idx2chars(label)):
x_value = float(x_batch[0][i][1] * width * 100)
y_value = -float(x_batch[0][i][2] * height * 100)
x_dic.setdefault(char, []).append(x_value)
y_dic.setdefault(char, []).append(y_value)
# Plot all points per name
fig, ax = plt.subplots()
##only the mean points
# for c in x_dic.keys():
# plt.scatter(np.mean(x_dic[c]), np.mean(y_dic[c]), s=10)
# pylab.ylim([-100, 550])
#
# for char in x_dic.keys():
# ax.annotate(char, (np.mean(x_dic[char]), np.mean(y_dic[char])), xytext=(np.mean(x_dic[char]) + 10,
# np.mean(y_dic[char]) + 10))
# ax.text(500, 1, 'user analysis', verticalalignment='bottom', horizontalalignment='right', color='green', fontsize=15)
# for all the points
for c in x_dic.keys():
plt.scatter(x_dic[c], y_dic[c], s=2)
# pylab.ylim([-100, 550])
for d in x_dic.keys():
plt.scatter(np.mean(x_dic[d]), np.mean(y_dic[d]), s=10, c='black')
for char in x_dic.keys():
# ax.annotate(char, (np.mean(x_dic[char]), np.mean(y_dic[char])), xytext=(np.mean(x_dic[char]) + 10, \
# np.mean(y_dic[char]) + 10))
plt.text(np.mean(x_dic[char]) + 5, np.mean(y_dic[char]) + 5, char, weight='bold')
# ax.text(900, -50, 'user analysis', verticalalignment='bottom', horizontalalignment='right', color='green', fontsize=15)
# plt.legend(loc='best')
fig.savefig(save_path)
plt.show()
plt.close(fig)
if __name__ == "__main__":
distance, length = wer('I am a boy but you are a girl.', 'I as d d s a a asdfg fga sd you are s girl.', True)
print(distance)
print(length)
|
[
"torch.manual_seed",
"numpy.mean",
"torch.device",
"torch.topk",
"torch.load",
"matplotlib.pyplot.close",
"torch.no_grad",
"torch.cuda.is_available",
"matplotlib.pyplot.subplots",
"torch.save",
"matplotlib.pyplot.scatter",
"torch.nn.utils.rnn.pack_padded_sequence",
"re.sub",
"editdistance.eval",
"torch.zeros",
"torch.arange",
"matplotlib.pyplot.show"
] |
[((371, 391), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (388, 391), False, 'import torch\n'), ((4898, 4923), 'torch.zeros', 'torch.zeros', (['output.shape'], {}), '(output.shape)\n', (4909, 4923), False, 'import torch\n'), ((4939, 4967), 'torch.topk', 'torch.topk', (['output', '(3)'], {'dim': '(1)'}), '(output, 3, dim=1)\n', (4949, 4967), False, 'import torch\n'), ((5412, 5484), 'torch.save', 'torch.save', (['state_dict_model', 'path'], {'_use_new_zipfile_serialization': '(False)'}), '(state_dict_model, path, _use_new_zipfile_serialization=False)\n', (5422, 5484), False, 'import torch\n'), ((5549, 5574), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5572, 5574), False, 'import torch\n'), ((6372, 6417), 're.sub', 're.sub', (['re_non_silence_noises', '""""""', 'input_text'], {}), "(re_non_silence_noises, '', input_text)\n", (6378, 6417), False, 'import re\n'), ((6744, 6778), 're.sub', 're.sub', (['"""^<START>|<EOS>$"""', '""""""', 'ref'], {}), "('^<START>|<EOS>$', '', ref)\n", (6750, 6778), False, 'import re\n'), ((6789, 6823), 're.sub', 're.sub', (['"""^<START>|<EOS>$"""', '""""""', 'hyp'], {}), "('^<START>|<EOS>$', '', hyp)\n", (6795, 6823), False, 'import re\n'), ((7366, 7400), 're.sub', 're.sub', (['"""^<START>|<EOS>$"""', '""""""', 'ref'], {}), "('^<START>|<EOS>$', '', ref)\n", (7372, 7400), False, 'import re\n'), ((7411, 7445), 're.sub', 're.sub', (['"""^<START>|<EOS>$"""', '""""""', 'hyp'], {}), "('^<START>|<EOS>$', '', hyp)\n", (7417, 7445), False, 'import re\n'), ((8133, 8147), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (8145, 8147), True, 'import matplotlib.pyplot as plt\n'), ((9452, 9462), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9460, 9462), True, 'import matplotlib.pyplot as plt\n'), ((9467, 9481), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (9476, 9481), True, 'import matplotlib.pyplot as plt\n'), ((331, 356), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (354, 356), False, 'import torch\n'), ((2423, 2438), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2436, 2438), False, 'import torch\n'), ((7651, 7678), 'editdistance.eval', 'editdistance.eval', (['ref', 'hyp'], {}), '(ref, hyp)\n', (7668, 7678), False, 'import editdistance\n'), ((8748, 8784), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_dic[c]', 'y_dic[c]'], {'s': '(2)'}), '(x_dic[c], y_dic[c], s=2)\n', (8759, 8784), True, 'import matplotlib.pyplot as plt\n'), ((5611, 5627), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (5621, 5627), False, 'import torch\n'), ((8867, 8884), 'numpy.mean', 'np.mean', (['x_dic[d]'], {}), '(x_dic[d])\n', (8874, 8884), True, 'import numpy as np\n'), ((8886, 8903), 'numpy.mean', 'np.mean', (['y_dic[d]'], {}), '(y_dic[d])\n', (8893, 8903), True, 'import numpy as np\n'), ((3274, 3302), 'torch.topk', 'torch.topk', (['output', '(3)'], {'dim': '(1)'}), '(output, 3, dim=1)\n', (3284, 3302), False, 'import torch\n'), ((3557, 3659), 'torch.nn.utils.rnn.pack_padded_sequence', 'pack_padded_sequence', (['(top1_predicted == y_batch)', 'input_len'], {'batch_first': '(True)', 'enforce_sorted': '(False)'}), '(top1_predicted == y_batch, input_len, batch_first=True,\n enforce_sorted=False)\n', (3577, 3659), False, 'from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n'), ((5090, 5119), 'torch.arange', 'torch.arange', (['output.shape[1]'], {}), '(output.shape[1])\n', (5102, 5119), False, 'import torch\n'), ((5173, 5202), 'torch.arange', 'torch.arange', (['output.shape[1]'], {}), '(output.shape[1])\n', (5185, 5202), False, 'import torch\n'), ((5256, 5285), 'torch.arange', 'torch.arange', (['output.shape[1]'], {}), '(output.shape[1])\n', (5268, 5285), False, 'import torch\n'), ((9191, 9211), 'numpy.mean', 'np.mean', (['x_dic[char]'], {}), '(x_dic[char])\n', (9198, 9211), True, 'import numpy as np\n'), ((9217, 9237), 'numpy.mean', 'np.mean', (['y_dic[char]'], {}), '(y_dic[char])\n', (9224, 9237), True, 'import numpy as np\n'), ((5704, 5723), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (5716, 5723), False, 'import torch\n')]
|
import numpy as np
import pydicom as dicom
def read_dicom(filename):
"""Read DICOM file and convert it to a decent quality uint8 image.
Parameters
----------
filename: str
Existing DICOM file filename.
"""
try:
data = dicom.read_file(filename)
img = np.frombuffer(data.PixelData, dtype=np.uint16).copy()
if data.PhotometricInterpretation == 'MONOCHROME1':
img = img.max() - img
img = img.reshape((data.Rows, data.Columns))
return img, data.ImagerPixelSpacing[0]
except:
return None
def preprocess_xray(img, cut_min=5., cut_max=99.):
"""Preprocess the X-ray image using histogram clipping and global contrast normalization.
Parameters
----------
cut_min: int
Lowest percentile which is used to cut the image histogram.
cut_max: int
Highest percentile.
"""
img = img.astype(np.float64)
lim1, lim2 = np.percentile(img, [cut_min, cut_max])
img[img < lim1] = lim1
img[img > lim2] = lim2
img -= lim1
img /= img.max()
img *= 255
return img.astype(np.uint8, casting='unsafe')
def get_joint_y_proposals(img, av_points=11, margin=0.25):
"""Return Y-coordinates of the joint approximate locations."""
R, C = img.shape
# Sum the middle if the leg is along the X-axis
segm_line = np.sum(img[int(R * margin):int(R * (1 - margin)),
int(C / 3):int(C - C / 3)], axis=1)
# Smooth the segmentation line and find the absolute of the derivative
segm_line = np.abs(np.convolve(
np.diff(segm_line), np.ones((av_points, )) / av_points)[(av_points-1):])
# Get top tau % of the peaks
peaks = np.argsort(segm_line)[::-1][:int(0.1 * R * (1 - 2 * margin))]
return peaks[::10] + int(R * margin)
|
[
"numpy.frombuffer",
"numpy.ones",
"numpy.diff",
"numpy.argsort",
"pydicom.read_file",
"numpy.percentile"
] |
[((950, 988), 'numpy.percentile', 'np.percentile', (['img', '[cut_min, cut_max]'], {}), '(img, [cut_min, cut_max])\n', (963, 988), True, 'import numpy as np\n'), ((261, 286), 'pydicom.read_file', 'dicom.read_file', (['filename'], {}), '(filename)\n', (276, 286), True, 'import pydicom as dicom\n'), ((1719, 1740), 'numpy.argsort', 'np.argsort', (['segm_line'], {}), '(segm_line)\n', (1729, 1740), True, 'import numpy as np\n'), ((301, 347), 'numpy.frombuffer', 'np.frombuffer', (['data.PixelData'], {'dtype': 'np.uint16'}), '(data.PixelData, dtype=np.uint16)\n', (314, 347), True, 'import numpy as np\n'), ((1600, 1618), 'numpy.diff', 'np.diff', (['segm_line'], {}), '(segm_line)\n', (1607, 1618), True, 'import numpy as np\n'), ((1620, 1641), 'numpy.ones', 'np.ones', (['(av_points,)'], {}), '((av_points,))\n', (1627, 1641), True, 'import numpy as np\n')]
|
# AUTOGENERATED! DO NOT EDIT! File to edit: ttbarzp.ipynb (unless otherwise specified).
__all__ = ['get_elijah_ttbarzp_cs', 'get_manuel_ttbarzp_cs', 'import47Ddata', 'get47Dfeatures']
# Cell
import numpy as np
import tensorflow as tf
# Cell
def get_elijah_ttbarzp_cs():
r"""
Contains cross section information produced by Elijah for $pp \to t\overline{t} \; Z'$ collider phenomenology.
Returns list containing signal masses, signal cross sections (for those masses, in pb), and background cross sections
(also in pb)
"""
# Z' masses (GeV) for which Elijah created signal samples
elijah_masses = [10, 50, 100, 200, 350, 500, 1000, 2000, 5000]
# signal cross sections (pb)
elijah_sig_css = [9.801, 0.5445, 0.1442, 0.03622, 0.009998, 0.003802, 0.0003936, 2.034e-05, 2.748e-08]
# background cross sections (pb)
elijah_bg_css = [0.106, 0.0117, 5.58]
return [elijah_masses, elijah_sig_css, elijah_bg_css]
# Cell
def get_manuel_ttbarzp_cs():
r"""
Contains cross section information produced through MadGraph by Manuel for collider phenomenology regarding
the semihadronic, semileptonic $pp \to t\overline{t} \; Z', Z' \to b\overline{b}$ channel
"""
# Z' masses (GeV) for which I (Elijah) created signal samples
manuel_masses = [350, 500, 750, 1000, 2000, 3000, 4000]
# signal cross sections (pb)
manuel_sig_css = [0.001395, 0.0007823, 0.0003429, 0.0001692, 1.808e-05, 1.325e-06, 4.456e-07]
# background cross sections (pb)
manuel_bg_css = [0.1339, 0.01187, 5.603]
return [manuel_masses, manuel_sig_css, manuel_bg_css]
# Cell
def import47Ddata(name):
r"""
Imports `name.npy` file containing 47-dimensional data for training
Available files:
- bgh.npy (Standard Model background 1, $pp \to t\overline{t}h$)
- bg4t.npy (Standard Model background 2, $pp \to t\overline{t}t\overline{t}$)
- bgnoh.npy (Standard Model background 3, $pp \to t\overline{t} \; \setminus \; h$)
- sig350G.npy ($Z'$ signal, $m_{Z'} = 350$ GeV)
- sig500G.npy ($Z'$ signal, $m_{Z'} = 500$ GeV)
- sig1T.npy ($Z'$ signal, $m_{Z'} = 1$ TeV)
- sig2T.npy ($Z'$ signal, $m_{Z'} = 2$ TeV)
- sig4T.npy ($Z'$ signal, $m_{Z'} = 4$ TeV)
"""
if name[-4:] == '.npy':
name = name[:-4]
url = 'https://storage.googleapis.com/ttbarzp/47dim/'
try:
path = tf.keras.utils.get_file(f'{name}.npy', url + name + '.npy')
data = np.load(path)
return data
except:
print(f"{name}.npy doesn't appear to exist")
# Cell
def get47Dfeatures():
"""
Returns list containing the names of the 47 features found in the data accessible through
`ttbarzp.import47Ddata()`
"""
return [
'pT b1', 'pT b2', 'pT b3', 'pT b4',
'sdEta b1 b2', 'sdEta b1 b3', 'sdEta b1 b4', 'sdEta b2 b3', 'sdEta b2 b4', 'sdEta b3 b4',
'sdPhi b1 b2', 'sdPhi b1 b3', 'sdPhi b1 b4', 'sdPhi b2 b3', 'sdPhi b2 b4', 'sdPhi b3 b4',
'dR b1 b2', 'dR b1 b3', 'dR b1 b4', 'dR b2 b3', 'dR b2 b4', 'dR b3 b4',
'MET', 'pT l', 'MT l MET',
'M b1 b2', 'M b1 b3', 'M b1 b4', 'M b2 b3', 'M b2 b4', 'M b3 b4',
'MT b1 l MET', 'MT b2 l MET', 'MT b3 l MET', 'MT b4 l MET',
'M j1 j2', 'pT j1', 'pT j2', 'dR j1 j2',
'dR b1 l', 'dR b2 l', 'dR b3 l', 'dR b4 l',
'sdPhi b1 l', 'sdPhi b2 l', 'sdPhi b3 l', 'sdPhi b4 l']
|
[
"numpy.load",
"tensorflow.keras.utils.get_file"
] |
[((2383, 2442), 'tensorflow.keras.utils.get_file', 'tf.keras.utils.get_file', (['f"""{name}.npy"""', "(url + name + '.npy')"], {}), "(f'{name}.npy', url + name + '.npy')\n", (2406, 2442), True, 'import tensorflow as tf\n'), ((2458, 2471), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (2465, 2471), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 11:01:16 2015
@author: hehu
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.lda import LDA
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import NullFormatter
from scipy.linalg import eig
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def visualize(X, y, clf):
fig, ax = plt.subplots(figsize=[6,6])
plt.axis('equal')
# create a mesh to plot in
#x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
#y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x_min, x_max = -9, 3
y_min, y_max = -7, 5
if clf is not None:
h = .01 # step size in the mesh
xx, yy = np.meshgrid(np.arange(x_min-1, x_max+1, h),
np.arange(y_min-1, y_max+1, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, cmap='bwr', alpha=0.5) #plt.cm.Paired cmap='bwr',
ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
if clf.kernel == "linear":
# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-10, 5, 500)
yy = a * xx - (clf.intercept_[0]) / w[1]
# plot the parallels to the separating hyperplane that pass through the
# support vectors
margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
yy_down = yy + a * margin
yy_up = yy - a * margin
ax.plot(xx, yy, 'k-')
ax.plot(xx, yy_down, 'k--')
ax.plot(xx, yy_up, 'k--')
for svIdx in range(clf.support_vectors_.shape[0]):
sv = [clf.support_vectors_[svIdx, 0], clf.support_vectors_[svIdx, 1]]
ax.annotate("Support Vectors",
sv,
xytext=(-6, 3),
size=13,
bbox=dict(boxstyle="round4", fc="w", ec = "g"),
arrowprops=dict(arrowstyle="simple",
connectionstyle="arc3,rad=0.2",
shrinkA = 0,
shrinkB = 8,
fc = "g",
ec = "g"),
horizontalalignment='center',
verticalalignment='middle')
# Plot margin
x0 = -0.5
y0 = a * x0 - (clf.intercept_[0]) / w[1]
distances = np.hypot(x0 - xx, y0 - yy_down)
minIdx = np.argmin(distances)
x1 = xx[minIdx]
y1 = yy_down[minIdx]
ax.annotate("",
xy=(x0, y0), xycoords='data',
xytext=(x1, y1), textcoords='data',
arrowprops=dict(arrowstyle="<->",
connectionstyle="arc3"),
)
distances = np.hypot(x0 - xx, y0 - yy_up)
minIdx = np.argmin(distances)
x2 = xx[minIdx]
y2 = yy_up[minIdx]
ax.annotate("",
xy=(x0, y0), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="<->",
connectionstyle="arc3"),
)
ax.annotate("Margin",
(0.5*(x0+x1), 0.5*(y0+y1)),
xytext=(1.5, -6.7),
size=13,
bbox=dict(boxstyle="round4", fc="w", ec = "g"),
arrowprops=dict(arrowstyle="simple",
connectionstyle="arc3,rad=-0.2",
shrinkA = 0,
shrinkB = 8,
fc = "g",
ec = "g"),
horizontalalignment='center',
verticalalignment='middle')
ax.annotate("Margin",
(0.5*(x0+x2), 0.5*(y0+y2)),
xytext=(1.5, -6.7),
size=13,
bbox=dict(boxstyle="round4", fc="w", ec = "g"),
arrowprops=dict(arrowstyle="simple",
connectionstyle="arc3,rad=-0.2",
shrinkA = 0,
shrinkB = 8,
fc = "g",
ec = "g"),
horizontalalignment='center',
verticalalignment='middle')
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
facecolors='none', zorder=10)
#ax.scatter(X[:, 0], X[:, 1], c=y, zorder=10, cmap=plt.cm.Paired)
ax.set_ylim(y_min, y_max)
ax.set_xlim(x_min, x_max)
X1 = X[y==1, :]
X2 = X[y==0, :]
ax.plot(X1[:, 0], X1[:, 1], 'ro', zorder = 1, alpha = 0.6)
ax.plot(X2[:, 0], X2[:, 1], 'bx', zorder = 1)
def generate_data(N):
X1 = np.random.randn(2,N)
X2 = np.random.randn(2,N)
M1 = 0.7*np.array([[1.5151, -0.1129], [0.1399, 0.6287]])
M2 = 0.7*np.array([[0.8602, 1.2461], [-0.0737, -1.5240]])
T1 = np.array([-1, 1]).reshape((2,1))
T2 = np.array([-2, -5]).reshape((2,1))
X1 = np.dot(M1, X1) + np.tile(T1, [1,N])
X2 = np.dot(M2, X2) + np.tile(T2, [1,N])
X1 = X1[::-1,:]
X2 = X2[::-1,:]
return X1, X2
if __name__ == "__main__":
plt.close("all")
# Generate random training data
N = 200
np.random.seed(2014)
X1, X2 = generate_data(N)
X = np.concatenate((X1.T, X2.T))
y = np.concatenate((np.ones(N), np.zeros(N)))
# Generate test sample
np.random.seed(2016)
X1_test, X2_test = generate_data(N)
X_test = np.concatenate((X1_test.T, X2_test.T))
y_test = np.concatenate((np.ones(N), np.zeros(N)))
clf = SVC(kernel = 'linear', C = 100)
clf.fit(X, y)
visualize(X, y, None)
plt.savefig("../images/SVM_data.pdf", bbox_inches = "tight", transparent = True)
visualize(X, y, clf)
plt.savefig("../images/SVM_boundary.pdf", bbox_inches = "tight", transparent = True)
clf = SVC(kernel = 'poly', degree = 2, C = 1)
clf.fit(X, y)
visualize(X, y, clf)
plt.title("SVM with 2nd order Polynomial Kernel")
plt.savefig("../images/SVM_boundary_poly2.pdf", bbox_inches = "tight", transparent = True)
clf = SVC(kernel = 'rbf', C = 1)
clf.fit(X, y)
visualize(X, y, clf)
plt.title("SVM with the RBF Kernel")
plt.savefig("../images/SVM_boundary_RBF.pdf", bbox_inches = "tight", transparent = True)
|
[
"numpy.array",
"numpy.arange",
"matplotlib.pyplot.close",
"numpy.dot",
"numpy.linspace",
"numpy.random.seed",
"numpy.concatenate",
"numpy.argmin",
"numpy.hypot",
"matplotlib.pyplot.axis",
"numpy.tile",
"matplotlib.pyplot.savefig",
"numpy.ones",
"matplotlib.pyplot.title",
"numpy.random.randn",
"sklearn.svm.SVC",
"numpy.power",
"numpy.sum",
"numpy.zeros",
"matplotlib.pyplot.subplots"
] |
[((788, 816), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '[6, 6]'}), '(figsize=[6, 6])\n', (800, 816), True, 'import matplotlib.pyplot as plt\n'), ((820, 837), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (828, 837), True, 'import matplotlib.pyplot as plt\n'), ((5852, 5873), 'numpy.random.randn', 'np.random.randn', (['(2)', 'N'], {}), '(2, N)\n', (5867, 5873), True, 'import numpy as np\n'), ((5882, 5903), 'numpy.random.randn', 'np.random.randn', (['(2)', 'N'], {}), '(2, N)\n', (5897, 5903), True, 'import numpy as np\n'), ((6325, 6341), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (6334, 6341), True, 'import matplotlib.pyplot as plt\n'), ((6414, 6434), 'numpy.random.seed', 'np.random.seed', (['(2014)'], {}), '(2014)\n', (6428, 6434), True, 'import numpy as np\n'), ((6483, 6511), 'numpy.concatenate', 'np.concatenate', (['(X1.T, X2.T)'], {}), '((X1.T, X2.T))\n', (6497, 6511), True, 'import numpy as np\n'), ((6607, 6627), 'numpy.random.seed', 'np.random.seed', (['(2016)'], {}), '(2016)\n', (6621, 6627), True, 'import numpy as np\n'), ((6691, 6729), 'numpy.concatenate', 'np.concatenate', (['(X1_test.T, X2_test.T)'], {}), '((X1_test.T, X2_test.T))\n', (6705, 6729), True, 'import numpy as np\n'), ((6800, 6827), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""linear"""', 'C': '(100)'}), "(kernel='linear', C=100)\n", (6803, 6827), False, 'from sklearn.svm import SVC, LinearSVC\n'), ((6885, 6961), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../images/SVM_data.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "('../images/SVM_data.pdf', bbox_inches='tight', transparent=True)\n", (6896, 6961), True, 'import matplotlib.pyplot as plt\n'), ((7000, 7085), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../images/SVM_boundary.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "('../images/SVM_boundary.pdf', bbox_inches='tight', transparent=True\n )\n", (7011, 7085), True, 'import matplotlib.pyplot as plt\n'), ((7104, 7137), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""poly"""', 'degree': '(2)', 'C': '(1)'}), "(kernel='poly', degree=2, C=1)\n", (7107, 7137), False, 'from sklearn.svm import SVC, LinearSVC\n'), ((7196, 7245), 'matplotlib.pyplot.title', 'plt.title', (['"""SVM with 2nd order Polynomial Kernel"""'], {}), "('SVM with 2nd order Polynomial Kernel')\n", (7205, 7245), True, 'import matplotlib.pyplot as plt\n'), ((7250, 7340), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../images/SVM_boundary_poly2.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "('../images/SVM_boundary_poly2.pdf', bbox_inches='tight',\n transparent=True)\n", (7261, 7340), True, 'import matplotlib.pyplot as plt\n'), ((7356, 7378), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""rbf"""', 'C': '(1)'}), "(kernel='rbf', C=1)\n", (7359, 7378), False, 'from sklearn.svm import SVC, LinearSVC\n'), ((7435, 7471), 'matplotlib.pyplot.title', 'plt.title', (['"""SVM with the RBF Kernel"""'], {}), "('SVM with the RBF Kernel')\n", (7444, 7471), True, 'import matplotlib.pyplot as plt\n'), ((7476, 7564), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""../images/SVM_boundary_RBF.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "('../images/SVM_boundary_RBF.pdf', bbox_inches='tight',\n transparent=True)\n", (7487, 7564), True, 'import matplotlib.pyplot as plt\n'), ((5921, 5968), 'numpy.array', 'np.array', (['[[1.5151, -0.1129], [0.1399, 0.6287]]'], {}), '([[1.5151, -0.1129], [0.1399, 0.6287]])\n', (5929, 5968), True, 'import numpy as np\n'), ((5982, 6029), 'numpy.array', 'np.array', (['[[0.8602, 1.2461], [-0.0737, -1.524]]'], {}), '([[0.8602, 1.2461], [-0.0737, -1.524]])\n', (5990, 6029), True, 'import numpy as np\n'), ((6135, 6149), 'numpy.dot', 'np.dot', (['M1', 'X1'], {}), '(M1, X1)\n', (6141, 6149), True, 'import numpy as np\n'), ((6152, 6171), 'numpy.tile', 'np.tile', (['T1', '[1, N]'], {}), '(T1, [1, N])\n', (6159, 6171), True, 'import numpy as np\n'), ((6180, 6194), 'numpy.dot', 'np.dot', (['M2', 'X2'], {}), '(M2, X2)\n', (6186, 6194), True, 'import numpy as np\n'), ((6197, 6216), 'numpy.tile', 'np.tile', (['T2', '[1, N]'], {}), '(T2, [1, N])\n', (6204, 6216), True, 'import numpy as np\n'), ((1152, 1186), 'numpy.arange', 'np.arange', (['(x_min - 1)', '(x_max + 1)', 'h'], {}), '(x_min - 1, x_max + 1, h)\n', (1161, 1186), True, 'import numpy as np\n'), ((1213, 1247), 'numpy.arange', 'np.arange', (['(y_min - 1)', '(y_max + 1)', 'h'], {}), '(y_min - 1, y_max + 1, h)\n', (1222, 1247), True, 'import numpy as np\n'), ((1709, 1733), 'numpy.linspace', 'np.linspace', (['(-10)', '(5)', '(500)'], {}), '(-10, 5, 500)\n', (1720, 1733), True, 'import numpy as np\n'), ((3158, 3189), 'numpy.hypot', 'np.hypot', (['(x0 - xx)', '(y0 - yy_down)'], {}), '(x0 - xx, y0 - yy_down)\n', (3166, 3189), True, 'import numpy as np\n'), ((3211, 3231), 'numpy.argmin', 'np.argmin', (['distances'], {}), '(distances)\n', (3220, 3231), True, 'import numpy as np\n'), ((3573, 3602), 'numpy.hypot', 'np.hypot', (['(x0 - xx)', '(y0 - yy_up)'], {}), '(x0 - xx, y0 - yy_up)\n', (3581, 3602), True, 'import numpy as np\n'), ((3624, 3644), 'numpy.argmin', 'np.argmin', (['distances'], {}), '(distances)\n', (3633, 3644), True, 'import numpy as np\n'), ((6045, 6062), 'numpy.array', 'np.array', (['[-1, 1]'], {}), '([-1, 1])\n', (6053, 6062), True, 'import numpy as np\n'), ((6087, 6105), 'numpy.array', 'np.array', (['[-2, -5]'], {}), '([-2, -5])\n', (6095, 6105), True, 'import numpy as np\n'), ((6536, 6546), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (6543, 6546), True, 'import numpy as np\n'), ((6548, 6559), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6556, 6559), True, 'import numpy as np\n'), ((6759, 6769), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (6766, 6769), True, 'import numpy as np\n'), ((6771, 6782), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (6779, 6782), True, 'import numpy as np\n'), ((690, 711), 'numpy.power', 'np.power', (['(x - mu)', '(2.0)'], {}), '(x - mu, 2.0)\n', (698, 711), True, 'import numpy as np\n'), ((718, 736), 'numpy.power', 'np.power', (['sig', '(2.0)'], {}), '(sig, 2.0)\n', (726, 736), True, 'import numpy as np\n'), ((1943, 1965), 'numpy.sum', 'np.sum', (['(clf.coef_ ** 2)'], {}), '(clf.coef_ ** 2)\n', (1949, 1965), True, 'import numpy as np\n')]
|
import numpy as np
import os
import os.path as op
import cv2
from tqdm import tqdm
import multiprocessing
from FeatureExtractor import get_gist_C_implementation
from utils import ensure_dir, info
input_dir = "./dataset/raw_image"
catalog = {}
paths = []
feats = []
for (root, dirs, files) in os.walk(input_dir):
for f in files:
if f.split('.')[-1].lower() in ['jpg', 'bmp', 'png']:
path = op.join(root, f)
catalog[len(catalog)] = {
'path': path # For possible further metadata
}
info("Extracting GIST descriptor", domain=__file__)
processnum = 6
unit = len(catalog) // processnum + 1
def getfeat(start, end, use_tqdm=False):
subpaths, subfeats = [], []
for i in (range(start, end) if not use_tqdm else tqdm(range(start, end))):
img = cv2.imread(catalog[i]['path'])
vec = get_gist_C_implementation(img)
subpaths.append(catalog[i]['path'])
subfeats.append(vec)
return subpaths, subfeats
pool = multiprocessing.Pool()
processes = []
info("Starting worker processes", domain=__file__)
for pid in tqdm(range(1, processnum)):
processes.append(pool.apply_async(getfeat, args=(pid * unit, min((pid + 1) * unit, len(catalog)))))
subpath, subfeat = getfeat(0, unit, use_tqdm=True)
paths, feats = subpath, subfeat
info("Joining worker processes", domain=__file__)
for pid in tqdm(range(processnum - 1)):
subpath, subfeat = processes[pid].get()
paths += subpath
feats += subfeat
np.savez("./dataset/feature.npz", Path=paths, Feat=feats)
info("Preprocess completed! {} images loaded into dataset".format(len(paths)), domain=__file__)
|
[
"utils.info",
"numpy.savez",
"FeatureExtractor.get_gist_C_implementation",
"os.path.join",
"multiprocessing.Pool",
"cv2.imread",
"os.walk"
] |
[((294, 312), 'os.walk', 'os.walk', (['input_dir'], {}), '(input_dir)\n', (301, 312), False, 'import os\n'), ((547, 598), 'utils.info', 'info', (['"""Extracting GIST descriptor"""'], {'domain': '__file__'}), "('Extracting GIST descriptor', domain=__file__)\n", (551, 598), False, 'from utils import ensure_dir, info\n'), ((1006, 1028), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (1026, 1028), False, 'import multiprocessing\n'), ((1045, 1095), 'utils.info', 'info', (['"""Starting worker processes"""'], {'domain': '__file__'}), "('Starting worker processes', domain=__file__)\n", (1049, 1095), False, 'from utils import ensure_dir, info\n'), ((1324, 1373), 'utils.info', 'info', (['"""Joining worker processes"""'], {'domain': '__file__'}), "('Joining worker processes', domain=__file__)\n", (1328, 1373), False, 'from utils import ensure_dir, info\n'), ((1501, 1558), 'numpy.savez', 'np.savez', (['"""./dataset/feature.npz"""'], {'Path': 'paths', 'Feat': 'feats'}), "('./dataset/feature.npz', Path=paths, Feat=feats)\n", (1509, 1558), True, 'import numpy as np\n'), ((819, 849), 'cv2.imread', 'cv2.imread', (["catalog[i]['path']"], {}), "(catalog[i]['path'])\n", (829, 849), False, 'import cv2\n'), ((864, 894), 'FeatureExtractor.get_gist_C_implementation', 'get_gist_C_implementation', (['img'], {}), '(img)\n', (889, 894), False, 'from FeatureExtractor import get_gist_C_implementation\n'), ((415, 431), 'os.path.join', 'op.join', (['root', 'f'], {}), '(root, f)\n', (422, 431), True, 'import os.path as op\n')]
|
"""Spectrum module"""
import numpy as np
from scipy.stats import norm
def pow2db(power: np.array) -> np.array:
"""
Convert power to decibels
https://de.mathworks.com/help/signal/ref/pow2db.html
"""
return 10.0 * np.log10(power)
def db2pow(decibel: np.array) -> np.array:
"""
Convert decibel to power
https://de.mathworks.com/help/signal/ref/db2pow.html
"""
return np.power(10.0, decibel / 10.0)
def mag2db(power: np.array) -> np.array:
"""
Convert magnitude to decibels
https://de.mathworks.com/help/signal/ref/mag2db.html
"""
return 2 * pow2db(power)
def signal_energy(signal: np.array) -> np.array:
"""Calculate the signal energy"""
return np.sum(np.square(signal, dtype=np.float64))
def compute_normalized_spectral_difference(
reference_spectrum: np.array, distorted_spectrum: np.array
) -> np.array:
"""Compute the normalized difference of two spectra"""
difference = np.sum(
np.abs(db2pow(reference_spectrum) - db2pow(distorted_spectrum)), axis=1
)
return pow2db(
difference
/ (np.sum(np.abs(db2pow(reference_spectrum)), axis=1) + np.finfo(float).eps)
)
def compute_spectral_support(spectrum: np.array, scale: float = 12) -> np.array:
"""Compute the spectral support of perceptual spectrum using a normal distribution cdf"""
return np.apply_along_axis(norm.cdf, 1, spectrum, scale=scale)
|
[
"numpy.log10",
"numpy.power",
"numpy.square",
"numpy.apply_along_axis",
"numpy.finfo"
] |
[((409, 439), 'numpy.power', 'np.power', (['(10.0)', '(decibel / 10.0)'], {}), '(10.0, decibel / 10.0)\n', (417, 439), True, 'import numpy as np\n'), ((1374, 1429), 'numpy.apply_along_axis', 'np.apply_along_axis', (['norm.cdf', '(1)', 'spectrum'], {'scale': 'scale'}), '(norm.cdf, 1, spectrum, scale=scale)\n', (1393, 1429), True, 'import numpy as np\n'), ((235, 250), 'numpy.log10', 'np.log10', (['power'], {}), '(power)\n', (243, 250), True, 'import numpy as np\n'), ((726, 761), 'numpy.square', 'np.square', (['signal'], {'dtype': 'np.float64'}), '(signal, dtype=np.float64)\n', (735, 761), True, 'import numpy as np\n'), ((1159, 1174), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (1167, 1174), True, 'import numpy as np\n')]
|
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
def data_to_2d_heatmap(X):
pca = PCA(n_components=2)
pca.fit(X)
X_simple = pca.transform(X)
X_simple = np.array(X_simple)
# print(X_simple)
x_simple = X_simple[:,0]
y_simple = X_simple[:,1]
# fig, ax = plt.subplots()
# ax.plot(x_simple, y_simple, 'o')
# ax.set_title('Random data')
# plt.show()
heatmap, xedges, yedges = np.histogram2d(x_simple, y_simple, bins=32)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
# plt.imshow(heatmap, extent=extent, cmap="viridis")
plt.imshow(heatmap, extent=extent, cmap="jet")
plt.show()
num_samples, num_dimensions = 100000, 100
X = np.random.rand(num_samples, num_dimensions)
data_to_2d_heatmap(X)
|
[
"matplotlib.pyplot.imshow",
"numpy.random.rand",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.clf",
"numpy.array",
"numpy.histogram2d",
"matplotlib.pyplot.show"
] |
[((728, 771), 'numpy.random.rand', 'np.random.rand', (['num_samples', 'num_dimensions'], {}), '(num_samples, num_dimensions)\n', (742, 771), True, 'import numpy as np\n'), ((131, 150), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (134, 150), False, 'from sklearn.decomposition import PCA\n'), ((207, 225), 'numpy.array', 'np.array', (['X_simple'], {}), '(X_simple)\n', (215, 225), True, 'import numpy as np\n'), ((447, 490), 'numpy.histogram2d', 'np.histogram2d', (['x_simple', 'y_simple'], {'bins': '(32)'}), '(x_simple, y_simple, bins=32)\n', (461, 490), True, 'import numpy as np\n'), ((551, 560), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (558, 560), True, 'import matplotlib.pyplot as plt\n'), ((618, 664), 'matplotlib.pyplot.imshow', 'plt.imshow', (['heatmap'], {'extent': 'extent', 'cmap': '"""jet"""'}), "(heatmap, extent=extent, cmap='jet')\n", (628, 664), True, 'import matplotlib.pyplot as plt\n'), ((667, 677), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (675, 677), True, 'import matplotlib.pyplot as plt\n')]
|
from src import tours
import numpy as np
tolerance = 1e-4
def test_tour_traversal():
square = np.array([[0, 0], [0, 1], [1, 1], [1, 0.]])
tour = [0, 1, 2, 3]
assert abs(tours.tour_traversal(tour, square) - 4.) < tolerance
|
[
"numpy.array",
"src.tours.tour_traversal"
] |
[((101, 145), 'numpy.array', 'np.array', (['[[0, 0], [0, 1], [1, 1], [1, 0.0]]'], {}), '([[0, 0], [0, 1], [1, 1], [1, 0.0]])\n', (109, 145), True, 'import numpy as np\n'), ((184, 218), 'src.tours.tour_traversal', 'tours.tour_traversal', (['tour', 'square'], {}), '(tour, square)\n', (204, 218), False, 'from src import tours\n')]
|
from netCDF4 import Dataset, num2date
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
import argparse
import ast
import gc
import logging
import math
import sys
import time
import numpy as np
import pandas as pd
import psutil
import tensorflow as tf
from tensorflow.keras.mixed_precision import experimental as mixed_precision
try:
import tensorflow_addons as tfa
except Exception as e:
tfa = None
import data_generators
import custom_losses as cl
import hparameters
import models
import utility
tf.keras.backend.set_floatx('float16')
tf.keras.backend.set_epsilon(1e-3)
try:
gpu_devices = tf.config.list_physical_devices('GPU')
except Exception as e:
gpu_devices = tf.config.experimental.list_physical_devices('GPU')
policy = mixed_precision.Policy('mixed_float16')
mixed_precision.set_policy(policy)
def is_compatible_with(self, other):
"""Returns True if the `other` DType will be converted to this DType.
Monkey patch: incompatibility issues between tfa.optimizers and mixed precision training
The conversion rules are as follows:
```python
DType(T) .is_compatible_with(DType(T)) == True
```
Args:
other: A `DType` (or object that may be converted to a `DType`).
Returns:
True if a Tensor of the `other` `DType` will be implicitly converted to
this `DType`.
"""
other = tf.dtypes.as_dtype(other)
if self._type_enum==19 and other.as_datatype_enum==1:
return True
return self._type_enum in (other.as_datatype_enum,
other.base_dtype.as_datatype_enum)
tf.DType.is_compatible_with = is_compatible_with
class WeatherModel():
"""Handles the Training of the Deep Learning Weather model
Example of how to use:
WeatherModel = WeatherModel( t_params, m_params)
WeatherModel.initialize_scheme_era5Eobs() #Initializes datasets for ERA5 and Eobs
WeatherModel.train_model() #Trains and saves model
"""
def __init__(self, t_params, m_params):
"""Train the TRU_NET Model
"""
self.t_params = t_params
self.m_params = m_params
def initialize_scheme_era5Eobs(self):
"""Initialization scheme for the ERA5 and E-OBS datasets.
This method creates the datasets
"""
# region ---- Parameters related to training length and training reporting frequency
era5_eobs = data_generators.Era5_Eobs( self.t_params, self.m_params)
# hparameters files calculates train_batches assuing we are only evaluating one location,
# therefore we must adjust got multiple locations (loc_count)
self.t_params['train_batches'] = int(self.t_params['train_batches'] * era5_eobs.loc_count)
self.t_params['val_batches'] = int(self.t_params['val_batches'] * era5_eobs.loc_count)
# The fequency at which we report during training and validation i.e every 10% of minibatches report training loss and training mse
self.train_batch_report_freq = max( int(self.t_params['train_batches']*self.t_params['reporting_freq']), 3)
self.val_batch_report_freq = max( int(self.t_params['val_batches']*self.t_params['reporting_freq']), 3)
#endregion
# region ---- Restoring/Creating New Training Records and Restoring training progress
#This training records keeps track of the losses on each epoch
try:
self.df_training_info = pd.read_csv( "checkpoints/{}/checkpoint_scores.csv".format(utility.model_name_mkr(m_params,t_params=self.t_params,htuning=m_params.get('htuning',False))), header=0, index_col=False)
self.df_training_info = self.df_training_info[['Epoch','Train_loss','Train_mse','Val_loss','Val_mse','Checkpoint_Path','Last_Trained_Batch']]
self.start_epoch = int(max([self.df_training_info['Epoch'][0]], default=0))
last_batch = int( self.df_training_info.loc[self.df_training_info['Epoch']==self.start_epoch,'Last_Trained_Batch'].iloc[0] )
if(last_batch in [-1, self.t_params['train_batches']] ):
self.start_epoch = self.start_epoch + 1
self.batches_to_skip = 0
else:
self.batches_to_skip = last_batch
print("Recovered training records")
except FileNotFoundError as e:
#If no file found, then make new training records file
self.df_training_info = pd.DataFrame(columns=['Epoch','Train_loss','Train_mse','Val_loss','Val_mse','Checkpoint_Path','Last_Trained_Batch'] )
self.batches_to_skip = 0
self.start_epoch = 0
print("Did not recover training records. Starting from scratch")
# endregion
# region ---- Defining Model / Optimizer / Losses / Metrics / Records / Checkpoints / Tensorboard
devices = tf.config.get_visible_devices() #tf.config.experimental.list_physical_devices('GPU')
#gpus_names = [ device.name for device in devices if device.device_type == "GPU" ]
#self.strategy = tf.distribute.MirroredStrategy( devices=gpus_names ) #OneDeviceStrategy(device="/GPU:0") #
self.strategy = tf.distribute.MirroredStrategy( )
assert self.t_params['batch_size'] % self.strategy.num_replicas_in_sync == 0
print("Number of Devices used in MirroredStrategy: {}".format(self.strategy.num_replicas_in_sync))
with self.strategy.scope():
#Model
self.strategy_gpu_count = self.strategy.num_replicas_in_sync
self.t_params['gpu_count'] = self.strategy.num_replicas_in_sync
self.model = models.model_loader( self.t_params, self.m_params )
#Optimizer
optimizer = tfa.optimizers.RectifiedAdam( **self.m_params['rec_adam_params'], total_steps=self.t_params['train_batches']*20)
self.optimizer = mixed_precision.LossScaleOptimizer( optimizer, loss_scale=tf.mixed_precision.experimental.DynamicLossScale() )
# These objects will aggregate losses and metrics across batches and epochs
self.loss_agg_batch = tf.keras.metrics.Mean(name='loss_agg_batch' )
self.loss_agg_epoch = tf.keras.metrics.Mean(name="loss_agg_epoch")
self.mse_agg_epoch = tf.keras.metrics.Mean(name='mse_agg_epoch')
self.loss_agg_val = tf.keras.metrics.Mean(name='loss_agg_val')
self.mse_agg_val = tf.keras.metrics.Mean(name='mse_agg_val')
#checkpoints (For Epochs)
#The CheckpointManagers can be called to serializae the weights within TRUNET
checkpoint_path_epoch = "./checkpoints/{}/epoch".format(utility.model_name_mkr(m_params,t_params=self.t_params, htuning=m_params.get('htuning',False) ))
os.makedirs(checkpoint_path_epoch,exist_ok=True)
with self.strategy.scope():
ckpt_epoch = tf.train.Checkpoint(model=self.model, optimizer=self.optimizer)
self.ckpt_mngr_epoch = tf.train.CheckpointManager(ckpt_epoch, checkpoint_path_epoch, max_to_keep=self.t_params['checkpoints_to_keep'], keep_checkpoint_every_n_hours=None)
#restoring last checkpoint if it exists
if self.ckpt_mngr_epoch.latest_checkpoint:
# compat: Initializing model and optimizer before restoring from checkpoint
try:
ckpt_epoch.restore(self.ckpt_mngr_epoch.latest_checkpoint).assert_consumed()
except AssertionError as e:
ckpt_epoch.restore(self.ckpt_mngr_epoch.latest_checkpoint)
print (' Restoring model from best checkpoint')
else:
print (' Initializing model from scratch')
#Tensorboard
os.makedirs("log_tensboard/{}".format(utility.model_name_mkr(m_params, t_params=self.t_params, htuning=self.m_params.get('htuning',False) )), exist_ok=True )
#self.writer = tf.summary.create_file_writer( "log_tensboard/{}".format(utility.model_name_mkr(m_params,t_params=self.t_params, htuning=self.m_params.get('htuning',False) ) ) )
# endregion
# region ---- Making Datasets
#caching dataset to file post pre-processing steps have been completed
cache_suffix = utility.cache_suffix_mkr( m_params, self.t_params )
os.makedirs( './Data/data_cache/', exist_ok=True )
_ds_train_val, _ = era5_eobs.load_data_era5eobs( self.t_params['train_batches'] + self.t_params['val_batches'] , self.t_params['start_date'], self.t_params['parallel_calls'] )
ds_train = _ds_train_val.take(self.t_params['train_batches'] )
ds_val = _ds_train_val.skip(self.t_params['train_batches'] ).take(self.t_params['val_batches'])
#TODO: undo cache
ds_train = ds_train.cache('Data/data_cache/train'+cache_suffix )
ds_val = ds_val.cache('Data/data_cache/val'+cache_suffix )
ds_train = ds_train.unbatch().shuffle( self.t_params['batch_size']*int(self.t_params['train_batches']/5), reshuffle_each_iteration=True).batch(self.t_params['batch_size']) #.repeat(self.t_params['epochs']-self.start_epoch)
ds_train_val = ds_train.concatenate(ds_val)
ds_train_val = ds_train_val.repeat(self.t_params.get('epochs',100)-self.start_epoch)
self.ds_train_val = self.strategy.experimental_distribute_dataset(dataset=ds_train_val)
self.iter_train_val = enumerate(self.ds_train_val)
bc_ds_in_train = int( self.t_params['train_batches']/era5_eobs.loc_count ) #batch_count
bc_ds_in_val = int( self.t_params['val_batches']/era5_eobs.loc_count )
self.reset_idxs_training = np.cumsum( [bc_ds_in_train]*era5_eobs.loc_count )
self.reset_idxs_validation = np.cumsum( [bc_ds_in_val]*era5_eobs.loc_count )
# endregion
def train_model(self):
"""During training we produce a prediction for a (n by n) square patch.
But we caculate losses on a central (h, w) region within the (n by n) patch
This central region is defined by "bounds" below
"""
bounds = cl.central_region_bounds(self.m_params['region_grid_params']) #list [ lower_h_bound[0], upper_h_bound[0], lower_w_bound[1], upper_w_bound[1] ]
#Training for n epochs
#self.t_params['train_batches'] = self.t_params['train_batches'] if self.m_params['time_sequential'] else int(self.t_params['train_batches']*self.t_params['lookback_target'] )
#self.t_params['val_batches'] = self.t_params['val_batches'] if self.m_params['time_sequential'] else int(self.t_params['val_batches']*self.t_params['lookback_target'] )
for epoch in range(self.start_epoch, int(self.t_params['epochs']) ):
#region resetting metrics, losses, records, timers
self.loss_agg_batch.reset_states()
self.loss_agg_epoch.reset_states()
self.mse_agg_epoch.reset_states()
self.loss_agg_val.reset_states()
self.mse_agg_val.reset_states()
self.df_training_info = self.df_training_info.append( { 'Epoch':epoch, 'Last_Trained_Batch':0 }, ignore_index=True )
start_epoch_train = time.time()
start_batch_group_time = time.time()
batch=0
print("\n\nStarting EPOCH {}".format(epoch ))
#endregion
# --- Training Loops
for batch in range(self.batches_to_skip+1,self.t_params['train_batches'] +1):
# get next set of training datums
idx, (feature, target, mask) = next(self.iter_train_val)
gradients = self.distributed_train_step( feature, target, mask, bounds, 0.0 )
#print(gradients)
# reporting
if( batch % self.train_batch_report_freq==0 or batch == self.t_params['train_batches']):
batch_group_time = time.time() - start_batch_group_time
est_completion_time_seconds = (batch_group_time/self.t_params['reporting_freq']) * (1 - batch/self.t_params['train_batches'])
est_completion_time_mins = est_completion_time_seconds/60
print("\t\tBatch:{}/{}\tTrain Loss: {:.8f} \t Batch Time:{:.4f}\tEpoch mins left:{:.1f}".format(batch, self.t_params['train_batches'], self.loss_agg_batch.result(), batch_group_time, est_completion_time_mins ) )
# resetting time and losses
start_batch_group_time = time.time()
# Updating record of the last batch to be operated on in training epoch
self.df_training_info.loc[ ( self.df_training_info['Epoch']==epoch) , ['Last_Trained_Batch'] ] = batch
self.df_training_info.to_csv( path_or_buf="checkpoints/{}/checkpoint_scores.csv".format(utility.model_name_mkr(self.m_params,t_params=self.t_params, htuning=m_params.get('htuning',False) )), header=True, index=False )
li_losses = [self.loss_agg_batch.result()]
li_names = ['train_loss_batch']
step = batch + (epoch)*self.t_params['train_batches']
#utility.tensorboard_record( self.writer.as_default(), li_losses, li_names, step, gradients, self.model.trainable_variables )
#utility.tensorboard_record( self.writer.as_default(), li_losses, li_names, step, None, None )
self.loss_agg_batch.reset_states()
if batch in self.reset_idxs_training:
self.model.reset_states()
# --- Tensorboard record
li_losses = [self.loss_agg_epoch.result(), self.mse_agg_epoch.result()]
li_names = ['train_loss_epoch','train_mse_epoch']
#utility.tensorboard_record( self.writer.as_default(), li_losses, li_names, epoch)
print("\tStarting Validation")
start_batch_group_time = time.time()
# --- Validation Loops
for batch in range(1, self.t_params['val_batches']+1):
# next datum
idx, (feature, target, mask) = next(self.iter_train_val)
bool_cmpltd = self.distributed_val_step(feature, target, mask, bounds)
# Reporting for validation
if batch % self.val_batch_report_freq == 0 or batch==self.t_params['val_batches'] :
batch_group_time = time.time() - start_batch_group_time
est_completion_time_seconds = (batch_group_time/self.t_params['reporting_freq']) * (1 - batch/self.t_params['val_batches'])
est_completion_time_mins = est_completion_time_seconds/60
print("\t\tCompleted Validation Batch:{}/{} \t Time:{:.4f} \tEst Time Left:{:.1f}".format( batch, self.t_params['val_batches'], batch_group_time, est_completion_time_mins))
start_batch_group_time = time.time()
if batch in self.reset_idxs_validation:
self.model.reset_states()
# region - End of Epoch Reporting and Early iteration Callback
print("\tEpoch:{}\t Train Loss:{:.8f}\t Train MSE:{:.5f}\t Val Loss:{:.5f}\t Val MSE:{:.5f}\t Time:{:.5f}".format(epoch, self.loss_agg_epoch.result(), self.mse_agg_epoch.result(),
self.loss_agg_val.result(), self.mse_agg_val.result() ,time.time()-start_epoch_train ) )
#utility.tensorboard_record( self.writer.as_default(), [self.loss_agg_val.result(), self.mse_agg_val.result()], ['Validation Loss', 'Validation MSE' ], epoch )
self.df_training_info = utility.update_checkpoints_epoch(self.df_training_info, epoch, self.loss_agg_epoch, self.loss_agg_val, self.ckpt_mngr_epoch, self.t_params,
self.m_params, self.mse_agg_epoch ,self.mse_agg_val, self.t_params['objective'] )
# Early Stop Callback
if epoch > ( max( self.df_training_info.loc[:, 'Epoch'], default=0 ) + self.t_params['early_stopping_period']) :
print("Model Stopping Early at EPOCH {}".format(epoch))
print(self.df_training_info)
break
# endregion
print("Model Training Finished")
def train_step(self, feature, target, mask, bounds, _init):
if _init==1.0:
if self.m_params['time_sequential'] == True:
inp_shape = [self.t_params['batch_size'], self.t_params['lookback_feature']] + self.m_params['region_grid_params']['outer_box_dims'] + [len(self.t_params['vars_for_feature'])]
else:
inp_shape = [self.t_params['batch_size'] ] + self.m_params['region_grid_params']['outer_box_dims'] + [ int(self.t_params['lookback_feature']*len(self.t_params['vars_for_feature'])) ]
_ = self.model( tf.zeros( inp_shape, dtype=tf.float16), self.t_params['trainable'] ) #( bs, tar_seq_len, h, w)
gradients = [ tf.zeros_like(t_var, dtype=tf.float32 ) for t_var in self.model.trainable_variables ]
self.optimizer.apply_gradients(zip(gradients, self.model.trainable_variables))
return [0]
with tf.GradientTape(persistent=False) as tape:
# non conditional continuous training
if self.m_params['model_type_settings']['discrete_continuous'] == False:
#making predictions
preds = self.model( feature, self.t_params['trainable'] ) #( bs, tar_seq_len, h, w)
preds = tf.squeeze( preds,axis=[-1] )
preds = cl.extract_central_region(preds, bounds)
mask = cl.extract_central_region(mask, bounds)
target = cl.extract_central_region(target, bounds)
#Applying mask
preds_masked = tf.boolean_mask( preds, mask )
target_masked = tf.boolean_mask( target, mask )
# reversing standardization
preds_masked = utility.standardize_ati( preds_masked, self.t_params['normalization_shift']['rain'], self.t_params['normalization_scales']['rain'], reverse=True)
# getting losses for records and/or optimizer
metric_mse = cl.mse(target_masked, preds_masked)
loss_to_optimize = metric_mse
# conditional continuous training
elif self.m_params['model_type_settings']['discrete_continuous'] == True:
# Producing predictions - conditional rain value and prob of rain
preds = self.model( feature, self.t_params['trainable'] ) # ( bs, seq_len, h, w, 1)
preds = tf.squeeze(preds, axis=[-1])
preds, probs = tf.unstack(preds, axis=0)
# extracting the central region of interest
preds = cl.extract_central_region(preds, bounds)
probs = cl.extract_central_region(probs, bounds)
mask = cl.extract_central_region(mask, bounds)
target = cl.extract_central_region(target, bounds)
# applying mask to predicted values
preds_masked = tf.boolean_mask(preds, mask )
probs_masked = tf.boolean_mask(probs, mask )
target_masked = tf.boolean_mask(target, mask )
# Reverising standardization of predictions
preds_masked = utility.standardize_ati( preds_masked, self.t_params['normalization_shift']['rain'],
self.t_params['normalization_scales']['rain'], reverse=True)
# Getting true labels and predicted labels for whether or not it rained [ 1 if if did rain, 0 if it did not rain]
labels_true = tf.where( target_masked > 0.0, 1.0, 0.0 )
labels_pred = probs_masked
all_count = tf.size( labels_true, out_type=tf.int64 )
# region Calculating Losses and Metrics
metric_mse = cl.mse( target_masked, cl.cond_rain(preds_masked, probs_masked, threshold=0.5) )
# To calculate metric_mse for CC model we assume that pred_rain=0 if pred_prob<=0.5
# CC Normal loss
loss_to_optimize = 0
loss_to_optimize += cl.mse( target_masked, preds_masked, all_count )
loss_to_optimize += tf.reduce_mean( tf.keras.backend.binary_crossentropy(labels_true, labels_pred, from_logits=False) )
# endregion
loss_to_optimize_agg = tf.grad_pass_through( lambda x: x/self.strategy_gpu_count )(loss_to_optimize)
scaled_loss = self.optimizer.get_scaled_loss( loss_to_optimize_agg )
scaled_gradients = tape.gradient( scaled_loss, self.model.trainable_variables )
unscaled_gradients = self.optimizer.get_unscaled_gradients(scaled_gradients)
gradients, _ = tf.clip_by_global_norm( unscaled_gradients, clip_norm=self.m_params['clip_norm'] ) #gradient clipping
self.optimizer.apply_gradients( zip(gradients, self.model.trainable_variables))
# Metrics (batchwise, epoch)
self.loss_agg_batch( loss_to_optimize )
self.loss_agg_epoch( loss_to_optimize )
self.mse_agg_epoch( metric_mse )
val = cl.rNmse(target_masked, preds_masked, 10.0)
return gradients
def val_step(self, feature, target, mask, bounds):
# Non CC distribution
if self.m_params['model_type_settings']['discrete_continuous'] == False:
# Get predictions
preds = self.model(feature, False )
preds = tf.squeeze(preds)
# Extracting central region for evaluation
preds = cl.extract_central_region(preds, bounds)
mask = cl.extract_central_region(mask, bounds)
target = cl.extract_central_region(target, bounds)
# Applying masks to predictions
preds_masked = tf.boolean_mask( preds, mask )
target_masked = tf.boolean_mask( target, mask )
preds_masked = utility.standardize_ati( preds_masked, self.t_params['normalization_shift']['rain'],
self.t_params['normalization_scales']['rain'], reverse=True)
# Updating losses
mse = cl.mse( target_masked , preds_masked )
loss = mse
# CC distribution
elif self.m_params['model_type_settings']['discrete_continuous'] == True:
# Get predictions
preds = self.model(feature, training=False )
preds = tf.squeeze(preds,axis=[-1])
preds, probs = tf.unstack(preds, axis=0)
# Extracting central region for evaluation
preds = cl.extract_central_region(preds, bounds)
probs = cl.extract_central_region(probs, bounds)
mask = cl.extract_central_region(mask, bounds)
target = cl.extract_central_region(target,bounds)
# Applying masks to predictions
preds_masked = tf.boolean_mask( preds, mask )
probs_masked = tf.boolean_mask( probs, mask)
target_masked = tf.boolean_mask( target, mask )
preds_masked = utility.standardize_ati( preds_masked, self.t_params['normalization_shift']['rain'],
self.t_params['normalization_scales']['rain'], reverse=True)
# Getting classification labels for whether or not it rained
labels_true = tf.where( target_masked > 0.0, 1.0, 0.0 )
labels_pred = probs_masked
all_count = tf.size( labels_true, out_type=tf.int64 )
# calculating seperate mse for reporting
# This mse metric assumes that if probability of rain is predicted below 0.5, the rain value is 0
mse = cl.mse( target_masked, cl.cond_rain( preds_masked, probs_masked, threshold=0.5) )
# Calculating cross entropy loss
loss = tf.reduce_mean( tf.keras.backend.binary_crossentropy( labels_true, labels_pred, from_logits=False) )
# Calculating conditinal continuous loss
loss += cl.mse( target_masked, preds_masked, all_count )
self.loss_agg_val(loss)
self.mse_agg_val(mse)
return True
@tf.function
def distributed_train_step(self, feature, target, mask, bounds, _init):
gradients = self.strategy.run( self.train_step, args=(feature, target, mask, bounds, _init) )
return gradients
@tf.function
def distributed_val_step(self, feature, target, mask, bounds):
bool_completed = self.strategy.run( self.val_step, args=(feature, target, mask, bounds))
return bool_completed
if __name__ == "__main__":
s_dir = utility.get_script_directory(sys.argv[0])
args_dict = utility.parse_arguments(s_dir)
# get training and model params
t_params, m_params = utility.load_params(args_dict)
# Initialize and train model
weather_model = WeatherModel(t_params, m_params)
weather_model.initialize_scheme_era5Eobs()
weather_model.train_model()
|
[
"tensorflow.unstack",
"tensorflow.train.Checkpoint",
"custom_losses.extract_central_region",
"tensorflow.boolean_mask",
"custom_losses.cond_rain",
"tensorflow.keras.backend.set_epsilon",
"utility.load_params",
"tensorflow_addons.optimizers.RectifiedAdam",
"tensorflow.GradientTape",
"models.model_loader",
"tensorflow.config.list_physical_devices",
"tensorflow.clip_by_global_norm",
"pandas.DataFrame",
"tensorflow.distribute.MirroredStrategy",
"tensorflow.train.CheckpointManager",
"utility.parse_arguments",
"tensorflow.zeros_like",
"tensorflow.size",
"tensorflow.zeros",
"tensorflow.keras.backend.binary_crossentropy",
"tensorflow.dtypes.as_dtype",
"custom_losses.rNmse",
"utility.update_checkpoints_epoch",
"tensorflow.keras.metrics.Mean",
"utility.standardize_ati",
"tensorflow.keras.backend.set_floatx",
"tensorflow.where",
"utility.cache_suffix_mkr",
"custom_losses.central_region_bounds",
"tensorflow.keras.mixed_precision.experimental.set_policy",
"time.time",
"custom_losses.mse",
"tensorflow.keras.mixed_precision.experimental.Policy",
"tensorflow.config.get_visible_devices",
"os.makedirs",
"data_generators.Era5_Eobs",
"utility.get_script_directory",
"tensorflow.mixed_precision.experimental.DynamicLossScale",
"numpy.cumsum",
"tensorflow.squeeze",
"tensorflow.grad_pass_through",
"tensorflow.config.experimental.list_physical_devices"
] |
[((593, 631), 'tensorflow.keras.backend.set_floatx', 'tf.keras.backend.set_floatx', (['"""float16"""'], {}), "('float16')\n", (620, 631), True, 'import tensorflow as tf\n'), ((633, 668), 'tensorflow.keras.backend.set_epsilon', 'tf.keras.backend.set_epsilon', (['(0.001)'], {}), '(0.001)\n', (661, 668), True, 'import tensorflow as tf\n'), ((841, 880), 'tensorflow.keras.mixed_precision.experimental.Policy', 'mixed_precision.Policy', (['"""mixed_float16"""'], {}), "('mixed_float16')\n", (863, 880), True, 'from tensorflow.keras.mixed_precision import experimental as mixed_precision\n'), ((882, 916), 'tensorflow.keras.mixed_precision.experimental.set_policy', 'mixed_precision.set_policy', (['policy'], {}), '(policy)\n', (908, 916), True, 'from tensorflow.keras.mixed_precision import experimental as mixed_precision\n'), ((695, 733), 'tensorflow.config.list_physical_devices', 'tf.config.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (726, 733), True, 'import tensorflow as tf\n'), ((1482, 1507), 'tensorflow.dtypes.as_dtype', 'tf.dtypes.as_dtype', (['other'], {}), '(other)\n', (1500, 1507), True, 'import tensorflow as tf\n'), ((26375, 26416), 'utility.get_script_directory', 'utility.get_script_directory', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (26403, 26416), False, 'import utility\n'), ((26434, 26464), 'utility.parse_arguments', 'utility.parse_arguments', (['s_dir'], {}), '(s_dir)\n', (26457, 26464), False, 'import utility\n'), ((26530, 26560), 'utility.load_params', 'utility.load_params', (['args_dict'], {}), '(args_dict)\n', (26549, 26560), False, 'import utility\n'), ((777, 828), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (821, 828), True, 'import tensorflow as tf\n'), ((2597, 2652), 'data_generators.Era5_Eobs', 'data_generators.Era5_Eobs', (['self.t_params', 'self.m_params'], {}), '(self.t_params, self.m_params)\n', (2622, 2652), False, 'import data_generators\n'), ((5065, 5096), 'tensorflow.config.get_visible_devices', 'tf.config.get_visible_devices', ([], {}), '()\n', (5094, 5096), True, 'import tensorflow as tf\n'), ((5386, 5418), 'tensorflow.distribute.MirroredStrategy', 'tf.distribute.MirroredStrategy', ([], {}), '()\n', (5416, 5418), True, 'import tensorflow as tf\n'), ((7061, 7110), 'os.makedirs', 'os.makedirs', (['checkpoint_path_epoch'], {'exist_ok': '(True)'}), '(checkpoint_path_epoch, exist_ok=True)\n', (7072, 7110), False, 'import os\n'), ((8634, 8683), 'utility.cache_suffix_mkr', 'utility.cache_suffix_mkr', (['m_params', 'self.t_params'], {}), '(m_params, self.t_params)\n', (8658, 8683), False, 'import utility\n'), ((8695, 8743), 'os.makedirs', 'os.makedirs', (['"""./Data/data_cache/"""'], {'exist_ok': '(True)'}), "('./Data/data_cache/', exist_ok=True)\n", (8706, 8743), False, 'import os\n'), ((10044, 10093), 'numpy.cumsum', 'np.cumsum', (['([bc_ds_in_train] * era5_eobs.loc_count)'], {}), '([bc_ds_in_train] * era5_eobs.loc_count)\n', (10053, 10093), True, 'import numpy as np\n'), ((10132, 10179), 'numpy.cumsum', 'np.cumsum', (['([bc_ds_in_val] * era5_eobs.loc_count)'], {}), '([bc_ds_in_val] * era5_eobs.loc_count)\n', (10141, 10179), True, 'import numpy as np\n'), ((10513, 10574), 'custom_losses.central_region_bounds', 'cl.central_region_bounds', (["self.m_params['region_grid_params']"], {}), "(self.m_params['region_grid_params'])\n", (10537, 10574), True, 'import custom_losses as cl\n'), ((22586, 22629), 'custom_losses.rNmse', 'cl.rNmse', (['target_masked', 'preds_masked', '(10.0)'], {}), '(target_masked, preds_masked, 10.0)\n', (22594, 22629), True, 'import custom_losses as cl\n'), ((5860, 5909), 'models.model_loader', 'models.model_loader', (['self.t_params', 'self.m_params'], {}), '(self.t_params, self.m_params)\n', (5879, 5909), False, 'import models\n'), ((5975, 6092), 'tensorflow_addons.optimizers.RectifiedAdam', 'tfa.optimizers.RectifiedAdam', ([], {'total_steps': "(self.t_params['train_batches'] * 20)"}), "(**self.m_params['rec_adam_params'],\n total_steps=self.t_params['train_batches'] * 20)\n", (6003, 6092), True, 'import tensorflow_addons as tfa\n'), ((6379, 6423), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""loss_agg_batch"""'}), "(name='loss_agg_batch')\n", (6400, 6423), True, 'import tensorflow as tf\n'), ((6460, 6504), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""loss_agg_epoch"""'}), "(name='loss_agg_epoch')\n", (6481, 6504), True, 'import tensorflow as tf\n'), ((6541, 6584), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""mse_agg_epoch"""'}), "(name='mse_agg_epoch')\n", (6562, 6584), True, 'import tensorflow as tf\n'), ((6632, 6674), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""loss_agg_val"""'}), "(name='loss_agg_val')\n", (6653, 6674), True, 'import tensorflow as tf\n'), ((6707, 6748), 'tensorflow.keras.metrics.Mean', 'tf.keras.metrics.Mean', ([], {'name': '"""mse_agg_val"""'}), "(name='mse_agg_val')\n", (6728, 6748), True, 'import tensorflow as tf\n'), ((7183, 7246), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'model': 'self.model', 'optimizer': 'self.optimizer'}), '(model=self.model, optimizer=self.optimizer)\n', (7202, 7246), True, 'import tensorflow as tf\n'), ((7283, 7435), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['ckpt_epoch', 'checkpoint_path_epoch'], {'max_to_keep': "self.t_params['checkpoints_to_keep']", 'keep_checkpoint_every_n_hours': 'None'}), "(ckpt_epoch, checkpoint_path_epoch, max_to_keep=\n self.t_params['checkpoints_to_keep'], keep_checkpoint_every_n_hours=None)\n", (7309, 7435), True, 'import tensorflow as tf\n'), ((11673, 11684), 'time.time', 'time.time', ([], {}), '()\n', (11682, 11684), False, 'import time\n'), ((11723, 11734), 'time.time', 'time.time', ([], {}), '()\n', (11732, 11734), False, 'import time\n'), ((14610, 14621), 'time.time', 'time.time', ([], {}), '()\n', (14619, 14621), False, 'import time\n'), ((16514, 16748), 'utility.update_checkpoints_epoch', 'utility.update_checkpoints_epoch', (['self.df_training_info', 'epoch', 'self.loss_agg_epoch', 'self.loss_agg_val', 'self.ckpt_mngr_epoch', 'self.t_params', 'self.m_params', 'self.mse_agg_epoch', 'self.mse_agg_val', "self.t_params['objective']"], {}), "(self.df_training_info, epoch, self.\n loss_agg_epoch, self.loss_agg_val, self.ckpt_mngr_epoch, self.t_params,\n self.m_params, self.mse_agg_epoch, self.mse_agg_val, self.t_params[\n 'objective'])\n", (16546, 16748), False, 'import utility\n'), ((18113, 18146), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {'persistent': '(False)'}), '(persistent=False)\n', (18128, 18146), True, 'import tensorflow as tf\n'), ((22172, 22257), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['unscaled_gradients'], {'clip_norm': "self.m_params['clip_norm']"}), "(unscaled_gradients, clip_norm=self.m_params['clip_norm']\n )\n", (22194, 22257), True, 'import tensorflow as tf\n'), ((22994, 23011), 'tensorflow.squeeze', 'tf.squeeze', (['preds'], {}), '(preds)\n', (23004, 23011), True, 'import tensorflow as tf\n'), ((23093, 23133), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['preds', 'bounds'], {}), '(preds, bounds)\n', (23118, 23133), True, 'import custom_losses as cl\n'), ((23157, 23196), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['mask', 'bounds'], {}), '(mask, bounds)\n', (23182, 23196), True, 'import custom_losses as cl\n'), ((23220, 23261), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['target', 'bounds'], {}), '(target, bounds)\n', (23245, 23261), True, 'import custom_losses as cl\n'), ((23349, 23377), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['preds', 'mask'], {}), '(preds, mask)\n', (23364, 23377), True, 'import tensorflow as tf\n'), ((23409, 23438), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['target', 'mask'], {}), '(target, mask)\n', (23424, 23438), True, 'import tensorflow as tf\n'), ((23469, 23618), 'utility.standardize_ati', 'utility.standardize_ati', (['preds_masked', "self.t_params['normalization_shift']['rain']", "self.t_params['normalization_scales']['rain']"], {'reverse': '(True)'}), "(preds_masked, self.t_params['normalization_shift'][\n 'rain'], self.t_params['normalization_scales']['rain'], reverse=True)\n", (23492, 23618), False, 'import utility\n'), ((23719, 23754), 'custom_losses.mse', 'cl.mse', (['target_masked', 'preds_masked'], {}), '(target_masked, preds_masked)\n', (23725, 23754), True, 'import custom_losses as cl\n'), ((4646, 4772), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Epoch', 'Train_loss', 'Train_mse', 'Val_loss', 'Val_mse',\n 'Checkpoint_Path', 'Last_Trained_Batch']"}), "(columns=['Epoch', 'Train_loss', 'Train_mse', 'Val_loss',\n 'Val_mse', 'Checkpoint_Path', 'Last_Trained_Batch'])\n", (4658, 4772), True, 'import pandas as pd\n'), ((17767, 17804), 'tensorflow.zeros', 'tf.zeros', (['inp_shape'], {'dtype': 'tf.float16'}), '(inp_shape, dtype=tf.float16)\n', (17775, 17804), True, 'import tensorflow as tf\n'), ((17894, 17932), 'tensorflow.zeros_like', 'tf.zeros_like', (['t_var'], {'dtype': 'tf.float32'}), '(t_var, dtype=tf.float32)\n', (17907, 17932), True, 'import tensorflow as tf\n'), ((18511, 18539), 'tensorflow.squeeze', 'tf.squeeze', (['preds'], {'axis': '[-1]'}), '(preds, axis=[-1])\n', (18521, 18539), True, 'import tensorflow as tf\n'), ((18588, 18628), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['preds', 'bounds'], {}), '(preds, bounds)\n', (18613, 18628), True, 'import custom_losses as cl\n'), ((18656, 18695), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['mask', 'bounds'], {}), '(mask, bounds)\n', (18681, 18695), True, 'import custom_losses as cl\n'), ((18723, 18764), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['target', 'bounds'], {}), '(target, bounds)\n', (18748, 18764), True, 'import custom_losses as cl\n'), ((18831, 18859), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['preds', 'mask'], {}), '(preds, mask)\n', (18846, 18859), True, 'import tensorflow as tf\n'), ((18895, 18924), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['target', 'mask'], {}), '(target, mask)\n', (18910, 18924), True, 'import tensorflow as tf\n'), ((19007, 19156), 'utility.standardize_ati', 'utility.standardize_ati', (['preds_masked', "self.t_params['normalization_shift']['rain']", "self.t_params['normalization_scales']['rain']"], {'reverse': '(True)'}), "(preds_masked, self.t_params['normalization_shift'][\n 'rain'], self.t_params['normalization_scales']['rain'], reverse=True)\n", (19030, 19156), False, 'import utility\n'), ((19248, 19283), 'custom_losses.mse', 'cl.mse', (['target_masked', 'preds_masked'], {}), '(target_masked, preds_masked)\n', (19254, 19283), True, 'import custom_losses as cl\n'), ((21785, 21844), 'tensorflow.grad_pass_through', 'tf.grad_pass_through', (['(lambda x: x / self.strategy_gpu_count)'], {}), '(lambda x: x / self.strategy_gpu_count)\n', (21805, 21844), True, 'import tensorflow as tf\n'), ((24035, 24063), 'tensorflow.squeeze', 'tf.squeeze', (['preds'], {'axis': '[-1]'}), '(preds, axis=[-1])\n', (24045, 24063), True, 'import tensorflow as tf\n'), ((24091, 24116), 'tensorflow.unstack', 'tf.unstack', (['preds'], {'axis': '(0)'}), '(preds, axis=0)\n', (24101, 24116), True, 'import tensorflow as tf\n'), ((24208, 24248), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['preds', 'bounds'], {}), '(preds, bounds)\n', (24233, 24248), True, 'import custom_losses as cl\n'), ((24272, 24312), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['probs', 'bounds'], {}), '(probs, bounds)\n', (24297, 24312), True, 'import custom_losses as cl\n'), ((24336, 24375), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['mask', 'bounds'], {}), '(mask, bounds)\n', (24361, 24375), True, 'import custom_losses as cl\n'), ((24400, 24441), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['target', 'bounds'], {}), '(target, bounds)\n', (24425, 24441), True, 'import custom_losses as cl\n'), ((24519, 24547), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['preds', 'mask'], {}), '(preds, mask)\n', (24534, 24547), True, 'import tensorflow as tf\n'), ((24581, 24609), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['probs', 'mask'], {}), '(probs, mask)\n', (24596, 24609), True, 'import tensorflow as tf\n'), ((24642, 24671), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['target', 'mask'], {}), '(target, mask)\n', (24657, 24671), True, 'import tensorflow as tf\n'), ((24705, 24854), 'utility.standardize_ati', 'utility.standardize_ati', (['preds_masked', "self.t_params['normalization_shift']['rain']", "self.t_params['normalization_scales']['rain']"], {'reverse': '(True)'}), "(preds_masked, self.t_params['normalization_shift'][\n 'rain'], self.t_params['normalization_scales']['rain'], reverse=True)\n", (24728, 24854), False, 'import utility\n'), ((25022, 25061), 'tensorflow.where', 'tf.where', (['(target_masked > 0.0)', '(1.0)', '(0.0)'], {}), '(target_masked > 0.0, 1.0, 0.0)\n', (25030, 25061), True, 'import tensorflow as tf\n'), ((25132, 25171), 'tensorflow.size', 'tf.size', (['labels_true'], {'out_type': 'tf.int64'}), '(labels_true, out_type=tf.int64)\n', (25139, 25171), True, 'import tensorflow as tf\n'), ((25721, 25767), 'custom_losses.mse', 'cl.mse', (['target_masked', 'preds_masked', 'all_count'], {}), '(target_masked, preds_masked, all_count)\n', (25727, 25767), True, 'import custom_losses as cl\n'), ((6179, 6229), 'tensorflow.mixed_precision.experimental.DynamicLossScale', 'tf.mixed_precision.experimental.DynamicLossScale', ([], {}), '()\n', (6227, 6229), True, 'import tensorflow as tf\n'), ((13121, 13132), 'time.time', 'time.time', ([], {}), '()\n', (13130, 13132), False, 'import time\n'), ((15712, 15723), 'time.time', 'time.time', ([], {}), '()\n', (15721, 15723), False, 'import time\n'), ((19707, 19735), 'tensorflow.squeeze', 'tf.squeeze', (['preds'], {'axis': '[-1]'}), '(preds, axis=[-1])\n', (19717, 19735), True, 'import tensorflow as tf\n'), ((19768, 19793), 'tensorflow.unstack', 'tf.unstack', (['preds'], {'axis': '(0)'}), '(preds, axis=0)\n', (19778, 19793), True, 'import tensorflow as tf\n'), ((19899, 19939), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['preds', 'bounds'], {}), '(preds, bounds)\n', (19924, 19939), True, 'import custom_losses as cl\n'), ((19967, 20007), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['probs', 'bounds'], {}), '(probs, bounds)\n', (19992, 20007), True, 'import custom_losses as cl\n'), ((20035, 20074), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['mask', 'bounds'], {}), '(mask, bounds)\n', (20060, 20074), True, 'import custom_losses as cl\n'), ((20102, 20143), 'custom_losses.extract_central_region', 'cl.extract_central_region', (['target', 'bounds'], {}), '(target, bounds)\n', (20127, 20143), True, 'import custom_losses as cl\n'), ((20234, 20262), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['preds', 'mask'], {}), '(preds, mask)\n', (20249, 20262), True, 'import tensorflow as tf\n'), ((20299, 20327), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['probs', 'mask'], {}), '(probs, mask)\n', (20314, 20327), True, 'import tensorflow as tf\n'), ((20365, 20394), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['target', 'mask'], {}), '(target, mask)\n', (20380, 20394), True, 'import tensorflow as tf\n'), ((20511, 20660), 'utility.standardize_ati', 'utility.standardize_ati', (['preds_masked', "self.t_params['normalization_shift']['rain']", "self.t_params['normalization_scales']['rain']"], {'reverse': '(True)'}), "(preds_masked, self.t_params['normalization_shift'][\n 'rain'], self.t_params['normalization_scales']['rain'], reverse=True)\n", (20534, 20660), False, 'import utility\n'), ((20936, 20975), 'tensorflow.where', 'tf.where', (['(target_masked > 0.0)', '(1.0)', '(0.0)'], {}), '(target_masked > 0.0, 1.0, 0.0)\n', (20944, 20975), True, 'import tensorflow as tf\n'), ((21054, 21093), 'tensorflow.size', 'tf.size', (['labels_true'], {'out_type': 'tf.int64'}), '(labels_true, out_type=tf.int64)\n', (21061, 21093), True, 'import tensorflow as tf\n'), ((21519, 21565), 'custom_losses.mse', 'cl.mse', (['target_masked', 'preds_masked', 'all_count'], {}), '(target_masked, preds_masked, all_count)\n', (21525, 21565), True, 'import custom_losses as cl\n'), ((25387, 25442), 'custom_losses.cond_rain', 'cl.cond_rain', (['preds_masked', 'probs_masked'], {'threshold': '(0.5)'}), '(preds_masked, probs_masked, threshold=0.5)\n', (25399, 25442), True, 'import custom_losses as cl\n'), ((25556, 25642), 'tensorflow.keras.backend.binary_crossentropy', 'tf.keras.backend.binary_crossentropy', (['labels_true', 'labels_pred'], {'from_logits': '(False)'}), '(labels_true, labels_pred, from_logits=\n False)\n', (25592, 25642), True, 'import tensorflow as tf\n'), ((12506, 12517), 'time.time', 'time.time', ([], {}), '()\n', (12515, 12517), False, 'import time\n'), ((15155, 15166), 'time.time', 'time.time', ([], {}), '()\n', (15164, 15166), False, 'import time\n'), ((16226, 16237), 'time.time', 'time.time', ([], {}), '()\n', (16235, 16237), False, 'import time\n'), ((21241, 21296), 'custom_losses.cond_rain', 'cl.cond_rain', (['preds_masked', 'probs_masked'], {'threshold': '(0.5)'}), '(preds_masked, probs_masked, threshold=0.5)\n', (21253, 21296), True, 'import custom_losses as cl\n'), ((21625, 21711), 'tensorflow.keras.backend.binary_crossentropy', 'tf.keras.backend.binary_crossentropy', (['labels_true', 'labels_pred'], {'from_logits': '(False)'}), '(labels_true, labels_pred, from_logits=\n False)\n', (21661, 21711), True, 'import tensorflow as tf\n')]
|
import numpy as np
from numpy.random import seed
seed(1)
import pandas as pd
from math import sqrt
from sklearn.decomposition import PCA
######################################################################
# METRICS
######################################################################
def mse(y, y_hat):
"""
Calculates Mean Squared Error.
MSE measures the prediction accuracy of a
forecasting method by calculating the squared deviation
of the prediction and the true value at a given time and
averages these devations over the length of the series.
y: numpy array
actual test values
y_hat: numpy array
predicted values
return: MSE
"""
mse = np.mean(np.square(y - y_hat))
return mse
def rmse(y, y_hat):
"""
Calculates Root Mean Squared Error.
RMSE measures the prediction accuracy of a
forecasting method by calculating the squared deviation
of the prediction and the true value at a given time and
averages these devations over the length of the series.
Finally the RMSE will be in the same scale
as the original time series so its comparison with other
series is possible only if they share a common scale.
y: numpy array
actual test values
y_hat: numpy array
predicted values
return: RMSE
"""
rmse = sqrt(np.mean(np.square(y - y_hat)))
return rmse
def mape(y, y_hat):
"""
Calculates Mean Absolute Percentage Error.
MAPE measures the relative prediction accuracy of a
forecasting method by calculating the percentual deviation
of the prediction and the true value at a given time and
averages these devations over the length of the series.
y: numpy array
actual test values
y_hat: numpy array
predicted values
return: MAPE
"""
mape = np.mean(np.abs(y - y_hat) / np.abs(y))
mape = 100 * mape
return mape
def smape(y, y_hat):
"""
Calculates Symmetric Mean Absolute Percentage Error.
SMAPE measures the relative prediction accuracy of a
forecasting method by calculating the relative deviation
of the prediction and the true value scaled by the sum of the
absolute values for the prediction and true value at a
given time, then averages these devations over the length
of the series. This allows the SMAPE to have bounds between
0% and 200% which is desireble compared to normal MAPE that
may be undetermined.
y: numpy array
actual test values
y_hat: numpy array
predicted values
return: SMAPE
"""
smape = np.mean(np.abs(y - y_hat) / (np.abs(y) + np.abs(y_hat)))
smape = 200 * smape
return smape
def mase(y, y_hat, y_train, seasonality=1):
"""
Calculates the M4 Mean Absolute Scaled Error.
MASE measures the relative prediction accuracy of a
forecasting method by comparinng the mean absolute errors
of the prediction and the true value against the mean
absolute errors of the seasonal naive model.
y: numpy array
actual test values
y_hat: numpy array
predicted values
y_train: numpy array
actual train values for Naive1 predictions
seasonality: int
main frequency of the time series
Hourly 24, Daily 7, Weekly 52,
Monthly 12, Quarterly 4, Yearly 1
return: MASE
"""
scale = np.mean(abs(y_train[seasonality:] - y_train[:-seasonality]))
mase = np.mean(abs(y - y_hat)) / scale
mase = 100 * mase
return mase
def rmsse(y, y_hat, y_train, seasonality=1):
"""
Calculates the M5 Root Mean Squared Scaled Error.
Calculates the M4 Mean Absolute Scaled Error.
MASE measures the relative prediction accuracy of a
forecasting method by comparinng the mean squared errors
of the prediction and the true value against the mean
squared errors of the seasonal naive model.
y: numpy array
actual test values
y_hat: numpy array of len h (forecasting horizon)
predicted values
seasonality: int
main frequency of the time series
Hourly 24, Daily 7, Weekly 52,
Monthly 12, Quarterly 4, Yearly 1
return: RMSSE
"""
scale = np.mean(np.square(y_train[seasonality:] - y_train[:-seasonality]))
rmsse = sqrt(mse(y, y_hat) / scale)
rmsse = 100 * rmsse
return rmsse
def pinball_loss(y, y_hat, tau=0.5):
"""
Calculates the Pinball Loss.
The Pinball loss measures the deviation of a quantile forecast.
By weighting the absolute deviation in a non symmetric way, the
loss pays more attention to under or over estimation.
A common value for tau is 0.5 for the deviation from the median.
y: numpy array
actual test values
y_hat: numpy array of len h (forecasting horizon)
predicted values
tau: float
Fixes the quantile against which the predictions are compared.
return: pinball_loss
"""
delta_y = y - y_hat
pinball = np.maximum(tau * delta_y, (tau-1) * delta_y)
pinball = pinball.mean()
return pinball_loss
def evaluate_panel(y_test, y_hat, y_train,
metric, seasonality):
"""
Calculates a specific metric for y and y_hat
y_test: pandas df
df with columns unique_id, ds, y
y_hat: pandas df
df with columns unique_id, ds, y_hat
y_train: pandas df
df with columns unique_id, ds, y (train)
this is used in the scaled metrics
seasonality: int
main frequency of the time series
Hourly 24, Daily 7, Weekly 52,
Monthly 12, Quarterly 4, Yearly 1
return: list of metric evaluations for each unique_id
in the panel data
"""
metric_name = metric.__code__.co_name
uids = y_test.index.get_level_values('unique_id').unique()
y_hat_uids = y_hat.index.get_level_values('unique_id').unique()
assert len(y_test)==len(y_hat), "not same length"
assert all(uids == y_hat_uids), "not same u_ids"
idxs, evaluations = [], []
for uid in uids:
y_test_uid = y_test.loc[uid].values
y_hat_uid = y_hat.loc[uid].values
y_train_uid = y_train.loc[uid].y.values
if metric_name in ['mase', 'rmsse']:
evaluation_uid = metric(y=y_test_uid, y_hat=y_hat_uid,
y_train=y_train_uid, seasonality=seasonality)
else:
evaluation_uid = metric(y=y_test_uid, y_hat=y_hat_uid)
idxs.append(uid)
evaluations.append(evaluation_uid)
idxs = pd.Index(idxs, name='unique_id')
evaluations = pd.Series(evaluations, index=idxs)
return evaluations
def compute_evaluations(y_test, y_hat, y_train, metrics, seasonality): #, progress_bar
"""
Calculates all metrics in list for y and y_hat panel data,
and creates rank based on PCA dimensionality reduction.
y_test: pandas df
df with columns unique_id, ds, y
y_hat: pandas df
df with columns unique_id, ds, y_hat
y_train: pandas df
df with columns unique_id, ds, y (train)
this is used in the scaled metrics
metrics: list
list of strings containing all metrics to compute
seasonality: int
main frequency of the time series
Hourly 24, Daily 7, Weekly 52,
Monthly 12, Quarterly 4, Yearly 1
return: list of metric evaluations
"""
print("\n Evaluating models")
evaluations = {}
for metric_name, metric in metrics.items():
print(metric_name)
for col in y_hat.columns:
mod_evaluation = evaluate_panel(y_test=y_test, y_hat=y_hat[col],
y_train=y_train, metric=metric,
seasonality=seasonality)
mod_evaluation.name = y_hat[col].name
if not (metric_name in evaluations.keys()):
evaluations[metric_name] = [mod_evaluation]
else:
evaluations[metric_name].append(mod_evaluation)
#progress_bar['value']+=1
#progress_bar.update()
# Collapse Metrics
for metric_name, metric in metrics.items():
evaluations[metric_name] = pd.concat(evaluations[metric_name], axis=1)
evaluations[metric_name] = evaluations[metric_name].mean(axis=0)
evaluations = pd.DataFrame.from_dict(evaluations)
# PCA rank
X = evaluations.values
pca = PCA(n_components=1)
pca.fit(X)
evaluations['pca_rank'] = pca.fit_transform(X)
evaluations['pca_rank'] = evaluations['pca_rank'].rank(ascending=False)
evaluations['pca_rank'] = evaluations['pca_rank'].astype(int)
evaluations.sort_values(by='pca_rank', inplace=True)
evaluations.reset_index(inplace=True)
evaluations.rename(columns={'index': 'model'}, inplace=True)
return evaluations
|
[
"pandas.Series",
"numpy.abs",
"sklearn.decomposition.PCA",
"pandas.DataFrame.from_dict",
"numpy.square",
"pandas.Index",
"numpy.random.seed",
"numpy.maximum",
"pandas.concat"
] |
[((49, 56), 'numpy.random.seed', 'seed', (['(1)'], {}), '(1)\n', (53, 56), False, 'from numpy.random import seed\n'), ((4958, 5004), 'numpy.maximum', 'np.maximum', (['(tau * delta_y)', '((tau - 1) * delta_y)'], {}), '(tau * delta_y, (tau - 1) * delta_y)\n', (4968, 5004), True, 'import numpy as np\n'), ((6497, 6529), 'pandas.Index', 'pd.Index', (['idxs'], {'name': '"""unique_id"""'}), "(idxs, name='unique_id')\n", (6505, 6529), True, 'import pandas as pd\n'), ((6548, 6582), 'pandas.Series', 'pd.Series', (['evaluations'], {'index': 'idxs'}), '(evaluations, index=idxs)\n', (6557, 6582), True, 'import pandas as pd\n'), ((8268, 8303), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['evaluations'], {}), '(evaluations)\n', (8290, 8303), True, 'import pandas as pd\n'), ((8361, 8380), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(1)'}), '(n_components=1)\n', (8364, 8380), False, 'from sklearn.decomposition import PCA\n'), ((717, 737), 'numpy.square', 'np.square', (['(y - y_hat)'], {}), '(y - y_hat)\n', (726, 737), True, 'import numpy as np\n'), ((4198, 4255), 'numpy.square', 'np.square', (['(y_train[seasonality:] - y_train[:-seasonality])'], {}), '(y_train[seasonality:] - y_train[:-seasonality])\n', (4207, 4255), True, 'import numpy as np\n'), ((8128, 8171), 'pandas.concat', 'pd.concat', (['evaluations[metric_name]'], {'axis': '(1)'}), '(evaluations[metric_name], axis=1)\n', (8137, 8171), True, 'import pandas as pd\n'), ((1360, 1380), 'numpy.square', 'np.square', (['(y - y_hat)'], {}), '(y - y_hat)\n', (1369, 1380), True, 'import numpy as np\n'), ((1852, 1869), 'numpy.abs', 'np.abs', (['(y - y_hat)'], {}), '(y - y_hat)\n', (1858, 1869), True, 'import numpy as np\n'), ((1872, 1881), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (1878, 1881), True, 'import numpy as np\n'), ((2606, 2623), 'numpy.abs', 'np.abs', (['(y - y_hat)'], {}), '(y - y_hat)\n', (2612, 2623), True, 'import numpy as np\n'), ((2627, 2636), 'numpy.abs', 'np.abs', (['y'], {}), '(y)\n', (2633, 2636), True, 'import numpy as np\n'), ((2639, 2652), 'numpy.abs', 'np.abs', (['y_hat'], {}), '(y_hat)\n', (2645, 2652), True, 'import numpy as np\n')]
|
# Copyright 2015 Google Inc. 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.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from src.exp.bboxes import read_images
def read_batches_of_clips(paths, batch_size, num_frames_per_clip=16, stride=8, resize_size=112):
clips = []
names = []
for clip, name in read_clips(paths, num_frames_per_clip, stride, resize_size):
if len(clip) >= batch_size:
yield np.array(clips), names
clips.append(clip)
names.append(name)
def read_clips(paths, num_frames_per_clip, stride, resize_size):
assert stride < num_frames_per_clip, "stride < num_frames_per_clip"
for path in paths:
vc = cv2.VideoCapture(path)
clip = []
first_frame_n = 0
for frame in read_images(vc):
if len(clip) >= num_frames_per_clip:
yield np.array(clip).astype(np.float32), (path, first_frame_n)
clip = clip[:num_frames_per_clip - stride]
first_frame_n += stride
img = np.array(cv2.resize(np.array(frame), (resize_size, resize_size))).astype(np.float32)
clip.append(img)
# if piece of clip remains then pad it
if len(clip) > 0:
for frame in range(len(clip), num_frames_per_clip):
clip[frame] = clip[-1]
yield np.array(clip).astype(np.float32), (path, first_frame_n)
|
[
"numpy.array",
"src.exp.bboxes.read_images",
"cv2.VideoCapture"
] |
[((1432, 1454), 'cv2.VideoCapture', 'cv2.VideoCapture', (['path'], {}), '(path)\n', (1448, 1454), False, 'import cv2\n'), ((1520, 1535), 'src.exp.bboxes.read_images', 'read_images', (['vc'], {}), '(vc)\n', (1531, 1535), False, 'from src.exp.bboxes import read_images\n'), ((1180, 1195), 'numpy.array', 'np.array', (['clips'], {}), '(clips)\n', (1188, 1195), True, 'import numpy as np\n'), ((1802, 1817), 'numpy.array', 'np.array', (['frame'], {}), '(frame)\n', (1810, 1817), True, 'import numpy as np\n'), ((2090, 2104), 'numpy.array', 'np.array', (['clip'], {}), '(clip)\n', (2098, 2104), True, 'import numpy as np\n'), ((1608, 1622), 'numpy.array', 'np.array', (['clip'], {}), '(clip)\n', (1616, 1622), True, 'import numpy as np\n')]
|
"""
This module is the computational part of the geometrical module of ToFu
"""
# Built-in
import sys
import warnings
# Common
import numpy as np
import scipy.interpolate as scpinterp
import scipy.integrate as scpintg
if sys.version[0]=='3':
from inspect import signature as insp
elif sys.version[0]=='2':
from inspect import getargspec as insp
# ToFu-specific
try:
import tofu.geom._def as _def
import tofu.geom._GG as _GG
except Exception:
from . import _def as _def
from . import _GG as _GG
"""
###############################################################################
###############################################################################
Ves functions
###############################################################################
"""
############################################
##### Ves sub-functions
############################################
def _Struct_set_Poly(Poly, pos=None, extent=None, arrayorder='C',
Type='Tor', Clock=False):
""" Compute geometrical attributes of a Struct object """
# Make Poly closed, counter-clockwise, with '(cc,N)' layout and arrayorder
Poly = _GG.Poly_Order(Poly, order='C', Clock=False,
close=True, layout='(cc,N)', Test=True)
assert Poly.shape[0]==2, "Arg Poly must be a 2D polygon !"
fPfmt = np.ascontiguousarray if arrayorder=='C' else np.asfortranarray
# Get all remarkable points and moments
NP = Poly.shape[1]-1
P1Max = Poly[:,np.argmax(Poly[0,:])]
P1Min = Poly[:,np.argmin(Poly[0,:])]
P2Max = Poly[:,np.argmax(Poly[1,:])]
P2Min = Poly[:,np.argmin(Poly[1,:])]
BaryP = np.sum(Poly[:,:-1],axis=1,keepdims=False)/(Poly.shape[1]-1)
BaryL = np.array([(P1Max[0]+P1Min[0])/2., (P2Max[1]+P2Min[1])/2.])
BaryS, Surf = _GG.poly_area_and_barycenter(Poly, NP)
# Get lim-related indicators
noccur = int(pos.size)
Multi = noccur>1
# Get Tor-related quantities
if Type.lower()=='lin':
Vol, BaryV = None, None
else:
Vol, BaryV = _GG.Poly_VolAngTor(Poly)
msg = "Pb. with volume computation for Ves object of type 'Tor' !"
assert Vol>0., msg
# Compute the non-normalized vector of each side of the Poly
Vect = np.diff(Poly,n=1,axis=1)
Vect = fPfmt(Vect)
# Compute the normalised vectors directed inwards
Vin = np.array([Vect[1,:],-Vect[0,:]])
Vin = -Vin # Poly is Counter Clock-wise as defined above
Vin = Vin/np.hypot(Vin[0,:],Vin[1,:])[np.newaxis,:]
Vin = fPfmt(Vin)
poly = _GG.Poly_Order(Poly, order=arrayorder, Clock=Clock,
close=False, layout='(cc,N)', Test=True)
# Get bounding circle
circC = BaryS
r = np.sqrt(np.sum((poly-circC[:,np.newaxis])**2,axis=0))
circr = np.max(r)
dout = {'Poly':poly, 'pos':pos, 'extent':extent,
'noccur':noccur, 'Multi':Multi, 'nP':NP,
'P1Max':P1Max, 'P1Min':P1Min, 'P2Max':P2Max, 'P2Min':P2Min,
'BaryP':BaryP, 'BaryL':BaryL, 'BaryS':BaryS, 'BaryV':BaryV,
'Surf':Surf, 'VolAng':Vol, 'Vect':Vect, 'VIn':Vin,
'circ-C':circC, 'circ-r':circr, 'Clock':Clock}
return dout
def _Ves_get_InsideConvexPoly(Poly, P2Min, P2Max, BaryS, RelOff=_def.TorRelOff, ZLim='Def', Spline=True, Splprms=_def.TorSplprms, NP=_def.TorInsideNP, Plot=False, Test=True):
if Test:
assert type(RelOff) is float, "Arg RelOff must be a float"
assert ZLim is None or ZLim=='Def' or type(ZLim) in [tuple,list], "Arg ZLim must be a tuple (ZlimMin, ZLimMax)"
assert type(Spline) is bool, "Arg Spline must be a bool !"
if not ZLim is None:
if ZLim=='Def':
ZLim = (P2Min[1]+0.1*(P2Max[1]-P2Min[1]), P2Max[1]-0.05*(P2Max[1]-P2Min[1]))
indZLim = (Poly[1,:]<ZLim[0]) | (Poly[1,:]>ZLim[1])
if Poly.shape[1]-indZLim.sum()<10:
msg = "Poly seems to be Convex and simple enough !"
msg += "\n Poly.shape[1] - indZLim.sum() < 10"
warnings.warn(msg)
return Poly
Poly = np.delete(Poly, indZLim.nonzero()[0], axis=1)
if np.all(Poly[:,0]==Poly[:,-1]):
Poly = Poly[:,:-1]
Np = Poly.shape[1]
if Spline:
BarySbis = np.tile(BaryS,(Np,1)).T
Ptemp = (1.-RelOff)*(Poly-BarySbis)
#Poly = BarySbis + Ptemp
Ang = np.arctan2(Ptemp[1,:],Ptemp[0,:])
Ang, ind = np.unique(Ang, return_index=True)
Ptemp = Ptemp[:,ind]
# spline parameters
ww = Splprms[0]*np.ones((Np+1,))
ss = Splprms[1]*(Np+1) # smoothness parameter
kk = Splprms[2] # spline order
nest = int((Np+1)/2.) # estimate of number of knots needed (-1 = maximal)
# Find the knot points
#tckp,uu = scpinterp.splprep([np.append(Ptemp[0,:],Ptemp[0,0]),np.append(Ptemp[1,:],Ptemp[1,0]),np.append(Ang,Ang[0]+2.*np.pi)], w=ww, s=ss, k=kk, nest=nest)
tckp,uu = scpinterp.splprep([np.append(Ptemp[0,:],Ptemp[0,0]),np.append(Ptemp[1,:],Ptemp[1,0])], u=np.append(Ang,Ang[0]+2.*np.pi), w=ww, s=ss, k=kk, nest=nest, full_output=0)
xnew,ynew = scpinterp.splev(np.linspace(-np.pi,np.pi,NP),tckp)
Poly = np.array([xnew+BaryS[0],ynew+BaryS[1]])
Poly = np.concatenate((Poly,Poly[:,0:1]),axis=1)
if Plot:
f = plt.figure(facecolor='w',figsize=(8,10))
ax = f.add_axes([0.1,0.1,0.8,0.8])
ax.plot(Poly[0,:], Poly[1,:],'-k', Poly[0,:],Poly[1,:],'-r')
ax.set_aspect(aspect="equal",adjustable='datalim'), ax.set_xlabel(r"R (m)"), ax.set_ylabel(r"Z (m)")
f.canvas.draw()
return Poly
def _Ves_get_sampleEdge(VPoly, dL, DS=None, dLMode='abs', DIn=0., VIn=None,
margin=1.e-9):
types =[int,float,np.int32,np.int64,np.float32,np.float64]
assert type(dL) in types and type(DIn) in types
assert DS is None or (hasattr(DS,'__iter__') and len(DS)==2)
if DS is None:
DS = [None,None]
else:
assert all([ds is None or (hasattr(ds,'__iter__') and len(ds)==2 and
all([ss is None or type(ss) in types
for ss in ds])) for ds in DS])
assert (type(dLMode) is str and
dLMode.lower() in ['abs','rel']), "Arg dLMode must be in ['abs','rel'] !"
#assert ind is None or (type(ind) is np.ndarray and ind.ndim==1 and ind.dtype in ['int32','int64'] and np.all(ind>=0)), "Arg ind must be None or 1D np.ndarray of positive int !"
Pts, dLr, ind, N,\
Rref, VPolybis = _GG.discretize_vpoly(VPoly, float(dL),
mode=dLMode.lower(),
D1=DS[0], D2=DS[1],
margin=margin,
DIn=float(DIn), VIn=VIn)
return Pts, dLr, ind
def _Ves_get_sampleCross(VPoly, Min1, Max1, Min2, Max2, dS,
DS=None, dSMode='abs', ind=None,
margin=1.e-9, mode='flat'):
assert mode in ['flat','imshow']
types =[int,float,np.int32,np.int64,np.float32,np.float64]
c0 = (hasattr(dS,'__iter__') and len(dS)==2
and all([type(ds) in types for ds in dS]))
assert c0 or type(dS) in types, "Arg dS must be a float or a list 2 floats!"
dS = [float(dS),float(dS)] if type(dS) in types else [float(dS[0]),
float(dS[1])]
assert DS is None or (hasattr(DS,'__iter__') and len(DS)==2)
if DS is None:
DS = [None,None]
else:
assert all([ds is None or (hasattr(ds,'__iter__') and len(ds)==2
and all([ss is None or type(ss) in types
for ss in ds])) for ds in DS])
assert type(dSMode) is str and dSMode.lower() in ['abs','rel'],\
"Arg dSMode must be in ['abs','rel'] !"
assert ind is None or (type(ind) is np.ndarray and ind.ndim==1
and ind.dtype in ['int32','int64']
and np.all(ind>=0)), \
"Arg ind must be None or 1D np.ndarray of positive int !"
MinMax1 = np.array([Min1,Max1])
MinMax2 = np.array([Min2,Max2])
if ind is None:
if mode == 'flat':
Pts, dS, ind, d1r, d2r = _GG.discretize_segment2d(MinMax1, MinMax2,
dS[0], dS[1],
D1=DS[0],
D2=DS[1],
mode=dSMode,
VPoly=VPoly,
margin=margin)
out = (Pts, dS, ind, (d1r,d2r))
else:
x1, d1r, ind1, N1 = _GG._Ves_mesh_dlfromL_cython(MinMax1,
dS[0], DS[0],
Lim=True,
dLMode=dSMode,
margin=margin)
x2, d2r, ind2, N2 = _GG._Ves_mesh_dlfromL_cython(MinMax2,
dS[1], DS[1],
Lim=True,
dLMode=dSMode,
margin=margin)
xx1, xx2 = np.meshgrid(x1,x2)
pts = np.squeeze([xx1,xx2])
extent = (x1[0]-d1r/2., x1[-1]+d1r/2., x2[0]-d2r/2., x2[-1]+d2r/2.)
out = (pts, x1, x2, extent)
else:
assert mode == 'flat'
c0 = type(ind) is np.ndarray and ind.ndim==1
c0 = c0 and ind.dtype in ['int32','int64'] and np.all(ind>=0)
assert c0, "Arg ind must be a np.ndarray of int !"
Pts, dS, d1r, d2r = _GG._Ves_meshCross_FromInd(MinMax1, MinMax2,
dS[0], dS[1], ind,
dSMode=dSMode,
margin=margin)
out = (Pts, dS, ind, (d1r,d2r))
return out
def _Ves_get_sampleV(VPoly, Min1, Max1, Min2, Max2, dV,
DV=None, dVMode='abs', ind=None,
VType='Tor', VLim=None,
Out='(X,Y,Z)', margin=1.e-9):
types =[int,float,np.int32,np.int64,np.float32,np.float64]
assert type(dV) in types or (hasattr(dV,'__iter__') and len(dV)==3 and all([type(ds) in types for ds in dV])), "Arg dV must be a float or a list 3 floats !"
dV = [float(dV),float(dV),float(dV)] if type(dV) in types else [float(dV[0]),float(dV[1]),float(dV[2])]
assert DV is None or (hasattr(DV,'__iter__') and len(DV)==3)
if DV is None:
DV = [None,None,None]
else:
assert all([ds is None or (hasattr(ds,'__iter__') and len(ds)==2 and all([ss is None or type(ss) in types for ss in ds])) for ds in DV]), "Arg DV must be a list of 3 lists of 2 floats !"
assert type(dVMode) is str and dVMode.lower() in ['abs','rel'], "Arg dVMode must be in ['abs','rel'] !"
assert ind is None or (type(ind) is np.ndarray and ind.ndim==1 and ind.dtype in ['int32','int64'] and np.all(ind>=0)), "Arg ind must be None or 1D np.ndarray of positive int !"
MinMax1 = np.array([Min1,Max1])
MinMax2 = np.array([Min2,Max2])
VLim = None if VType.lower()=='tor' else np.array(VLim).ravel()
dVr = [None,None,None]
if ind is None:
if VType.lower()=='tor':
Pts, dV, ind, dVr[0], dVr[1], dVr[2] = _GG._Ves_Vmesh_Tor_SubFromD_cython(dV[0], dV[1], dV[2], MinMax1, MinMax2, DR=DV[0], DZ=DV[1], DPhi=DV[2], VPoly=VPoly, Out=Out, margin=margin)
else:
Pts, dV, ind, dVr[0], dVr[1], dVr[2] = _GG._Ves_Vmesh_Lin_SubFromD_cython(dV[0], dV[1], dV[2], VLim, MinMax1, MinMax2, DX=DV[0], DY=DV[1], DZ=DV[2], VPoly=VPoly, margin=margin)
else:
if VType.lower()=='tor':
Pts, dV, dVr[0], dVr[1], dVr[2] = _GG._Ves_Vmesh_Tor_SubFromInd_cython(dV[0], dV[1], dV[2], MinMax1, MinMax2, ind, Out=Out, margin=margin)
else:
Pts, dV, dVr[0], dVr[1], dVr[2] = _GG._Ves_Vmesh_Lin_SubFromInd_cython(dV[0], dV[1], dV[2], VLim, MinMax1, MinMax2, ind, margin=margin)
return Pts, dV, ind, dVr
def _Ves_get_sampleS(VPoly, Min1, Max1, Min2, Max2, dS,
DS=None, dSMode='abs', ind=None, DIn=0., VIn=None,
VType='Tor', VLim=None, nVLim=None, Out='(X,Y,Z)',
margin=1.e-9, Multi=False, Ind=None):
types =[int,float,np.int32,np.int64,np.float32,np.float64]
assert type(dS) in types or (hasattr(dS,'__iter__') and len(dS)==2 and all([type(ds) in types for ds in dS])), "Arg dS must be a float or a list of 2 floats !"
dS = [float(dS),float(dS),float(dS)] if type(dS) in types else [float(dS[0]),float(dS[1]),float(dS[2])]
assert DS is None or (hasattr(DS,'__iter__') and len(DS)==3)
msg = "type(nVLim)={0} and nVLim={1}".format(str(type(nVLim)),nVLim)
assert type(nVLim) is int and nVLim>=0, msg
if DS is None:
DS = [None,None,None]
else:
assert all([ds is None or (hasattr(ds,'__iter__') and len(ds)==2 and all([ss is None or type(ss) in types for ss in ds])) for ds in DS]), "Arg DS must be a list of 3 lists of 2 floats !"
assert type(dSMode) is str and dSMode.lower() in ['abs','rel'], "Arg dSMode must be in ['abs','rel'] !"
assert type(Multi) is bool, "Arg Multi must be a bool !"
VLim = None if (VLim is None or nVLim==0) else np.array(VLim)
MinMax1 = np.array([Min1,Max1])
MinMax2 = np.array([Min2,Max2])
# Check if Multi
if nVLim>1:
assert VLim is not None, "For multiple Struct, Lim cannot be None !"
assert all([hasattr(ll,'__iter__') and len(ll)==2 for ll in VLim])
if Ind is None:
Ind = np.arange(0,nVLim)
else:
Ind = [Ind] if not hasattr(Ind,'__iter__') else Ind
Ind = np.asarray(Ind).astype(int)
if ind is not None:
assert hasattr(ind,'__iter__') and len(ind)==len(Ind), "For multiple Struct, ind must be a list of len() = len(Ind) !"
assert all([type(ind[ii]) is np.ndarray and ind[ii].ndim==1 and ind[ii].dtype in ['int32','int64'] and np.all(ind[ii]>=0) for ii in range(0,len(ind))]), "For multiple Struct, ind must be a list of index arrays !"
else:
VLim = [None] if VLim is None else [VLim.ravel()]
assert ind is None or (type(ind) is np.ndarray and ind.ndim==1 and ind.dtype in ['int32','int64'] and np.all(ind>=0)), "Arg ind must be None or 1D np.ndarray of positive int !"
Ind = [0]
if ind is None:
Pts, dS, ind, dSr = [0 for ii in Ind], [dS for ii in Ind], [0 for ii in Ind], [[0,0] for ii in Ind]
if VType.lower()=='tor':
for ii in range(0,len(Ind)):
if VLim[Ind[ii]] is None:
Pts[ii], dS[ii], ind[ii], NL, dSr[ii][0], Rref, dSr[ii][1], nRPhi0, VPbis = _GG._Ves_Smesh_Tor_SubFromD_cython(dS[ii][0], dS[ii][1], VPoly, DR=DS[0], DZ=DS[1], DPhi=DS[2], DIn=DIn, VIn=VIn, PhiMinMax=None, Out=Out, margin=margin)
else:
Pts[ii], dS[ii], ind[ii], NL, dSr[ii][0], Rref, dR0r, dZ0r, dSr[ii][1], VPbis = _GG._Ves_Smesh_TorStruct_SubFromD_cython(VLim[Ind[ii]], dS[ii][0], dS[ii][1], VPoly, DR=DS[0], DZ=DS[1], DPhi=DS[2], DIn=DIn, VIn=VIn, Out=Out, margin=margin)
dSr[ii] += [dR0r, dZ0r]
else:
for ii in range(0,len(Ind)):
Pts[ii], dS[ii], ind[ii], NL, dSr[ii][0], Rref, dSr[ii][1], dY0r, dZ0r, VPbis = _GG._Ves_Smesh_Lin_SubFromD_cython(VLim[Ind[ii]], dS[ii][0], dS[ii][1], VPoly, DX=DS[0], DY=DS[1], DZ=DS[2], DIn=DIn, VIn=VIn, margin=margin)
dSr[ii] += [dY0r, dZ0r]
else:
ind = ind if Multi else [ind]
Pts, dS, dSr = [np.ones((3,0)) for ii in Ind], [dS for ii in Ind], [[0,0] for ii in Ind]
if VType.lower()=='tor':
for ii in range(0,len(Ind)):
if ind[Ind[ii]].size>0:
if VLim[Ind[ii]] is None:
Pts[ii], dS[ii], NL, dSr[ii][0], Rref, dSr[ii][1], nRPhi0, VPbis = _GG._Ves_Smesh_Tor_SubFromInd_cython(dS[ii][0], dS[ii][1], VPoly, ind[Ind[ii]], DIn=DIn, VIn=VIn, PhiMinMax=None, Out=Out, margin=margin)
else:
Pts[ii], dS[ii], NL, dSr[ii][0], Rref, dR0r, dZ0r, dSr[ii][1], VPbis = _GG._Ves_Smesh_TorStruct_SubFromInd_cython(VLim[Ind[ii]], dS[ii][0], dS[ii][1], VPoly, ind[Ind[ii]], DIn=DIn, VIn=VIn, Out=Out, margin=margin)
dSr[ii] += [dR0r, dZ0r]
else:
for ii in range(0,len(Ind)):
if ind[Ind[ii]].size>0:
Pts[ii], dS[ii], NL, dSr[ii][0], Rref, dSr[ii][1], dY0r, dZ0r, VPbis = _GG._Ves_Smesh_Lin_SubFromInd_cython(VLim[Ind[ii]], dS[ii][0], dS[ii][1], VPoly, ind[Ind[ii]], DIn=DIn, VIn=VIn, margin=margin)
dSr[ii] += [dY0r, dZ0r]
if len(VLim)==1:
Pts, dS, ind, dSr = Pts[0], dS[0], ind[0], dSr[0]
return Pts, dS, ind, dSr
# ------------------------------------------------------------
# phi / theta projections for magfieldlines
def _Struct_get_phithetaproj(ax=None, poly_closed=None, lim=None, noccur=0):
# phi = toroidal angle
if noccur == 0:
Dphi = np.array([[-np.pi,np.pi]])
nphi = np.r_[1]
else:
assert lim.ndim == 2, str(lim)
nphi = np.ones((noccur,),dtype=int)
ind = (lim[:,0] > lim[:,1]).nonzero()[0]
Dphi = np.concatenate((lim, np.full((noccur,2),np.nan)), axis=1)
if ind.size > 0:
for ii in ind:
Dphi[ii,:] = [lim[ii,0], np.pi, -np.pi, lim[ii,1]]
nphi[ii] = 2
# theta = poloidal angle
Dtheta = np.arctan2(poly_closed[1,:]-ax[1], poly_closed[0,:]-ax[0])
Dtheta = np.r_[np.min(Dtheta), np.max(Dtheta)]
if Dtheta[0] > Dtheta[1]:
ntheta = 2
Dtheta = [Dtheta[0],np.pi, -np.pi, Dtheta[1]]
else:
ntheta = 1
return nphi, Dphi, ntheta, Dtheta
def _get_phithetaproj_dist(poly_closed, ax, Dtheta, nDtheta,
Dphi, nDphi, theta, phi, ntheta, nphi, noccur):
if nDtheta == 1:
ind = (theta >= Dtheta[0]) & (theta <= Dtheta[1])
else:
ind = (theta >= Dtheta[0]) | (theta <= Dtheta[1])
disttheta = np.full((theta.size,), np.nan)
# phi within Dphi
if noccur > 0:
indphi = np.zeros((nphi,),dtype=bool)
for ii in range(0,noccur):
for jj in range(0,nDphi[ii]):
indphi |= (phi >= Dphi[ii,jj]) & (phi<= Dphi[ii,jj+1])
if not np.any(indphi):
return disttheta, indphi
else:
indphi = np.ones((nphi,),dtype=bool)
# No theta within Dtheta
if not np.any(ind):
return disttheta, indphi
# Check for non-parallel AB / u pairs
u = np.array([np.cos(theta), np.sin(theta)])
AB = np.diff(poly_closed, axis=1)
detABu = AB[0,:,None]*u[1,None,:] - AB[1,:,None]*u[0,None,:]
inddet = ind[None,:] & (np.abs(detABu) > 1.e-9)
if not np.any(inddet):
return disttheta, indphi
nseg = poly_closed.shape[1]-1
k = np.full((nseg, ntheta), np.nan)
OA = poly_closed[:,:-1] - ax[:,None]
detOAu = (OA[0,:,None]*u[1,None,:] - OA[1,:,None]*u[0,None,:])[inddet]
ss = - detOAu / detABu[inddet]
inds = (ss >= 0.) & (ss < 1.)
inddet[inddet] = inds
if not np.any(inds):
return disttheta, indphi
scaOAu = (OA[0,:,None]*u[0,None,:] + OA[1,:,None]*u[1,None,:])[inddet]
scaABu = (AB[0,:,None]*u[0,None,:] + AB[1,:,None]*u[1,None,:])[inddet]
k[inddet] = scaOAu + ss[inds]*scaABu
indk = k[inddet] > 0.
inddet[inddet] = indk
if not np.any(indk):
return disttheta, indphi
k[~inddet] = np.nan
indok = np.any(inddet, axis=0)
disttheta[indok] = np.nanmin(k[:,indok], axis=0)
return disttheta, indphi
"""
###############################################################################
###############################################################################
LOS functions
###############################################################################
"""
def LOS_PRMin(Ds, us, kOut=None, Eps=1.e-12, squeeze=True, Test=True):
""" Compute the point on the LOS where the major radius is minimum """
if Test:
assert Ds.ndim in [1,2,3] and 3 in Ds.shape and Ds.shape == us.shape
if kOut is not None:
kOut = np.atleast_1d(kOut)
assert kOut.size == Ds.size/3
v = Ds.ndim == 1
if Ds.ndim == 1:
Ds, us = Ds[:,None,None], us[:,None,None]
elif Ds.ndim == 2:
Ds, us = Ds[:,:,None], us[:,:,None]
if kOut is not None:
if kOut.ndim == 1:
kOut = kOut[:,None]
_, nlos, nref = Ds.shape
kRMin = np.full((nlos,nref), np.nan)
uparN = np.sqrt(us[0,:,:]**2 + us[1,:,:]**2)
# Case with u vertical
ind = uparN > Eps
kRMin[~ind] = 0.
# Else
kRMin[ind] = -(us[0,ind]*Ds[0,ind] + us[1,ind]*Ds[1,ind]) / uparN[ind]**2
# Check
kRMin[kRMin <= 0.] = 0.
if kOut is not None:
kRMin[kRMin > kOut] = kOut[kRMin > kOut]
# squeeze
if squeeze:
if nref == 1 and nlos == 11:
kRMin = kRMin[0,0]
elif nref == 1:
kRMin = kRMin[:,0]
elif nlos == 1:
kRMin = kRMin[0,:]
return kRMin
def LOS_CrossProj(VType, Ds, us, kOuts, proj='All', multi=False,
num_threads=16, return_pts=False, Test=True):
""" Compute the parameters to plot the poloidal projection of the LOS """
assert type(VType) is str and VType.lower() in ['tor','lin']
dproj = {'cross':('R','Z'), 'hor':('x,y'), 'all':('R','Z','x','y'),
'3d':('x','y','z')}
assert type(proj) in [str, tuple]
if type(proj) is tuple:
assert all([type(pp) is str for pp in proj])
lcoords = proj
else:
proj = proj.lower()
assert proj in dproj.keys()
lcoords = dproj[proj]
if return_pts:
assert proj in ['cross','hor', '3d']
lc = [Ds.ndim == 3, Ds.shape == us.shape]
if not all(lc):
msg = "Ds and us must have the same shape and dim in [2,3]:\n"
msg += " - provided Ds.shape: %s\n"%str(Ds.shape)
msg += " - provided us.shape: %s"%str(us.shape)
raise Exception(msg)
lc = [kOuts.size == Ds.size/3, kOuts.shape == Ds.shape[1:]]
if not all(lc):
msg = "kOuts must have the same shape and ndim = Ds.ndim-1:\n"
msg += " - Ds.shape : %s\n"%str(Ds.shape)
msg += " - kOutss.shape: %s"%str(kOuts.shape)
raise Exception(msg)
# Prepare inputs
_, nlos, nseg = Ds.shape
# Detailed sampling for 'tor' and ('cross' or 'all')
R, Z = None, None
if 'R' in lcoords or 'Z' in lcoords:
angcross = np.arccos(np.sqrt(us[0,...]**2 + us[1,...]**2)
/np.sqrt(np.sum(us**2, axis=0)))
resnk = np.ceil(25.*(1 - (angcross/(np.pi/4)-1)**2) + 5)
resnk = 1./resnk.ravel()
# Use optimized get sample
DL = np.vstack((np.zeros((nlos*nseg,),dtype=float), kOuts.ravel()))
k, reseff, lind = _GG.LOS_get_sample(nlos*nseg, resnk, DL,
dmethod='rel', method='simps',
num_threads=num_threads, Test=Test)
assert lind.size == nseg*nlos - 1
ind = lind[nseg-1::nseg]
nbrep = np.r_[lind[0], np.diff(lind), k.size - lind[-1]]
pts = (np.repeat(Ds.reshape((3,nlos*nseg)), nbrep, axis=1)
+ k[None,:] * np.repeat(us.reshape((3,nlos*nseg)), nbrep,
axis=1))
if return_pts:
pts = np.array([np.hypot(pts[0,:],pts[1,:]), pts[2,:]])
if multi:
pts = np.split(pts, ind, axis=1)
else:
pts = np.insert(pts, ind, np.nan, axis=1)
else:
if multi:
if 'R' in lcoords:
R = np.split(np.hypot(pts[0,:],pts[1,:]), ind)
if 'Z' in lcoords:
Z = np.split(pts[2,:], ind)
else:
if 'R' in lcoords:
R = np.insert(np.hypot(pts[0,:],pts[1,:]), ind, np.nan)
if 'Z' in lcoords:
Z = np.insert(pts[2,:], ind, np.nan)
# Normal sampling => pts
# unnecessary only if 'tor' and 'cross'
x, y, z = None, None, None
if 'x' in lcoords or 'y' in lcoords or 'z' in lcoords:
pts = np.concatenate((Ds, Ds[:,:,-1:] + kOuts[None,:,-1:]*us[:,:,-1:]),
axis=-1)
if multi:
ind = np.arange(1,nlos)*(nseg+1)
pts = pts.reshape((3,nlos*(nseg+1)))
else:
nancoords = np.full((3,nlos,1), np.nan)
pts = np.concatenate((pts,nancoords), axis=-1)
pts = pts.reshape((3,nlos*(nseg+2)))
if return_pts:
assert proj in ['hor','3d']
if multi:
if proj == 'hor':
pts = np.split(pts[:2,:], ind, axis=1)
else:
pts = np.split(pts, ind, axis=1)
elif proj == 'hor':
pts = pts[:2,:]
else:
if multi:
if 'x' in lcoords:
x = np.split(pts[0,:], ind)
if 'y' in lcoords:
y = np.split(pts[1,:], ind)
if 'z' in lcoords:
z = np.split(pts[2,:], ind)
else:
if 'x' in lcoords:
x = pts[0,:]
if 'y' in lcoords:
y = pts[1,:]
if 'z' in lcoords:
z = pts[2,:]
if return_pts:
return pts
else:
return R, Z, x, y, z
##############################################
# Meshing & signal
##############################################
def LOS_get_sample(D, u, dL, DL=None, dLMode='abs', method='sum', Test=True):
""" Return the sampled line, with the specified method
'linspace': return the N+1 edges, including the first and last point
'sum' : return the N middle of the segments
'simps': return the N+1 egdes, where N has to be even (scipy.simpson requires an even number of intervals)
'romb' : return the N+1 edges, where N+1 = 2**k+1 (fed to scipy.romb for integration)
"""
if Test:
assert all([type(dd) is np.ndarray and dd.shape==(3,) for dd in [D,u]])
assert not hasattr(dL,'__iter__')
assert DL is None or all([hasattr(DL,'__iter__'), len(DL)==2, all([not hasattr(dd,'__iter__') for dd in DL])])
assert dLMode in ['abs','rel']
assert type(method) is str and method in ['linspace','sum','simps','romb']
# Compute the minimum number of intervals to satisfy the specified resolution
N = int(np.ceil((DL[1]-DL[0])/dL)) if dLMode=='abs' else int(np.ceil(1./dL))
# Modify N according to the desired method
if method=='simps':
N = N if N%2==0 else N+1
elif method=='romb':
N = 2**int(np.ceil(np.log(N)/np.log(2.)))
# Derive k and dLr
if method=='sum':
dLr = (DL[1]-DL[0])/N
k = DL[0] + (0.5+np.arange(0,N))*dLr
else:
k, dLr = np.linspace(DL[0], DL[1], N+1, endpoint=True, retstep=True, dtype=float)
Pts = D[:,np.newaxis] + k[np.newaxis,:]*u[:,np.newaxis]
return Pts, k, dLr
def LOS_calc_signal(ff, D, u, dL, DL=None, dLMode='abs', method='romb', Test=True):
assert hasattr(ff,'__call__'), "Arg ff must be a callable (function) taking at least 1 positional Pts (a (3,N) np.ndarray of cartesian (X,Y,Z) coordinates) !"
assert not method=='linspace'
Pts, k, dLr = LOS_get_sample(D, u, dL, DL=DL, dLMode=dLMode, method=method, Test=Test)
out = insp(ff)
if sys.version[0]=='3':
N = np.sum([(pp.kind==pp.POSITIONAL_OR_KEYWORD and pp.default is pp.empty) for pp in out.parameters.values()])
else:
N = len(out.args)
if N==1:
Vals = ff(Pts)
elif N==2:
Vals = ff(Pts, np.tile(-u,(Pts.shape[1],1)).T)
else:
raise ValueError("The function (ff) assessing the emissivity locally "
+ "must take a single positional argument: Pts a (3,N)"
+ " np.ndarray of (X,Y,Z) cartesian coordinates !")
Vals[np.isnan(Vals)] = 0.
if method=='sum':
Int = np.sum(Vals)*dLr
elif method=='simps':
Int = scpintg.simps(Vals, x=None, dx=dLr)
elif method=='romb':
Int = scpintg.romb(Vals, dx=dLr, show=False)
return Int
"""
###############################################################################
###############################################################################
Solid Angle particle
###############################################################################
"""
def calc_solidangle_particle(traj, pts, r=1., config=None,
approx=True, aniso=False, block=True):
""" Compute the solid angle subtended by a particle along a trajectory
The particle has radius r, and trajectory (array of points) traj
It is observed from pts (array of points)
traj and pts are (3,N) and (3,M) arrays of cartesian coordinates
approx = True => use approximation
aniso = True => return also unit vector of emission
block = True consider LOS collisions (with Ves, Struct...)
if block:
config = config used for LOS collisions
Return:
-------
sang: np.ndarray
(N,M) Array of floats, solid angles
"""
################
# Prepare inputs
traj = np.ascontiguousarray(traj, dtype=float)
pts = np.ascontiguousarray(pts, dtype=float)
r = np.r_[r].astype(float).ravel()
# Check booleans
assert type(approx) is bool
assert type(aniso) is bool
assert type(block) is bool
# Check config
assert config is None or config.__class__.__name__ == 'Config'
assert block == (config is not None)
# Check pts, traj and r are array of good shape
assert traj.ndim in [1,2]
assert pts.ndim in [1,2]
assert 3 in traj.shape and 3 in pts.shape
if traj.ndim == 1:
traj = traj.reshape((3,1))
if traj.shape[0] != 3:
traj = traj.T
if pts.ndim == 1:
pts = pts.reshape((3,1))
if pts.shape[0] != 3:
pts = pts.T
# get npart
ntraj = traj.shape[1]
nr = r.size
npts = pts.shape[1]
npart = max(nr,ntraj)
assert nr in [1,npart]
assert ntraj in [1,npart]
if nr < npart:
r = np.full((npart,), r[0])
if ntraj < npart:
traj = np.repeat(traj, npart, axis=1)
################
# Main computation
# traj2pts vector, with length (3d array (3,N,M))
vect = pts[:,None,:] - traj[:,:,None]
l = np.sqrt(np.sum(vect**2, axis=0))
# If aniso or block, normalize
if aniso or block:
vect = vect/l[None,:,:]
# Solid angle
if approx:
sang = np.pi*r[None,:]**2/l**2
else:
sang = 2.*np.pi*(1 - np.sqrt(1.-r**2[None,:]/l**2))
# block
if block:
kwdargs = config._get_kwdargs_LOS_isVis()
# TODO : modify this function along issue #102
indnan = _GG.LOS_areVis_PtsFromPts_VesStruct(traj, pts, k=l, vis=False,
**kwdargs)
sang[indnan] = 0.
vect[indnan,:] = np.nan
################
# Return
if aniso:
return sang, vect
else:
return sang
def calc_solidangle_particle_integ(traj, r=1., config=None,
approx=True, block=True, res=0.01):
# step0: if block : generate kwdargs from config
# step 1: sample cross-section
# step 2: loop on R of pts of cross-section (parallelize ?)
# => fix nb. of phi for the rest of the loop
# loop of Z
# step 3: loop phi
# Check visibility (if block = True) for each phi (LOS collision)
# If visible => compute solid angle
# integrate (sum * res) on each phi the solid angle
# Return sang as (N,nR,nZ) array
return
|
[
"numpy.sqrt",
"tofu.geom._GG.Poly_VolAngTor",
"numpy.log",
"tofu.geom._GG.discretize_segment2d",
"numpy.ascontiguousarray",
"numpy.array",
"numpy.arctan2",
"tofu.geom._GG._Ves_Smesh_Lin_SubFromD_cython",
"numpy.nanmin",
"numpy.sin",
"numpy.arange",
"numpy.repeat",
"tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython",
"numpy.asarray",
"numpy.diff",
"numpy.max",
"numpy.linspace",
"scipy.integrate.romb",
"numpy.concatenate",
"numpy.min",
"numpy.argmin",
"numpy.hypot",
"warnings.warn",
"numpy.meshgrid",
"tofu.geom._GG._Ves_Smesh_Tor_SubFromD_cython",
"tofu.geom._GG._Ves_Vmesh_Lin_SubFromD_cython",
"tofu.geom._GG._Ves_Smesh_TorStruct_SubFromInd_cython",
"numpy.tile",
"numpy.ceil",
"tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython",
"numpy.abs",
"numpy.ones",
"scipy.integrate.simps",
"numpy.argmax",
"numpy.any",
"numpy.squeeze",
"tofu.geom._GG.LOS_get_sample",
"tofu.geom._GG._Ves_mesh_dlfromL_cython",
"numpy.isnan",
"numpy.cos",
"tofu.geom._GG._Ves_Smesh_Lin_SubFromInd_cython",
"tofu.geom._GG._Ves_Smesh_Tor_SubFromInd_cython",
"tofu.geom._GG._Ves_meshCross_FromInd",
"numpy.atleast_1d",
"numpy.insert",
"tofu.geom._GG.Poly_Order",
"tofu.geom._GG._Ves_Smesh_TorStruct_SubFromD_cython",
"numpy.unique",
"tofu.geom._GG.LOS_areVis_PtsFromPts_VesStruct",
"inspect.getargspec",
"numpy.append",
"numpy.sum",
"numpy.zeros",
"numpy.split",
"tofu.geom._GG._Ves_Vmesh_Lin_SubFromInd_cython",
"tofu.geom._GG.poly_area_and_barycenter",
"numpy.full",
"numpy.all"
] |
[((1201, 1289), 'tofu.geom._GG.Poly_Order', '_GG.Poly_Order', (['Poly'], {'order': '"""C"""', 'Clock': '(False)', 'close': '(True)', 'layout': '"""(cc,N)"""', 'Test': '(True)'}), "(Poly, order='C', Clock=False, close=True, layout='(cc,N)',\n Test=True)\n", (1215, 1289), True, 'import tofu.geom._GG as _GG\n'), ((1768, 1836), 'numpy.array', 'np.array', (['[(P1Max[0] + P1Min[0]) / 2.0, (P2Max[1] + P2Min[1]) / 2.0]'], {}), '([(P1Max[0] + P1Min[0]) / 2.0, (P2Max[1] + P2Min[1]) / 2.0])\n', (1776, 1836), True, 'import numpy as np\n'), ((1845, 1883), 'tofu.geom._GG.poly_area_and_barycenter', '_GG.poly_area_and_barycenter', (['Poly', 'NP'], {}), '(Poly, NP)\n', (1873, 1883), True, 'import tofu.geom._GG as _GG\n'), ((2296, 2322), 'numpy.diff', 'np.diff', (['Poly'], {'n': '(1)', 'axis': '(1)'}), '(Poly, n=1, axis=1)\n', (2303, 2322), True, 'import numpy as np\n'), ((2409, 2444), 'numpy.array', 'np.array', (['[Vect[1, :], -Vect[0, :]]'], {}), '([Vect[1, :], -Vect[0, :]])\n', (2417, 2444), True, 'import numpy as np\n'), ((2592, 2689), 'tofu.geom._GG.Poly_Order', '_GG.Poly_Order', (['Poly'], {'order': 'arrayorder', 'Clock': 'Clock', 'close': '(False)', 'layout': '"""(cc,N)"""', 'Test': '(True)'}), "(Poly, order=arrayorder, Clock=Clock, close=False, layout=\n '(cc,N)', Test=True)\n", (2606, 2689), True, 'import tofu.geom._GG as _GG\n'), ((2830, 2839), 'numpy.max', 'np.max', (['r'], {}), '(r)\n', (2836, 2839), True, 'import numpy as np\n'), ((4161, 4194), 'numpy.all', 'np.all', (['(Poly[:, 0] == Poly[:, -1])'], {}), '(Poly[:, 0] == Poly[:, -1])\n', (4167, 4194), True, 'import numpy as np\n'), ((8235, 8257), 'numpy.array', 'np.array', (['[Min1, Max1]'], {}), '([Min1, Max1])\n', (8243, 8257), True, 'import numpy as np\n'), ((8271, 8293), 'numpy.array', 'np.array', (['[Min2, Max2]'], {}), '([Min2, Max2])\n', (8279, 8293), True, 'import numpy as np\n'), ((11590, 11612), 'numpy.array', 'np.array', (['[Min1, Max1]'], {}), '([Min1, Max1])\n', (11598, 11612), True, 'import numpy as np\n'), ((11626, 11648), 'numpy.array', 'np.array', (['[Min2, Max2]'], {}), '([Min2, Max2])\n', (11634, 11648), True, 'import numpy as np\n'), ((13864, 13886), 'numpy.array', 'np.array', (['[Min1, Max1]'], {}), '([Min1, Max1])\n', (13872, 13886), True, 'import numpy as np\n'), ((13900, 13922), 'numpy.array', 'np.array', (['[Min2, Max2]'], {}), '([Min2, Max2])\n', (13908, 13922), True, 'import numpy as np\n'), ((18129, 18193), 'numpy.arctan2', 'np.arctan2', (['(poly_closed[1, :] - ax[1])', '(poly_closed[0, :] - ax[0])'], {}), '(poly_closed[1, :] - ax[1], poly_closed[0, :] - ax[0])\n', (18139, 18193), True, 'import numpy as np\n'), ((18712, 18742), 'numpy.full', 'np.full', (['(theta.size,)', 'np.nan'], {}), '((theta.size,), np.nan)\n', (18719, 18742), True, 'import numpy as np\n'), ((19290, 19318), 'numpy.diff', 'np.diff', (['poly_closed'], {'axis': '(1)'}), '(poly_closed, axis=1)\n', (19297, 19318), True, 'import numpy as np\n'), ((19539, 19570), 'numpy.full', 'np.full', (['(nseg, ntheta)', 'np.nan'], {}), '((nseg, ntheta), np.nan)\n', (19546, 19570), True, 'import numpy as np\n'), ((20184, 20206), 'numpy.any', 'np.any', (['inddet'], {'axis': '(0)'}), '(inddet, axis=0)\n', (20190, 20206), True, 'import numpy as np\n'), ((20230, 20260), 'numpy.nanmin', 'np.nanmin', (['k[:, indok]'], {'axis': '(0)'}), '(k[:, indok], axis=0)\n', (20239, 20260), True, 'import numpy as np\n'), ((21205, 21234), 'numpy.full', 'np.full', (['(nlos, nref)', 'np.nan'], {}), '((nlos, nref), np.nan)\n', (21212, 21234), True, 'import numpy as np\n'), ((21246, 21290), 'numpy.sqrt', 'np.sqrt', (['(us[0, :, :] ** 2 + us[1, :, :] ** 2)'], {}), '(us[0, :, :] ** 2 + us[1, :, :] ** 2)\n', (21253, 21290), True, 'import numpy as np\n'), ((28275, 28283), 'inspect.getargspec', 'insp', (['ff'], {}), '(ff)\n', (28279, 28283), True, 'from inspect import getargspec as insp\n'), ((30135, 30174), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['traj'], {'dtype': 'float'}), '(traj, dtype=float)\n', (30155, 30174), True, 'import numpy as np\n'), ((30185, 30223), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['pts'], {'dtype': 'float'}), '(pts, dtype=float)\n', (30205, 30223), True, 'import numpy as np\n'), ((1696, 1740), 'numpy.sum', 'np.sum', (['Poly[:, :-1]'], {'axis': '(1)', 'keepdims': '(False)'}), '(Poly[:, :-1], axis=1, keepdims=False)\n', (1702, 1740), True, 'import numpy as np\n'), ((2092, 2116), 'tofu.geom._GG.Poly_VolAngTor', '_GG.Poly_VolAngTor', (['Poly'], {}), '(Poly)\n', (2110, 2116), True, 'import tofu.geom._GG as _GG\n'), ((2772, 2822), 'numpy.sum', 'np.sum', (['((poly - circC[:, np.newaxis]) ** 2)'], {'axis': '(0)'}), '((poly - circC[:, np.newaxis]) ** 2, axis=0)\n', (2778, 2822), True, 'import numpy as np\n'), ((4391, 4427), 'numpy.arctan2', 'np.arctan2', (['Ptemp[1, :]', 'Ptemp[0, :]'], {}), '(Ptemp[1, :], Ptemp[0, :])\n', (4401, 4427), True, 'import numpy as np\n'), ((4444, 4477), 'numpy.unique', 'np.unique', (['Ang'], {'return_index': '(True)'}), '(Ang, return_index=True)\n', (4453, 4477), True, 'import numpy as np\n'), ((5218, 5262), 'numpy.array', 'np.array', (['[xnew + BaryS[0], ynew + BaryS[1]]'], {}), '([xnew + BaryS[0], ynew + BaryS[1]])\n', (5226, 5262), True, 'import numpy as np\n'), ((5273, 5317), 'numpy.concatenate', 'np.concatenate', (['(Poly, Poly[:, 0:1])'], {'axis': '(1)'}), '((Poly, Poly[:, 0:1]), axis=1)\n', (5287, 5317), True, 'import numpy as np\n'), ((10113, 10211), 'tofu.geom._GG._Ves_meshCross_FromInd', '_GG._Ves_meshCross_FromInd', (['MinMax1', 'MinMax2', 'dS[0]', 'dS[1]', 'ind'], {'dSMode': 'dSMode', 'margin': 'margin'}), '(MinMax1, MinMax2, dS[0], dS[1], ind, dSMode=\n dSMode, margin=margin)\n', (10139, 10211), True, 'import tofu.geom._GG as _GG\n'), ((13835, 13849), 'numpy.array', 'np.array', (['VLim'], {}), '(VLim)\n', (13843, 13849), True, 'import numpy as np\n'), ((17672, 17699), 'numpy.array', 'np.array', (['[[-np.pi, np.pi]]'], {}), '([[-np.pi, np.pi]])\n', (17680, 17699), True, 'import numpy as np\n'), ((17787, 17816), 'numpy.ones', 'np.ones', (['(noccur,)'], {'dtype': 'int'}), '((noccur,), dtype=int)\n', (17794, 17816), True, 'import numpy as np\n'), ((18802, 18831), 'numpy.zeros', 'np.zeros', (['(nphi,)'], {'dtype': 'bool'}), '((nphi,), dtype=bool)\n', (18810, 18831), True, 'import numpy as np\n'), ((19074, 19102), 'numpy.ones', 'np.ones', (['(nphi,)'], {'dtype': 'bool'}), '((nphi,), dtype=bool)\n', (19081, 19102), True, 'import numpy as np\n'), ((19143, 19154), 'numpy.any', 'np.any', (['ind'], {}), '(ind)\n', (19149, 19154), True, 'import numpy as np\n'), ((19447, 19461), 'numpy.any', 'np.any', (['inddet'], {}), '(inddet)\n', (19453, 19461), True, 'import numpy as np\n'), ((19795, 19807), 'numpy.any', 'np.any', (['inds'], {}), '(inds)\n', (19801, 19807), True, 'import numpy as np\n'), ((20100, 20112), 'numpy.any', 'np.any', (['indk'], {}), '(indk)\n', (20106, 20112), True, 'import numpy as np\n'), ((20861, 20880), 'numpy.atleast_1d', 'np.atleast_1d', (['kOut'], {}), '(kOut)\n', (20874, 20880), True, 'import numpy as np\n'), ((23375, 23434), 'numpy.ceil', 'np.ceil', (['(25.0 * (1 - (angcross / (np.pi / 4) - 1) ** 2) + 5)'], {}), '(25.0 * (1 - (angcross / (np.pi / 4) - 1) ** 2) + 5)\n', (23382, 23434), True, 'import numpy as np\n'), ((23596, 23709), 'tofu.geom._GG.LOS_get_sample', '_GG.LOS_get_sample', (['(nlos * nseg)', 'resnk', 'DL'], {'dmethod': '"""rel"""', 'method': '"""simps"""', 'num_threads': 'num_threads', 'Test': 'Test'}), "(nlos * nseg, resnk, DL, dmethod='rel', method='simps',\n num_threads=num_threads, Test=Test)\n", (23614, 23709), True, 'import tofu.geom._GG as _GG\n'), ((24982, 25068), 'numpy.concatenate', 'np.concatenate', (['(Ds, Ds[:, :, -1:] + kOuts[None, :, -1:] * us[:, :, -1:])'], {'axis': '(-1)'}), '((Ds, Ds[:, :, -1:] + kOuts[None, :, -1:] * us[:, :, -1:]),\n axis=-1)\n', (24996, 25068), True, 'import numpy as np\n'), ((27734, 27808), 'numpy.linspace', 'np.linspace', (['DL[0]', 'DL[1]', '(N + 1)'], {'endpoint': '(True)', 'retstep': '(True)', 'dtype': 'float'}), '(DL[0], DL[1], N + 1, endpoint=True, retstep=True, dtype=float)\n', (27745, 27808), True, 'import numpy as np\n'), ((28831, 28845), 'numpy.isnan', 'np.isnan', (['Vals'], {}), '(Vals)\n', (28839, 28845), True, 'import numpy as np\n'), ((31071, 31094), 'numpy.full', 'np.full', (['(npart,)', 'r[0]'], {}), '((npart,), r[0])\n', (31078, 31094), True, 'import numpy as np\n'), ((31132, 31162), 'numpy.repeat', 'np.repeat', (['traj', 'npart'], {'axis': '(1)'}), '(traj, npart, axis=1)\n', (31141, 31162), True, 'import numpy as np\n'), ((31321, 31346), 'numpy.sum', 'np.sum', (['(vect ** 2)'], {'axis': '(0)'}), '(vect ** 2, axis=0)\n', (31327, 31346), True, 'import numpy as np\n'), ((31729, 31802), 'tofu.geom._GG.LOS_areVis_PtsFromPts_VesStruct', '_GG.LOS_areVis_PtsFromPts_VesStruct', (['traj', 'pts'], {'k': 'l', 'vis': '(False)'}), '(traj, pts, k=l, vis=False, **kwdargs)\n', (31764, 31802), True, 'import tofu.geom._GG as _GG\n'), ((1539, 1560), 'numpy.argmax', 'np.argmax', (['Poly[0, :]'], {}), '(Poly[0, :])\n', (1548, 1560), True, 'import numpy as np\n'), ((1580, 1601), 'numpy.argmin', 'np.argmin', (['Poly[0, :]'], {}), '(Poly[0, :])\n', (1589, 1601), True, 'import numpy as np\n'), ((1621, 1642), 'numpy.argmax', 'np.argmax', (['Poly[1, :]'], {}), '(Poly[1, :])\n', (1630, 1642), True, 'import numpy as np\n'), ((1662, 1683), 'numpy.argmin', 'np.argmin', (['Poly[1, :]'], {}), '(Poly[1, :])\n', (1671, 1683), True, 'import numpy as np\n'), ((2517, 2547), 'numpy.hypot', 'np.hypot', (['Vin[0, :]', 'Vin[1, :]'], {}), '(Vin[0, :], Vin[1, :])\n', (2525, 2547), True, 'import numpy as np\n'), ((4050, 4068), 'warnings.warn', 'warnings.warn', (['msg'], {}), '(msg)\n', (4063, 4068), False, 'import warnings\n'), ((4276, 4299), 'numpy.tile', 'np.tile', (['BaryS', '(Np, 1)'], {}), '(BaryS, (Np, 1))\n', (4283, 4299), True, 'import numpy as np\n'), ((4559, 4577), 'numpy.ones', 'np.ones', (['(Np + 1,)'], {}), '((Np + 1,))\n', (4566, 4577), True, 'import numpy as np\n'), ((5168, 5198), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', 'NP'], {}), '(-np.pi, np.pi, NP)\n', (5179, 5198), True, 'import numpy as np\n'), ((8116, 8132), 'numpy.all', 'np.all', (['(ind >= 0)'], {}), '(ind >= 0)\n', (8122, 8132), True, 'import numpy as np\n'), ((8377, 8498), 'tofu.geom._GG.discretize_segment2d', '_GG.discretize_segment2d', (['MinMax1', 'MinMax2', 'dS[0]', 'dS[1]'], {'D1': 'DS[0]', 'D2': 'DS[1]', 'mode': 'dSMode', 'VPoly': 'VPoly', 'margin': 'margin'}), '(MinMax1, MinMax2, dS[0], dS[1], D1=DS[0], D2=DS[1],\n mode=dSMode, VPoly=VPoly, margin=margin)\n', (8401, 8498), True, 'import tofu.geom._GG as _GG\n'), ((8957, 9052), 'tofu.geom._GG._Ves_mesh_dlfromL_cython', '_GG._Ves_mesh_dlfromL_cython', (['MinMax1', 'dS[0]', 'DS[0]'], {'Lim': '(True)', 'dLMode': 'dSMode', 'margin': 'margin'}), '(MinMax1, dS[0], DS[0], Lim=True, dLMode=dSMode,\n margin=margin)\n', (8985, 9052), True, 'import tofu.geom._GG as _GG\n'), ((9325, 9420), 'tofu.geom._GG._Ves_mesh_dlfromL_cython', '_GG._Ves_mesh_dlfromL_cython', (['MinMax2', 'dS[1]', 'DS[1]'], {'Lim': '(True)', 'dLMode': 'dSMode', 'margin': 'margin'}), '(MinMax2, dS[1], DS[1], Lim=True, dLMode=dSMode,\n margin=margin)\n', (9353, 9420), True, 'import tofu.geom._GG as _GG\n'), ((9684, 9703), 'numpy.meshgrid', 'np.meshgrid', (['x1', 'x2'], {}), '(x1, x2)\n', (9695, 9703), True, 'import numpy as np\n'), ((9721, 9743), 'numpy.squeeze', 'np.squeeze', (['[xx1, xx2]'], {}), '([xx1, xx2])\n', (9731, 9743), True, 'import numpy as np\n'), ((10011, 10027), 'numpy.all', 'np.all', (['(ind >= 0)'], {}), '(ind >= 0)\n', (10017, 10027), True, 'import numpy as np\n'), ((11500, 11516), 'numpy.all', 'np.all', (['(ind >= 0)'], {}), '(ind >= 0)\n', (11506, 11516), True, 'import numpy as np\n'), ((11847, 11993), 'tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython', '_GG._Ves_Vmesh_Tor_SubFromD_cython', (['dV[0]', 'dV[1]', 'dV[2]', 'MinMax1', 'MinMax2'], {'DR': 'DV[0]', 'DZ': 'DV[1]', 'DPhi': 'DV[2]', 'VPoly': 'VPoly', 'Out': 'Out', 'margin': 'margin'}), '(dV[0], dV[1], dV[2], MinMax1, MinMax2,\n DR=DV[0], DZ=DV[1], DPhi=DV[2], VPoly=VPoly, Out=Out, margin=margin)\n', (11881, 11993), True, 'import tofu.geom._GG as _GG\n'), ((12055, 12196), 'tofu.geom._GG._Ves_Vmesh_Lin_SubFromD_cython', '_GG._Ves_Vmesh_Lin_SubFromD_cython', (['dV[0]', 'dV[1]', 'dV[2]', 'VLim', 'MinMax1', 'MinMax2'], {'DX': 'DV[0]', 'DY': 'DV[1]', 'DZ': 'DV[2]', 'VPoly': 'VPoly', 'margin': 'margin'}), '(dV[0], dV[1], dV[2], VLim, MinMax1,\n MinMax2, DX=DV[0], DY=DV[1], DZ=DV[2], VPoly=VPoly, margin=margin)\n', (12089, 12196), True, 'import tofu.geom._GG as _GG\n'), ((12282, 12390), 'tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython', '_GG._Ves_Vmesh_Tor_SubFromInd_cython', (['dV[0]', 'dV[1]', 'dV[2]', 'MinMax1', 'MinMax2', 'ind'], {'Out': 'Out', 'margin': 'margin'}), '(dV[0], dV[1], dV[2], MinMax1, MinMax2,\n ind, Out=Out, margin=margin)\n', (12318, 12390), True, 'import tofu.geom._GG as _GG\n'), ((12447, 12552), 'tofu.geom._GG._Ves_Vmesh_Lin_SubFromInd_cython', '_GG._Ves_Vmesh_Lin_SubFromInd_cython', (['dV[0]', 'dV[1]', 'dV[2]', 'VLim', 'MinMax1', 'MinMax2', 'ind'], {'margin': 'margin'}), '(dV[0], dV[1], dV[2], VLim, MinMax1,\n MinMax2, ind, margin=margin)\n', (12483, 12552), True, 'import tofu.geom._GG as _GG\n'), ((14154, 14173), 'numpy.arange', 'np.arange', (['(0)', 'nVLim'], {}), '(0, nVLim)\n', (14163, 14173), True, 'import numpy as np\n'), ((18207, 18221), 'numpy.min', 'np.min', (['Dtheta'], {}), '(Dtheta)\n', (18213, 18221), True, 'import numpy as np\n'), ((18223, 18237), 'numpy.max', 'np.max', (['Dtheta'], {}), '(Dtheta)\n', (18229, 18237), True, 'import numpy as np\n'), ((18994, 19008), 'numpy.any', 'np.any', (['indphi'], {}), '(indphi)\n', (19000, 19008), True, 'import numpy as np\n'), ((19250, 19263), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (19256, 19263), True, 'import numpy as np\n'), ((19265, 19278), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (19271, 19278), True, 'import numpy as np\n'), ((19412, 19426), 'numpy.abs', 'np.abs', (['detABu'], {}), '(detABu)\n', (19418, 19426), True, 'import numpy as np\n'), ((25236, 25265), 'numpy.full', 'np.full', (['(3, nlos, 1)', 'np.nan'], {}), '((3, nlos, 1), np.nan)\n', (25243, 25265), True, 'import numpy as np\n'), ((25282, 25323), 'numpy.concatenate', 'np.concatenate', (['(pts, nancoords)'], {'axis': '(-1)'}), '((pts, nancoords), axis=-1)\n', (25296, 25323), True, 'import numpy as np\n'), ((27338, 27367), 'numpy.ceil', 'np.ceil', (['((DL[1] - DL[0]) / dL)'], {}), '((DL[1] - DL[0]) / dL)\n', (27345, 27367), True, 'import numpy as np\n'), ((27391, 27408), 'numpy.ceil', 'np.ceil', (['(1.0 / dL)'], {}), '(1.0 / dL)\n', (27398, 27408), True, 'import numpy as np\n'), ((28888, 28900), 'numpy.sum', 'np.sum', (['Vals'], {}), '(Vals)\n', (28894, 28900), True, 'import numpy as np\n'), ((28945, 28980), 'scipy.integrate.simps', 'scpintg.simps', (['Vals'], {'x': 'None', 'dx': 'dLr'}), '(Vals, x=None, dx=dLr)\n', (28958, 28980), True, 'import scipy.integrate as scpintg\n'), ((4986, 5021), 'numpy.append', 'np.append', (['Ptemp[0, :]', 'Ptemp[0, 0]'], {}), '(Ptemp[0, :], Ptemp[0, 0])\n', (4995, 5021), True, 'import numpy as np\n'), ((5019, 5054), 'numpy.append', 'np.append', (['Ptemp[1, :]', 'Ptemp[1, 0]'], {}), '(Ptemp[1, :], Ptemp[1, 0])\n', (5028, 5054), True, 'import numpy as np\n'), ((5056, 5092), 'numpy.append', 'np.append', (['Ang', '(Ang[0] + 2.0 * np.pi)'], {}), '(Ang, Ang[0] + 2.0 * np.pi)\n', (5065, 5092), True, 'import numpy as np\n'), ((11693, 11707), 'numpy.array', 'np.array', (['VLim'], {}), '(VLim)\n', (11701, 11707), True, 'import numpy as np\n'), ((14860, 14876), 'numpy.all', 'np.all', (['(ind >= 0)'], {}), '(ind >= 0)\n', (14866, 14876), True, 'import numpy as np\n'), ((15924, 16069), 'tofu.geom._GG._Ves_Smesh_Lin_SubFromD_cython', '_GG._Ves_Smesh_Lin_SubFromD_cython', (['VLim[Ind[ii]]', 'dS[ii][0]', 'dS[ii][1]', 'VPoly'], {'DX': 'DS[0]', 'DY': 'DS[1]', 'DZ': 'DS[2]', 'DIn': 'DIn', 'VIn': 'VIn', 'margin': 'margin'}), '(VLim[Ind[ii]], dS[ii][0], dS[ii][1],\n VPoly, DX=DS[0], DY=DS[1], DZ=DS[2], DIn=DIn, VIn=VIn, margin=margin)\n', (15958, 16069), True, 'import tofu.geom._GG as _GG\n'), ((16178, 16193), 'numpy.ones', 'np.ones', (['(3, 0)'], {}), '((3, 0))\n', (16185, 16193), True, 'import numpy as np\n'), ((17901, 17929), 'numpy.full', 'np.full', (['(noccur, 2)', 'np.nan'], {}), '((noccur, 2), np.nan)\n', (17908, 17929), True, 'import numpy as np\n'), ((23260, 23302), 'numpy.sqrt', 'np.sqrt', (['(us[0, ...] ** 2 + us[1, ...] ** 2)'], {}), '(us[0, ...] ** 2 + us[1, ...] ** 2)\n', (23267, 23302), True, 'import numpy as np\n'), ((23517, 23554), 'numpy.zeros', 'np.zeros', (['(nlos * nseg,)'], {'dtype': 'float'}), '((nlos * nseg,), dtype=float)\n', (23525, 23554), True, 'import numpy as np\n'), ((23901, 23914), 'numpy.diff', 'np.diff', (['lind'], {}), '(lind)\n', (23908, 23914), True, 'import numpy as np\n'), ((24259, 24285), 'numpy.split', 'np.split', (['pts', 'ind'], {'axis': '(1)'}), '(pts, ind, axis=1)\n', (24267, 24285), True, 'import numpy as np\n'), ((24326, 24361), 'numpy.insert', 'np.insert', (['pts', 'ind', 'np.nan'], {'axis': '(1)'}), '(pts, ind, np.nan, axis=1)\n', (24335, 24361), True, 'import numpy as np\n'), ((25122, 25140), 'numpy.arange', 'np.arange', (['(1)', 'nlos'], {}), '(1, nlos)\n', (25131, 25140), True, 'import numpy as np\n'), ((29020, 29058), 'scipy.integrate.romb', 'scpintg.romb', (['Vals'], {'dx': 'dLr', 'show': '(False)'}), '(Vals, dx=dLr, show=False)\n', (29032, 29058), True, 'import scipy.integrate as scpintg\n'), ((31549, 31590), 'numpy.sqrt', 'np.sqrt', (['(1.0 - r ** (2)[None, :] / l ** 2)'], {}), '(1.0 - r ** (2)[None, :] / l ** 2)\n', (31556, 31590), True, 'import numpy as np\n'), ((14269, 14284), 'numpy.asarray', 'np.asarray', (['Ind'], {}), '(Ind)\n', (14279, 14284), True, 'import numpy as np\n'), ((15294, 15456), 'tofu.geom._GG._Ves_Smesh_Tor_SubFromD_cython', '_GG._Ves_Smesh_Tor_SubFromD_cython', (['dS[ii][0]', 'dS[ii][1]', 'VPoly'], {'DR': 'DS[0]', 'DZ': 'DS[1]', 'DPhi': 'DS[2]', 'DIn': 'DIn', 'VIn': 'VIn', 'PhiMinMax': 'None', 'Out': 'Out', 'margin': 'margin'}), '(dS[ii][0], dS[ii][1], VPoly, DR=DS[0],\n DZ=DS[1], DPhi=DS[2], DIn=DIn, VIn=VIn, PhiMinMax=None, Out=Out, margin\n =margin)\n', (15328, 15456), True, 'import tofu.geom._GG as _GG\n'), ((15570, 15737), 'tofu.geom._GG._Ves_Smesh_TorStruct_SubFromD_cython', '_GG._Ves_Smesh_TorStruct_SubFromD_cython', (['VLim[Ind[ii]]', 'dS[ii][0]', 'dS[ii][1]', 'VPoly'], {'DR': 'DS[0]', 'DZ': 'DS[1]', 'DPhi': 'DS[2]', 'DIn': 'DIn', 'VIn': 'VIn', 'Out': 'Out', 'margin': 'margin'}), '(VLim[Ind[ii]], dS[ii][0], dS[ii][1\n ], VPoly, DR=DS[0], DZ=DS[1], DPhi=DS[2], DIn=DIn, VIn=VIn, Out=Out,\n margin=margin)\n', (15610, 15737), True, 'import tofu.geom._GG as _GG\n'), ((17138, 17269), 'tofu.geom._GG._Ves_Smesh_Lin_SubFromInd_cython', '_GG._Ves_Smesh_Lin_SubFromInd_cython', (['VLim[Ind[ii]]', 'dS[ii][0]', 'dS[ii][1]', 'VPoly', 'ind[Ind[ii]]'], {'DIn': 'DIn', 'VIn': 'VIn', 'margin': 'margin'}), '(VLim[Ind[ii]], dS[ii][0], dS[ii][1],\n VPoly, ind[Ind[ii]], DIn=DIn, VIn=VIn, margin=margin)\n', (17174, 17269), True, 'import tofu.geom._GG as _GG\n'), ((23335, 23358), 'numpy.sum', 'np.sum', (['(us ** 2)'], {'axis': '(0)'}), '(us ** 2, axis=0)\n', (23341, 23358), True, 'import numpy as np\n'), ((24175, 24205), 'numpy.hypot', 'np.hypot', (['pts[0, :]', 'pts[1, :]'], {}), '(pts[0, :], pts[1, :])\n', (24183, 24205), True, 'import numpy as np\n'), ((24559, 24583), 'numpy.split', 'np.split', (['pts[2, :]', 'ind'], {}), '(pts[2, :], ind)\n', (24567, 24583), True, 'import numpy as np\n'), ((24771, 24804), 'numpy.insert', 'np.insert', (['pts[2, :]', 'ind', 'np.nan'], {}), '(pts[2, :], ind, np.nan)\n', (24780, 24804), True, 'import numpy as np\n'), ((25518, 25551), 'numpy.split', 'np.split', (['pts[:2, :]', 'ind'], {'axis': '(1)'}), '(pts[:2, :], ind, axis=1)\n', (25526, 25551), True, 'import numpy as np\n'), ((25599, 25625), 'numpy.split', 'np.split', (['pts', 'ind'], {'axis': '(1)'}), '(pts, ind, axis=1)\n', (25607, 25625), True, 'import numpy as np\n'), ((25786, 25810), 'numpy.split', 'np.split', (['pts[0, :]', 'ind'], {}), '(pts[0, :], ind)\n', (25794, 25810), True, 'import numpy as np\n'), ((25869, 25893), 'numpy.split', 'np.split', (['pts[1, :]', 'ind'], {}), '(pts[1, :], ind)\n', (25877, 25893), True, 'import numpy as np\n'), ((25952, 25976), 'numpy.split', 'np.split', (['pts[2, :]', 'ind'], {}), '(pts[2, :], ind)\n', (25960, 25976), True, 'import numpy as np\n'), ((27687, 27702), 'numpy.arange', 'np.arange', (['(0)', 'N'], {}), '(0, N)\n', (27696, 27702), True, 'import numpy as np\n'), ((28542, 28572), 'numpy.tile', 'np.tile', (['(-u)', '(Pts.shape[1], 1)'], {}), '(-u, (Pts.shape[1], 1))\n', (28549, 28572), True, 'import numpy as np\n'), ((14571, 14591), 'numpy.all', 'np.all', (['(ind[ii] >= 0)'], {}), '(ind[ii] >= 0)\n', (14577, 14591), True, 'import numpy as np\n'), ((16502, 16644), 'tofu.geom._GG._Ves_Smesh_Tor_SubFromInd_cython', '_GG._Ves_Smesh_Tor_SubFromInd_cython', (['dS[ii][0]', 'dS[ii][1]', 'VPoly', 'ind[Ind[ii]]'], {'DIn': 'DIn', 'VIn': 'VIn', 'PhiMinMax': 'None', 'Out': 'Out', 'margin': 'margin'}), '(dS[ii][0], dS[ii][1], VPoly, ind[Ind[\n ii]], DIn=DIn, VIn=VIn, PhiMinMax=None, Out=Out, margin=margin)\n', (16538, 16644), True, 'import tofu.geom._GG as _GG\n'), ((16761, 16908), 'tofu.geom._GG._Ves_Smesh_TorStruct_SubFromInd_cython', '_GG._Ves_Smesh_TorStruct_SubFromInd_cython', (['VLim[Ind[ii]]', 'dS[ii][0]', 'dS[ii][1]', 'VPoly', 'ind[Ind[ii]]'], {'DIn': 'DIn', 'VIn': 'VIn', 'Out': 'Out', 'margin': 'margin'}), '(VLim[Ind[ii]], dS[ii][0], dS[ii]\n [1], VPoly, ind[Ind[ii]], DIn=DIn, VIn=VIn, Out=Out, margin=margin)\n', (16803, 16908), True, 'import tofu.geom._GG as _GG\n'), ((24466, 24496), 'numpy.hypot', 'np.hypot', (['pts[0, :]', 'pts[1, :]'], {}), '(pts[0, :], pts[1, :])\n', (24474, 24496), True, 'import numpy as np\n'), ((24670, 24700), 'numpy.hypot', 'np.hypot', (['pts[0, :]', 'pts[1, :]'], {}), '(pts[0, :], pts[1, :])\n', (24678, 24700), True, 'import numpy as np\n'), ((27563, 27572), 'numpy.log', 'np.log', (['N'], {}), '(N)\n', (27569, 27572), True, 'import numpy as np\n'), ((27573, 27584), 'numpy.log', 'np.log', (['(2.0)'], {}), '(2.0)\n', (27579, 27584), True, 'import numpy as np\n')]
|
"""Random subset dataset.
"""
import random
import numpy as np
import torch
from torch.utils.data import Dataset
from PIL import Image
class RandomSubset(Dataset):
"""Class allows to iterate every epoch through a different random subset of the original
dataset.
The intention behind this class is to speed up genetic optimization by using only a small subset
of the original dataset every epoch. The subset is randomly created every epoch from the
original dataset. Therefore, all samples from the original dataset are used at some point during
the training.
"""
def __init__(self, dataset: Dataset, subset_ratio: float) -> None:
"""
Args:
dataset: PyTorch dataset.
subset_ratio: Defines size of subset.
"""
super().__init__()
self.dataset = dataset
if isinstance(dataset.data, np.ndarray):
self.data = dataset.data
elif isinstance(dataset.data, list):
self.data = np.array(dataset.data)
elif isinstance(dataset.data, torch.Tensor):
self.data = dataset.data.numpy()
else:
raise TypeError(f"Targets must be of type 'list' or 'tensor', "
f"but got {type(dataset.data)}.")
if isinstance(dataset.targets, np.ndarray):
self.data = dataset.data
elif isinstance(dataset.targets, list):
self.targets = np.array(dataset.targets)
elif isinstance(dataset.targets, torch.Tensor):
self.targets = dataset.targets.numpy()
else:
raise TypeError(f"Targets must be of type 'list' or 'tensor', "
f"but got {type(dataset.targets)}.")
self.subset_length = int(len(self.data) * subset_ratio)
self.counter = 0
self._random_subset()
def _random_subset(self) -> None:
"""Creates random mappings.
"""
self.rand_map = random.sample(list(range(len(self.data))), self.subset_length)
def __len__(self) -> int:
return self.subset_length
def __getitem__(self, index: int) -> tuple:
self.counter += 1
if self.counter > self.subset_length:
self._random_subset()
self.counter = 0
rand_index = self.rand_map[index]
img, target = self.data[rand_index], int(self.targets[rand_index])
# Cast to PIL Image required for transformations.
if len(img.shape) == 2:
img = Image.fromarray(img, mode="L")
elif (len(img.shape) == 3) and (img.shape[-1] == 3):
img = Image.fromarray(img, mode="RGB")
if self.dataset.transform is not None:
img = self.dataset.transform(img)
return img, target
|
[
"numpy.array",
"PIL.Image.fromarray"
] |
[((2511, 2541), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {'mode': '"""L"""'}), "(img, mode='L')\n", (2526, 2541), False, 'from PIL import Image\n'), ((1013, 1035), 'numpy.array', 'np.array', (['dataset.data'], {}), '(dataset.data)\n', (1021, 1035), True, 'import numpy as np\n'), ((1451, 1476), 'numpy.array', 'np.array', (['dataset.targets'], {}), '(dataset.targets)\n', (1459, 1476), True, 'import numpy as np\n'), ((2621, 2653), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {'mode': '"""RGB"""'}), "(img, mode='RGB')\n", (2636, 2653), False, 'from PIL import Image\n')]
|
import numpy
import matplotlib.pyplot as plt
x = numpy.random.normal(1.9, 1.0, 109324)
plt.hist(x, 100)
plt.show()
|
[
"numpy.random.normal",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.show"
] |
[((50, 87), 'numpy.random.normal', 'numpy.random.normal', (['(1.9)', '(1.0)', '(109324)'], {}), '(1.9, 1.0, 109324)\n', (69, 87), False, 'import numpy\n'), ((89, 105), 'matplotlib.pyplot.hist', 'plt.hist', (['x', '(100)'], {}), '(x, 100)\n', (97, 105), True, 'import matplotlib.pyplot as plt\n'), ((106, 116), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (114, 116), True, 'import matplotlib.pyplot as plt\n')]
|
import numpy as np
vector = np.array([5, 10, 15, 20])
equal_to_ten = (vector == 10)
print(equal_to_ten)
matrix = np.array([[10, 25, 30], [45, 50, 55], [60, 65, 70]])
equal_to_25 = (matrix[:, 1]) == 25
print(equal_to_25)
##Lire le dataset world_alcohol.csv dans la variable world_alcohol
world_alcohol = np.genfromtxt('world_alcohol.csv', delimiter = ',', dtype = 'U75', skip_header = 1)
#Extraire le 3e colonne de world_alcohol et comparer la au pays "Canada". Assigner le résultat à la variable countries_canada
countries_canada = world_alcohol[:, 2]
print(countries_canada == 'Canada')
#Xtraire la première colonne de world_alcohol et comparer la chaine de caratères "1984". Assigner les résultat à la variable years_1984
years_1984 = world_alcohol[:, 0]
print(years_1984 == '1984')
|
[
"numpy.array",
"numpy.genfromtxt"
] |
[((29, 54), 'numpy.array', 'np.array', (['[5, 10, 15, 20]'], {}), '([5, 10, 15, 20])\n', (37, 54), True, 'import numpy as np\n'), ((118, 170), 'numpy.array', 'np.array', (['[[10, 25, 30], [45, 50, 55], [60, 65, 70]]'], {}), '([[10, 25, 30], [45, 50, 55], [60, 65, 70]])\n', (126, 170), True, 'import numpy as np\n'), ((313, 390), 'numpy.genfromtxt', 'np.genfromtxt', (['"""world_alcohol.csv"""'], {'delimiter': '""","""', 'dtype': '"""U75"""', 'skip_header': '(1)'}), "('world_alcohol.csv', delimiter=',', dtype='U75', skip_header=1)\n", (326, 390), True, 'import numpy as np\n')]
|
# Copyright 2021 Google
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from . import circuit_blocks
import cirq
import cirq_google
import numpy as np
_qubits = cirq.LineQubit.range(2)
@pytest.mark.parametrize(
"known_circuit, compiled_ops",
(
([cirq.SWAP(*_qubits)], circuit_blocks.swap_block(_qubits)),
(
[cirq.H(_qubits[0]), cirq.CNOT(*_qubits)],
circuit_blocks.bell_pair_block(_qubits),
),
(
[cirq.CNOT(*_qubits), cirq.H(_qubits[0])],
circuit_blocks.un_bell_pair_block(_qubits),
),
(
[
cirq.X(_qubits[0]) ** 0.5,
cirq.PhasedXZGate(
axis_phase_exponent=0.25, x_exponent=0.5, z_exponent=0
)(_qubits[1]),
cirq_google.SycamoreGate()(*_qubits),
],
circuit_blocks.scrambling_block(_qubits, [0, 3]),
),
(
[
cirq.Y(_qubits[0]) ** 0.5,
cirq.Y(_qubits[1]) ** 0.5,
cirq_google.SycamoreGate()(*_qubits),
],
circuit_blocks.scrambling_block(_qubits, [2, 2]),
),
),
)
def test_known_blocks_equal(known_circuit, compiled_ops):
desired_u = cirq.unitary(cirq.Circuit(known_circuit))
actual_u = cirq.unitary(cirq.Circuit(compiled_ops))
assert cirq.equal_up_to_global_phase(actual_u, desired_u)
def test_tsym_block_real():
tsym_circuit = circuit_blocks.tsym_block(_qubits, [0, 0]) # no rotations.
tsym_u = cirq.unitary(cirq.Circuit(tsym_circuit))
assert np.all(tsym_u.imag < 1e-6)
def test_block_1d_circuit():
depth = 8
n_qubits = 11
qubits = cirq.LineQubit.range(n_qubits)
def _simple_fun(pairs, unused):
assert len(unused) == 1
return [cirq.CNOT(*pairs).with_tags(str(unused[0]))]
test_block_circuit = circuit_blocks.block_1d_circuit(
qubits, depth, _simple_fun, np.vstack(np.arange((depth * len(qubits) // 2)))
)
assert len(test_block_circuit) == depth
assert len(test_block_circuit.all_qubits()) == n_qubits
tot_i = 0
for i, mom in enumerate(test_block_circuit):
for op in mom:
assert isinstance(op.gate, type(cirq.CNOT))
assert op.tags[0] == str(tot_i)
tot_i += 1
# Number of operations and working depth will
# always have parity that disagrees if number of
# qubits is odd.
assert i % 2 != tot_i % 2
def test_z_basis_gate():
assert circuit_blocks.inv_z_basis_gate("Z") == cirq.I
assert circuit_blocks.inv_z_basis_gate("X") == cirq.H
assert circuit_blocks.inv_z_basis_gate("Y") == cirq.PhasedXZGate(
axis_phase_exponent=-0.5, x_exponent=0.5, z_exponent=-0.5
)
|
[
"cirq.equal_up_to_global_phase",
"cirq.SWAP",
"cirq.CNOT",
"cirq.H",
"cirq.LineQubit.range",
"cirq.Circuit",
"cirq.PhasedXZGate",
"cirq.Y",
"cirq_google.SycamoreGate",
"cirq.X",
"numpy.all"
] |
[((676, 699), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['(2)'], {}), '(2)\n', (696, 699), False, 'import cirq\n'), ((1893, 1943), 'cirq.equal_up_to_global_phase', 'cirq.equal_up_to_global_phase', (['actual_u', 'desired_u'], {}), '(actual_u, desired_u)\n', (1922, 1943), False, 'import cirq\n'), ((2118, 2145), 'numpy.all', 'np.all', (['(tsym_u.imag < 1e-06)'], {}), '(tsym_u.imag < 1e-06)\n', (2124, 2145), True, 'import numpy as np\n'), ((2221, 2251), 'cirq.LineQubit.range', 'cirq.LineQubit.range', (['n_qubits'], {}), '(n_qubits)\n', (2241, 2251), False, 'import cirq\n'), ((1797, 1824), 'cirq.Circuit', 'cirq.Circuit', (['known_circuit'], {}), '(known_circuit)\n', (1809, 1824), False, 'import cirq\n'), ((1854, 1880), 'cirq.Circuit', 'cirq.Circuit', (['compiled_ops'], {}), '(compiled_ops)\n', (1866, 1880), False, 'import cirq\n'), ((2079, 2105), 'cirq.Circuit', 'cirq.Circuit', (['tsym_circuit'], {}), '(tsym_circuit)\n', (2091, 2105), False, 'import cirq\n'), ((3211, 3287), 'cirq.PhasedXZGate', 'cirq.PhasedXZGate', ([], {'axis_phase_exponent': '(-0.5)', 'x_exponent': '(0.5)', 'z_exponent': '(-0.5)'}), '(axis_phase_exponent=-0.5, x_exponent=0.5, z_exponent=-0.5)\n', (3228, 3287), False, 'import cirq\n'), ((779, 798), 'cirq.SWAP', 'cirq.SWAP', (['*_qubits'], {}), '(*_qubits)\n', (788, 798), False, 'import cirq\n'), ((861, 879), 'cirq.H', 'cirq.H', (['_qubits[0]'], {}), '(_qubits[0])\n', (867, 879), False, 'import cirq\n'), ((881, 900), 'cirq.CNOT', 'cirq.CNOT', (['*_qubits'], {}), '(*_qubits)\n', (890, 900), False, 'import cirq\n'), ((990, 1009), 'cirq.CNOT', 'cirq.CNOT', (['*_qubits'], {}), '(*_qubits)\n', (999, 1009), False, 'import cirq\n'), ((1011, 1029), 'cirq.H', 'cirq.H', (['_qubits[0]'], {}), '(_qubits[0])\n', (1017, 1029), False, 'import cirq\n'), ((1139, 1157), 'cirq.X', 'cirq.X', (['_qubits[0]'], {}), '(_qubits[0])\n', (1145, 1157), False, 'import cirq\n'), ((1182, 1255), 'cirq.PhasedXZGate', 'cirq.PhasedXZGate', ([], {'axis_phase_exponent': '(0.25)', 'x_exponent': '(0.5)', 'z_exponent': '(0)'}), '(axis_phase_exponent=0.25, x_exponent=0.5, z_exponent=0)\n', (1199, 1255), False, 'import cirq\n'), ((1323, 1349), 'cirq_google.SycamoreGate', 'cirq_google.SycamoreGate', ([], {}), '()\n', (1347, 1349), False, 'import cirq_google\n'), ((1489, 1507), 'cirq.Y', 'cirq.Y', (['_qubits[0]'], {}), '(_qubits[0])\n', (1495, 1507), False, 'import cirq\n'), ((1532, 1550), 'cirq.Y', 'cirq.Y', (['_qubits[1]'], {}), '(_qubits[1])\n', (1538, 1550), False, 'import cirq\n'), ((1575, 1601), 'cirq_google.SycamoreGate', 'cirq_google.SycamoreGate', ([], {}), '()\n', (1599, 1601), False, 'import cirq_google\n'), ((2337, 2354), 'cirq.CNOT', 'cirq.CNOT', (['*pairs'], {}), '(*pairs)\n', (2346, 2354), False, 'import cirq\n')]
|
from pyimagesearch.centroidtracker import CentroidTracker
from pyimagesearch.trackableobject import TrackableObject
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
help="path to Caffe pre-trained model")
ap.add_argument("-i", "--input", type=str,
help="path to optional input video file")
ap.add_argument("-o", "--output", type=str,
help="path to optional output video file")
ap.add_argument("-c", "--confidence", type=float, default=0.4,
help="minimum probability to filter weak detections")
ap.add_argument("-s", "--skip-frames", type=int, default=30,
help="# of skip frames between detections")
args = vars(ap.parse_args())
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
"sofa", "train", "tvmonitor"]
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
if not args.get("input", False):
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
# otherwise, grab a reference to the video file
else:
print("[INFO] opening video file...")
vs = cv2.VideoCapture(args["input"])
writer = None
# initialize the frame dimensions (we'll set them as soon as we read
# the first frame from the video)
W = None
H = None
# instantiate our centroid tracker, then initialize a list to store
# each of our dlib correlation trackers, followed by a dictionary to
# map each unique object ID to a TrackableObject
ct = CentroidTracker(maxDisappeared=40, maxDistance=50)
trackers = []
trackableObjects = {}
# initialize the total number of frames processed thus far, along
# with the total number of objects that have moved either up or down
totalFrames = 0
totalDown = 0
totalUp = 0
# start the frames per second throughput estimator
fps = FPS().start()
while True:
# grab the next frame and handle if we are reading from either
# VideoCapture or VideoStream
frame = vs.read()
frame = frame[1] if args.get("input", False) else frame
# if we are viewing a video and we did not grab a frame then we
# have reached the end of the video
if args["input"] is not None and frame is None:
break
# resize the frame to have a maximum width of 500 pixels (the
# less data we have, the faster we can process it), then convert
# the frame from BGR to RGB for dlib
frame = imutils.resize(frame, width=500)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# if the frame dimensions are empty, set them
if W is None or H is None:
(H, W) = frame.shape[:2]
# if we are supposed to be writing a video to disk, initialize
# the writer
if args["output"] is not None and writer is None:
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter(args["output"], fourcc, 30,
(W, H), True)
status = "Waiting"
rects = []
# check to see if we should run a more computationally expensive
# object detection method to aid our tracker
if totalFrames % args["skip_frames"] == 0:
# set the status and initialize our new set of object trackers
status = "Detecting"
trackers = []
# convert the frame to a blob and pass the blob through the
# network and obtain the detections
blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)
net.setInput(blob)
detections = net.forward()
for i in np.arange(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated
# with the prediction
confidence = detections[0, 0, i, 2]
# filter out weak detections by requiring a minimum
# confidence
if confidence > args["confidence"]:
# extract the index of the class label from the
# detections list
idx = int(detections[0, 0, i, 1])
# if the class label is not a person, ignore it
if CLASSES[idx] != "person":
continue
box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])
(startX, startY, endX, endY) = box.astype("int")
# construct a dlib rectangle object from the bounding
# box coordinates and then start the dlib correlation
# tracker
tracker = dlib.correlation_tracker()
rect = dlib.rectangle(startX, startY, endX, endY)
tracker.start_track(rgb, rect)
# add the tracker to our list of trackers so we can
# utilize it during skip frames
trackers.append(tracker)
else:
# loop over the trackers
for tracker in trackers:
# set the status of our system to be 'tracking' rather
# than 'waiting' or 'detecting'
status = "Tracking"
# update the tracker and grab the updated position
tracker.update(rgb)
pos = tracker.get_position()
# unpack the position object
startX = int(pos.left())
startY = int(pos.top())
endX = int(pos.right())
endY = int(pos.bottom())
# add the bounding box coordinates to the rectangles list
rects.append((startX, startY, endX, endY))
cv2.line(frame, (0, H // 2), (W, H // 2), (0, 255, 255), 2)
# use the centroid tracker to associate the (1) old object
# centroids with (2) the newly computed object centroids
objects = ct.update(rects)
text = "ID {}".format(objectID)
cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)
# construct a tuple of information we will be displaying on the
# frame
info = [
("Up", totalUp),
("Down", totalDown),
("Status", status),
]
# loop over the info tuples and draw them on our frame
for (i, (k, v)) in enumerate(info):
text = "{}: {}".format(k, v)
cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
if writer is not None:
writer.write(frame)
# show the output frame
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the q key was pressed, break from the loop
if key == ord("q"):
break
# increment the total number of frames processed thus far and
# then update the FPS counter
totalFrames += 1
fps.update()
fps.stop()
# check to see if we need to release the video writer pointer
if writer is not None:
writer.release()
# if we are not using a video file, stop the camera video stream
if not args.get("input", False):
vs.stop()
# otherwise, release the video file pointer
else:
vs.release()
# close any open windows
cv2.destroyAllWindows()
|
[
"time.sleep",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"numpy.arange",
"imutils.video.VideoStream",
"argparse.ArgumentParser",
"dlib.rectangle",
"cv2.line",
"cv2.dnn.readNetFromCaffe",
"cv2.VideoWriter",
"imutils.video.FPS",
"cv2.VideoWriter_fourcc",
"cv2.waitKey",
"cv2.dnn.blobFromImage",
"dlib.correlation_tracker",
"cv2.putText",
"cv2.circle",
"cv2.cvtColor",
"pyimagesearch.centroidtracker.CentroidTracker",
"imutils.resize",
"cv2.VideoCapture"
] |
[((276, 301), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (299, 301), False, 'import argparse\n'), ((1220, 1277), 'cv2.dnn.readNetFromCaffe', 'cv2.dnn.readNetFromCaffe', (["args['prototxt']", "args['model']"], {}), "(args['prototxt'], args['model'])\n", (1244, 1277), False, 'import cv2\n'), ((1874, 1924), 'pyimagesearch.centroidtracker.CentroidTracker', 'CentroidTracker', ([], {'maxDisappeared': '(40)', 'maxDistance': '(50)'}), '(maxDisappeared=40, maxDistance=50)\n', (1889, 1924), False, 'from pyimagesearch.centroidtracker import CentroidTracker\n'), ((3699, 3732), 'numpy.arange', 'np.arange', (['(0)', 'detections.shape[2]'], {}), '(0, detections.shape[2])\n', (3708, 3732), True, 'import numpy as np\n'), ((5362, 5421), 'cv2.line', 'cv2.line', (['frame', '(0, H // 2)', '(W, H // 2)', '(0, 255, 255)', '(2)'], {}), '(frame, (0, H // 2), (W, H // 2), (0, 255, 255), 2)\n', (5370, 5421), False, 'import cv2\n'), ((5600, 5714), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(centroid[0] - 10, centroid[1] - 10)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.5)', '(0, 255, 0)', '(2)'], {}), '(frame, text, (centroid[0] - 10, centroid[1] - 10), cv2.\n FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n', (5611, 5714), False, 'import cv2\n'), ((5710, 5775), 'cv2.circle', 'cv2.circle', (['frame', '(centroid[0], centroid[1])', '(4)', '(0, 255, 0)', '(-1)'], {}), '(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)\n', (5720, 5775), False, 'import cv2\n'), ((6860, 6883), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6881, 6883), False, 'import cv2\n'), ((1390, 1405), 'time.sleep', 'time.sleep', (['(2.0)'], {}), '(2.0)\n', (1400, 1405), False, 'import time\n'), ((1507, 1538), 'cv2.VideoCapture', 'cv2.VideoCapture', (["args['input']"], {}), "(args['input'])\n", (1523, 1538), False, 'import cv2\n'), ((2738, 2770), 'imutils.resize', 'imutils.resize', (['frame'], {'width': '(500)'}), '(frame, width=500)\n', (2752, 2770), False, 'import imutils\n'), ((2778, 2816), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (2790, 2816), False, 'import cv2\n'), ((3581, 3634), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['frame', '(0.007843)', '(W, H)', '(127.5)'], {}), '(frame, 0.007843, (W, H), 127.5)\n', (3602, 3634), False, 'import cv2\n'), ((6059, 6159), 'cv2.putText', 'cv2.putText', (['frame', 'text', '(10, H - (i * 20 + 20))', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.6)', '(0, 0, 255)', '(2)'], {}), '(frame, text, (10, H - (i * 20 + 20)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.6, (0, 0, 255), 2)\n', (6070, 6159), False, 'import cv2\n'), ((2199, 2204), 'imutils.video.FPS', 'FPS', ([], {}), '()\n', (2202, 2204), False, 'from imutils.video import FPS\n'), ((3063, 3094), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (3085, 3094), False, 'import cv2\n'), ((3106, 3163), 'cv2.VideoWriter', 'cv2.VideoWriter', (["args['output']", 'fourcc', '(30)', '(W, H)', '(True)'], {}), "(args['output'], fourcc, 30, (W, H), True)\n", (3121, 3163), False, 'import cv2\n'), ((6256, 6282), 'cv2.imshow', 'cv2.imshow', (['"""Frame"""', 'frame'], {}), "('Frame', frame)\n", (6266, 6282), False, 'import cv2\n'), ((1362, 1380), 'imutils.video.VideoStream', 'VideoStream', ([], {'src': '(0)'}), '(src=0)\n', (1373, 1380), False, 'from imutils.video import VideoStream\n'), ((4481, 4507), 'dlib.correlation_tracker', 'dlib.correlation_tracker', ([], {}), '()\n', (4505, 4507), False, 'import dlib\n'), ((4520, 4562), 'dlib.rectangle', 'dlib.rectangle', (['startX', 'startY', 'endX', 'endY'], {}), '(startX, startY, endX, endY)\n', (4534, 4562), False, 'import dlib\n'), ((6297, 6311), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (6308, 6311), False, 'import cv2\n'), ((4222, 4244), 'numpy.array', 'np.array', (['[W, H, W, H]'], {}), '([W, H, W, H])\n', (4230, 4244), True, 'import numpy as np\n')]
|
from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist
from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, \
get_paratext_dict
from util.Data import InputTRECCARExample
import numpy as np
import torch
import torch.nn as nn
from torch import Tensor
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from typing import Dict, Iterable, List
import transformers
from sentence_transformers import SentenceTransformer
from sentence_transformers import models
from sentence_transformers.evaluation import SentenceEvaluator
from sentence_transformers.util import batch_to_device
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score, adjusted_mutual_info_score
from tqdm.autonotebook import trange
from clearml import Task
import pickle
import argparse
import random
random.seed(42)
torch.manual_seed(42)
np.random.seed(42)
def prepare_cluster_data_train(pages_file, art_qrels, top_qrels, paratext):
page_paras, rev_para_top, _ = get_trec_dat(art_qrels, top_qrels, None)
ptext_dict = get_paratext_dict(paratext)
top_cluster_data = []
pages = []
with open(pages_file, 'r') as f:
for l in f:
pages.append(l.rstrip('\n'))
for i in trange(len(pages)):
page = pages[i]
paras = page_paras[page]
paratexts = [ptext_dict[p] for p in paras]
top_sections = list(set([rev_para_top[p] for p in paras]))
if len(top_sections) < 2:
continue
top_labels = [top_sections.index(rev_para_top[p]) for p in paras]
query_text = ' '.join(page.split('enwiki:')[1].split('%20'))
top_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=paras, texts=paratexts,
label=np.array(top_labels)))
print('Total data instances: %5d' % len(top_cluster_data))
return top_cluster_data
def prepare_cluster_data_for_eval(art_qrels, top_qrels, paratext, do_filter, val_samples):
page_paras, rev_para_top, _ = get_trec_dat(art_qrels, top_qrels, None)
len_paras = np.array([len(page_paras[page]) for page in page_paras.keys()])
print('mean paras: %.2f, std: %.2f, max paras: %.2f' % (np.mean(len_paras), np.std(len_paras), np.max(len_paras)))
ptext_dict = get_paratext_dict(paratext)
top_cluster_data = []
pages = list(page_paras.keys())
skipped_pages = 0
max_num_doc = max([len(page_paras[p]) for p in page_paras.keys()])
for i in trange(len(pages)):
page = pages[i]
paras = page_paras[page]
paratexts = [ptext_dict[p] for p in paras]
top_sections = list(set([rev_para_top[p] for p in paras]))
top_labels = [top_sections.index(rev_para_top[p]) for p in paras]
query_text = ' '.join(page.split('enwiki:')[1].split('%20'))
n = len(paras)
if do_filter:
if n < 20 or n > 200:
skipped_pages += 1
continue
paras = paras[:max_num_doc] if n >= max_num_doc else paras + ['dummy'] * (max_num_doc - n)
paratexts = paratexts[:max_num_doc] if n >= max_num_doc else paratexts + [''] * (max_num_doc - n)
top_labels = top_labels[:max_num_doc] if n >= max_num_doc else top_labels + [-1] * (max_num_doc - n)
if do_filter:
if len(set(top_labels)) < 2 or n / len(set(top_labels)) < 2.5:
## the page should have at least 2 top level sections and n/k should be at least 2.5
skipped_pages += 1
continue
top_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=paras, texts=paratexts,
label=np.array(top_labels)))
if val_samples > 0:
top_cluster_data = top_cluster_data[:val_samples]
print('Total data instances: %5d' % len(top_cluster_data))
return top_cluster_data
class QuerySpecificClusterModel(nn.Module):
def __init__(self, path:str=None, query_transformer:CustomSentenceTransformer=None,
psg_transformer:CustomSentenceTransformer=None, device:torch.device=None):
super(QuerySpecificClusterModel, self).__init__()
if path is not None:
self.query_model = CustomSentenceTransformer(path+'/query_model')
self.psg_model = CustomSentenceTransformer(path+'/psg_model')
else:
self.query_model = query_transformer
self.psg_model = psg_transformer
self.optim = OptimCluster
self.device = device
def save(self, path):
self.query_model.save(path+'/query_model')
self.psg_model.save(path+'/psg_model')
def _get_scheduler(self, optimizer, scheduler: str, warmup_steps: int, t_total: int):
"""
Taken from SentenceTransformers
Returns the correct learning rate scheduler
"""
scheduler = scheduler.lower()
if scheduler == 'constantlr':
return transformers.get_constant_schedule(optimizer)
elif scheduler == 'warmupconstant':
return transformers.get_constant_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps)
elif scheduler == 'warmuplinear':
return transformers.get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps,
num_training_steps=t_total)
elif scheduler == 'warmupcosine':
return transformers.get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps,
num_training_steps=t_total)
elif scheduler == 'warmupcosinewithhardrestarts':
return transformers.get_cosine_with_hard_restarts_schedule_with_warmup(optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=t_total)
else:
raise ValueError("Unknown scheduler {}".format(scheduler))
def query_batch_collate_fn(self, batch):
num_texts = len(batch[0].texts)
queries = []
texts = [[] for _ in range(num_texts)]
labels = []
for example in batch:
queries.append(example.q_context)
for idx, text in enumerate(example.texts):
texts[idx].append(text)
labels.append(example.label)
labels = torch.tensor(labels).to(self.device)
q_tokenized = self.query_model.tokenize(queries)
batch_to_device(q_tokenized, self.device)
psg_features = []
for idx in range(num_texts):
p_tokenized = self.psg_model.tokenize(texts[idx])
batch_to_device(p_tokenized, self.device)
psg_features.append(p_tokenized)
return q_tokenized, psg_features, labels
def forward(self, query_feature: Dict[str, Tensor], passage_features: Iterable[Dict[str, Tensor]], labels: Tensor):
n = labels.shape[1]
query_embedding = self.query_model(query_feature)['sentence_embedding']
# its the scaling vector, so each element in vector should be [0, 1]
psg_embeddings = torch.stack([self.psg_model(passages)['sentence_embedding']
for passages in passage_features], dim=1)
scaled_psg_embeddings = torch.tile(query_embedding.unsqueeze(1), (1, n, 1)) * psg_embeddings
return scaled_psg_embeddings
class BBClusterLossModel(nn.Module):
def __init__(self, model: QuerySpecificClusterModel, device, lambda_val: float, reg_const: float):
super(BBClusterLossModel, self).__init__()
self.model = model
self.lambda_val = lambda_val
self.reg = reg_const
self.optim = OptimCluster()
self.device = device
def true_adj_mat(self, label):
n = label.numel()
adj_mat = torch.zeros((n, n))
for i in range(n):
for j in range(n):
if i == j or label[i] == label[j]:
adj_mat[i][j] = 1.0
return adj_mat
def forward(self, query_feature: Dict[str, Tensor], passage_features: Iterable[Dict[str, Tensor]], labels: Tensor):
batch_size = labels.shape[0]
n = labels.shape[1]
ks = [torch.unique(labels[i]).numel() for i in range(batch_size)]
true_adjacency_mats = torch.stack([self.true_adj_mat(labels[i]) for i in range(batch_size)]).to(self.device)
query_embedding = self.model.query_model(query_feature)['sentence_embedding']
# its the scaling vector, so each element in vector should be [0, 1]
psg_embeddings = torch.stack([self.model.psg_model(passages)['sentence_embedding']
for passages in passage_features], dim=1)
scaled_psg_embeddings = torch.tile(query_embedding.unsqueeze(1), (1, n, 1)) * psg_embeddings
embeddings_dist_mats = torch.stack([euclid_dist(scaled_psg_embeddings[i]) for i in range(batch_size)])
mean_similar_dist = (embeddings_dist_mats * true_adjacency_mats).sum() / true_adjacency_mats.sum()
mean_dissimilar_dist = (embeddings_dist_mats * (1.0 - true_adjacency_mats)).sum() / (
1 - true_adjacency_mats).sum()
adjacency_mats = self.optim.apply(embeddings_dist_mats, self.lambda_val, ks).to(self.device)
err_mats = adjacency_mats * (1.0 - true_adjacency_mats) + (1.0 - adjacency_mats) * true_adjacency_mats
err_mean = err_mats.mean(dim=0).sum()
loss = err_mean + self.reg * (mean_similar_dist - mean_dissimilar_dist)
return loss
class BBClusterRNNLossModel(nn.Module):
def __init__(self, model: QuerySpecificClusterModel, device, lambda_val: float, reg_const: float):
super(BBClusterRNNLossModel, self).__init__()
self.model = model
self.lambda_val = lambda_val
self.reg = reg_const
self.optim = OptimCluster()
self.device = device
def true_adj_mat(self, label):
n = label.numel()
adj_mat = torch.zeros((n, n))
for i in range(n):
for j in range(n):
if i == j or label[i] == label[j]:
adj_mat[i][j] = 1.0
return adj_mat
def forward(self, query_feature: Dict[str, Tensor], passage_features: Iterable[Dict[str, Tensor]], labels: Tensor):
batch_size = labels.shape[0]
n = labels.shape[1]
ks = [torch.unique(labels[i]).numel() for i in range(batch_size)]
true_adjacency_mats = torch.stack([self.true_adj_mat(labels[i]) for i in range(batch_size)]).to(self.device)
psg_embeddings = torch.stack([self.model.psg_model(passages)['sentence_embedding']
for passages in passage_features], dim=1)
scaling_vector = torch.tensor([0])
# obtain the scaling vector from psg_embeddngs using RNN
scaled_psg_embeddings = torch.tile(scaling_vector.unsqueeze(1), (1, n, 1)) * psg_embeddings
embeddings_dist_mats = torch.stack([euclid_dist(scaled_psg_embeddings[i]) for i in range(batch_size)])
mean_similar_dist = (embeddings_dist_mats * true_adjacency_mats).sum() / true_adjacency_mats.sum()
mean_dissimilar_dist = (embeddings_dist_mats * (1.0 - true_adjacency_mats)).sum() / (
1 - true_adjacency_mats).sum()
adjacency_mats = self.optim.apply(embeddings_dist_mats, self.lambda_val, ks).to(self.device)
err_mats = adjacency_mats * (1.0 - true_adjacency_mats) + (1.0 - adjacency_mats) * true_adjacency_mats
err_mean = err_mats.mean(dim=0).sum()
loss = err_mean + self.reg * (mean_similar_dist - mean_dissimilar_dist)
return loss
class QueryClusterEvaluator(SentenceEvaluator):
def __init__(self, queries: List[str], passages: List[List[str]], labels: List[Tensor], use_model_device=True):
self.queries = queries
self.passages = passages
self.labels = labels
self.use_model_device = use_model_device
@classmethod
def from_input_examples(cls, examples: List[InputTRECCARExample], use_model_device, **kwargs):
queries = []
passages = []
labels = []
for example in examples:
queries.append(example.q_context)
passages.append(example.texts)
labels.append(torch.from_numpy(example.label))
return cls(queries=queries, passages=passages, labels=labels, use_model_device=use_model_device, **kwargs)
def euclid_dist(self, x):
dist_mat = torch.norm(x[:, None] - x, dim=2, p=2)
return dist_mat
def __call__(self, model, output_path: str = None, epoch: int = -1, steps: int = -1) -> float:
rand_scores, nmi_scores, ami_scores = [], [], []
model_device = model.device
if not self.use_model_device:
model.cpu()
for i in trange(len(self.queries), desc="Evaluating on val", smoothing=0.05):
query = self.queries[i]
passages_to_cluster = [self.passages[i][p] for p in range(len(self.passages[i]))
if len(self.passages[i][p])>0]
true_label = self.labels[i][:len(passages_to_cluster)]
query_feature = model.query_model.tokenize(query)
doc_features = model.psg_model.tokenize(passages_to_cluster)
if self.use_model_device:
batch_to_device(doc_features, model_device)
query_embedding = model.query_model(query_feature)['sentence_embedding']
psg_embeddings = model.psg_model(doc_features)['sentence_embedding']
scaled_psg_embeddings = query_embedding * psg_embeddings
embeddings_dist_mat = self.euclid_dist(scaled_psg_embeddings)
cl = AgglomerativeClustering(n_clusters=torch.unique(true_label).numel(), affinity='precomputed',
linkage='average')
cluster_label = cl.fit_predict(embeddings_dist_mat.detach().cpu().numpy())
rand_scores.append(adjusted_rand_score(true_label.numpy(), cluster_label))
nmi_scores.append(normalized_mutual_info_score(true_label.numpy(), cluster_label))
ami_scores.append(adjusted_mutual_info_score(true_label.numpy(), cluster_label))
mean_rand = np.mean(np.array(rand_scores))
mean_nmi = np.mean(np.array(nmi_scores))
mean_ami = np.mean(np.array(ami_scores))
print("\nRAND: %.5f, NMI: %.5f, AMI: %.5f\n" % (mean_rand, mean_nmi, mean_ami), flush=True)
if not self.use_model_device:
model.to(model_device)
return mean_rand
def train(train_cluster_data, val_cluster_data, test_cluster_data, output_path, eval_steps,
num_epochs, warmup_frac, lambda_val, reg, use_model_device, max_train_size=-1, train_psg_model=False,
model_name='distilbert-base-uncased', out_features=256, steps_per_epoch=None, weight_decay=0.01,
optimizer_class=transformers.AdamW, scheduler='WarmupLinear', optimizer_params={'lr':2e-5},
show_progress_bar=True, max_grad_norm=1, save_best_model=True):
tensorboard_writer = SummaryWriter('./tensorboard_logs')
task = Task.init(project_name='Query Specific BB Clustering', task_name='query_bbc_fixed_lambda')
config_dict = {'lambda_val': lambda_val, 'reg': reg}
config_dict = task.connect(config_dict)
if torch.cuda.is_available():
device = torch.device('cuda')
print('CUDA is available and using device: '+str(device))
else:
device = torch.device('cpu')
print('CUDA not available, using device: '+str(device))
### Configure sentence transformers for training and train on the provided dataset
# Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings
query_word_embedding_model = models.Transformer(model_name)
# Apply mean pooling to get one fixed sized sentence vector
query_pooling_model = models.Pooling(query_word_embedding_model.get_word_embedding_dimension(),
pooling_mode_mean_tokens=True,
pooling_mode_cls_token=False,
pooling_mode_max_tokens=False)
query_dense_model = models.Dense(in_features=query_pooling_model.get_sentence_embedding_dimension(),
out_features=out_features,
activation_function=nn.Sigmoid())
psg_word_embedding_model = models.Transformer(model_name)
# Apply mean pooling to get one fixed sized sentence vector
psg_pooling_model = models.Pooling(psg_word_embedding_model.get_word_embedding_dimension(),
pooling_mode_mean_tokens=True,
pooling_mode_cls_token=False,
pooling_mode_max_tokens=False)
psg_dense_model = models.Dense(in_features=psg_pooling_model.get_sentence_embedding_dimension(),
out_features=out_features,
activation_function=nn.Tanh())
query_model = CustomSentenceTransformer(modules=[query_word_embedding_model, query_pooling_model,
query_dense_model])
psg_model = SentenceTransformer(modules=[psg_word_embedding_model, psg_pooling_model, psg_dense_model])
model = QuerySpecificClusterModel(query_transformer=query_model, psg_transformer=psg_model, device=device)
train_dataloader = DataLoader(train_cluster_data, shuffle=True, batch_size=1)
evaluator = QueryClusterEvaluator.from_input_examples(val_cluster_data, use_model_device)
test_evaluator = QueryClusterEvaluator.from_input_examples(test_cluster_data, use_model_device)
warmup_steps = int(len(train_dataloader) * num_epochs * warmup_frac) # 10% of train data
print("Untrained performance")
model.to(device)
evaluator(model)
train_dataloader.collate_fn = model.query_batch_collate_fn
# Train the model
best_score = -9999999
if steps_per_epoch is None or steps_per_epoch == 0:
steps_per_epoch = len(train_dataloader)
num_train_steps = int(steps_per_epoch * num_epochs)
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay': weight_decay},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
data_iter = iter(train_dataloader)
optimizer = optimizer_class(optimizer_grouped_parameters, **optimizer_params)
scheduler_obj = model._get_scheduler(optimizer, scheduler=scheduler, warmup_steps=warmup_steps,
t_total=num_train_steps)
config = {'epochs': num_epochs, 'steps_per_epoch': steps_per_epoch}
global_step = 0
loss_model = BBClusterLossModel(model, device, lambda_val, reg)
for epoch in trange(config.get('epochs'), desc="Epoch", disable=not show_progress_bar):
training_steps = 0
running_loss_0 = 0.0
model.zero_grad()
model.train()
if not train_psg_model:
for m in model.psg_model.modules():
m.training = False
for _ in trange(config.get('steps_per_epoch'), desc="Iteration", smoothing=0.05, disable=not show_progress_bar):
try:
data = next(data_iter)
except StopIteration:
data_iter = iter(train_dataloader)
data = next(data_iter)
query_feature, psg_features, labels = data
if max_train_size > 0 and labels.shape[1] > max_train_size:
print('skipping instance with '+str(labels.shape[1])+' passages')
continue
loss_val = loss_model(query_feature, psg_features, labels)
running_loss_0 += loss_val.item()
loss_val.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
scheduler_obj.step()
training_steps += 1
global_step += 1
if eval_steps > 0 and training_steps % eval_steps == 0:
tensorboard_writer.add_scalar('training_loss', running_loss_0 / eval_steps, global_step)
# logger.report_scalar('Loss', 'training_loss', iteration=global_step, v
# alue=running_loss_0/evaluation_steps)
running_loss_0 = 0.0
# self._eval_during_training(evaluator, output_path, save_best_model, epoch, training_steps, callback)
if evaluator is not None:
score = evaluator(model, output_path=output_path, epoch=epoch, steps=training_steps)
tensorboard_writer.add_scalar('val_ARI', score, global_step)
# logger.report_scalar('Training progress', 'val_ARI', iteration=global_step, value=score)
if score > best_score:
best_score = score
if save_best_model:
print('Saving model at: ' + output_path)
model.save(output_path)
model.zero_grad()
model.train()
if not train_psg_model:
for m in model.psg_model.modules():
m.training = False
if evaluator is not None:
score = evaluator(model, output_path=output_path, epoch=epoch, steps=training_steps)
tensorboard_writer.add_scalar('val_ARI', score, global_step)
# logger.report_scalar('Training progress', 'val_ARI', iteration=global_step, value=score)
if score > best_score:
best_score = score
if save_best_model:
model.save(output_path)
if test_evaluator is not None:
best_model = QuerySpecificClusterModel(output_path)
if torch.cuda.is_available():
model.to(torch.device('cpu'))
best_model.to(device)
test_ari = test_evaluator(best_model)
best_model.to(torch.device('cpu'))
model.to(device)
else:
test_ari = test_evaluator(best_model)
tensorboard_writer.add_scalar('test_ARI', test_ari, global_step)
# logger.report_scalar('Training progress', 'test_ARI', iteration=global_step, value=test_ari)
if evaluator is None and output_path is not None: # No evaluator, but output path: save final model version
model.save(output_path)
def save_sqst_dataset(train_pages_file, art_qrels, top_qrels, paratext, val_samples, outdir):
page_paras, rev_para_top, _ = get_trec_dat(art_qrels, top_qrels, None)
ptext_dict = get_paratext_dict(paratext)
train_cluster_data = []
test_cluster_data = []
pages = []
with open(train_pages_file, 'r') as f:
for l in f:
pages.append(l.rstrip('\n'))
for i in trange(len(pages)):
page = pages[i]
paras = page_paras[page]
page_sec_para_dict = {}
for p in paras:
sec = rev_para_top[p]
if sec not in page_sec_para_dict.keys():
page_sec_para_dict[sec] = [p]
else:
page_sec_para_dict[sec].append(p)
sections = list(set([rev_para_top[p] for p in paras]))
train_paras = []
test_paras = []
for s in page_sec_para_dict.keys():
test_paras += page_sec_para_dict[s][:len(page_sec_para_dict[s])//2]
train_paras += page_sec_para_dict[s][len(page_sec_para_dict[s])//2:]
test_labels = [sections.index(rev_para_top[p]) for p in test_paras]
train_labels = [sections.index(rev_para_top[p]) for p in train_paras]
test_paratexts = [ptext_dict[p] for p in test_paras]
train_paratexts = [ptext_dict[p] for p in train_paras]
query_text = ' '.join(page.split('enwiki:')[1].split('%20'))
test_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=test_paras,
texts=test_paratexts, label=np.array(test_labels)))
train_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=train_paras,
texts=train_paratexts, label=np.array(train_labels)))
random.shuffle(test_cluster_data)
val_cluster_data = test_cluster_data[:val_samples]
test_cluster_data = test_cluster_data[val_samples:]
with open(outdir + '/sqst_treccar_train.pkl', 'wb') as f:
pickle.dump(train_cluster_data, f)
with open(outdir + '/sqst_treccar_val.pkl', 'wb') as f:
pickle.dump(val_cluster_data, f)
with open(outdir + '/sqst_treccar_test.pkl', 'wb') as f:
pickle.dump(test_cluster_data, f)
print('No. of data instances - Train: %5d, Val: %5d, Test: %5d' % (len(train_cluster_data), len(val_cluster_data),
len(test_cluster_data)))
def save_squt_dataset(train_pages_file, art_qrels, top_qrels, paratext, val_samples, outdir):
page_paras, rev_para_top, _ = get_trec_dat(art_qrels, top_qrels, None)
ptext_dict = get_paratext_dict(paratext)
train_cluster_data = []
test_cluster_data = []
pages = []
with open(train_pages_file, 'r') as f:
for l in f:
pages.append(l.rstrip('\n'))
for i in trange(len(pages)):
page = pages[i]
paras = page_paras[page]
page_sec_para_dict = {}
for p in paras:
sec = rev_para_top[p]
if sec not in page_sec_para_dict.keys():
page_sec_para_dict[sec] = [p]
else:
page_sec_para_dict[sec].append(p)
sections = list(set([rev_para_top[p] for p in paras]))
random.shuffle(sections)
test_sections, train_sections = sections[:len(sections)//2], sections[len(sections)//2:]
train_paras = []
test_paras = []
for s in test_sections:
test_paras += page_sec_para_dict[s]
for s in train_sections:
train_paras += page_sec_para_dict[s]
test_labels = [sections.index(rev_para_top[p]) for p in test_paras]
train_labels = [sections.index(rev_para_top[p]) for p in train_paras]
test_paratexts = [ptext_dict[p] for p in test_paras]
train_paratexts = [ptext_dict[p] for p in train_paras]
query_text = ' '.join(page.split('enwiki:')[1].split('%20'))
test_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=test_paras,
texts=test_paratexts, label=np.array(test_labels)))
train_cluster_data.append(InputTRECCARExample(qid=page, q_context=query_text, pids=train_paras,
texts=train_paratexts, label=np.array(train_labels)))
random.shuffle(test_cluster_data)
val_cluster_data = test_cluster_data[:val_samples]
test_cluster_data = test_cluster_data[val_samples:]
with open(outdir + '/squt_treccar_train.pkl', 'wb') as f:
pickle.dump(train_cluster_data, f)
with open(outdir + '/squt_treccar_val.pkl', 'wb') as f:
pickle.dump(val_cluster_data, f)
with open(outdir + '/squt_treccar_test.pkl', 'wb') as f:
pickle.dump(test_cluster_data, f)
print(
'No. of data instances - Train: %5d, Val: %5d, Test: %5d' % (len(train_cluster_data), len(val_cluster_data),
len(test_cluster_data)))
def save_sbert_embeds(sbert_model_name, pages_path, art_qrels, paratext_file, outpath):
sbert = SentenceTransformer(sbert_model_name)
page_paras, _, _ = get_trec_dat(art_qrels, None, None)
paratext_dict = get_paratext_dict(paratext_file)
paras = []
paratexts = []
with open(pages_path, 'r') as f:
for l in f:
page = l.rstrip('\n')
paras += page_paras[page]
paratexts += [paratext_dict[p] for p in page_paras[page]]
print(str(len(paratexts))+' paras to be encoded')
para_embeddings = sbert.encode(paratexts, show_progress_bar=True)
para_data = {'paraids': paras, 'paravecs': para_embeddings}
with open(outpath, 'wb') as f:
pickle.dump(para_data, f)
def main():
parser = argparse.ArgumentParser(description='Run treccar experiments')
parser.add_argument('-in', '--input_dir', default='/home/sk1105/sumanta/trec_dataset/train')
parser.add_argument('-out', '--output_model_path', default='/home/sk1105/sumanta/bb_cluster_models/temp_model')
parser.add_argument('-mn', '--model_name', default='distilbert-base-uncased')
parser.add_argument('-ls', '--loss', default='bb')
parser.add_argument('-lm', '--lambda_val', type=float, default=200.0)
parser.add_argument('-b', '--beta', type=float, default=10.0)
parser.add_argument('-rg', '--reg_const', type=float, default=2.5)
parser.add_argument('-ep', '--num_epoch', type=int, default=3)
parser.add_argument('-ws', '--warmup', type=float, default=0.1)
parser.add_argument('-es', '--eval_steps', type=int, default=100)
parser.add_argument('-md', '--max_sample_size', type=int, default=-1)
parser.add_argument('-ext', '--exp_type', default='sqst')
parser.add_argument('--gpu_eval', default=False, action='store_true')
parser.add_argument('--train_psg_model', default=False, action='store_true')
args = parser.parse_args()
input_dir = args.input_dir
output_path = args.output_model_path
model_name = args.model_name
loss_name = args.loss
lambda_val = args.lambda_val
beta = args.beta
reg = args.reg_const
epochs = args.num_epoch
warmup_fraction = args.warmup
eval_steps = args.eval_steps
max_sample_size = args.max_sample_size
exp_type = args.exp_type
gpu_eval = args.gpu_eval
train_psg_model = args.train_psg_model
if exp_type == 'sqst':
with open(input_dir + '/sqst/sqst_treccar_train.pkl', 'rb') as f:
train_cluster_data = pickle.load(f)
with open(input_dir + '/sqst/sqst_treccar_val.pkl', 'rb') as f:
val_cluster_data = pickle.load(f)
with open(input_dir + '/sqst/sqst_treccar_test.pkl', 'rb') as f:
test_cluster_data = pickle.load(f)
elif exp_type == 'squt':
with open(input_dir + '/squt/squt_treccar_train.pkl', 'rb') as f:
train_cluster_data = pickle.load(f)
with open(input_dir + '/squt/squt_treccar_val.pkl', 'rb') as f:
val_cluster_data = pickle.load(f)
with open(input_dir + '/squt/squt_treccar_test.pkl', 'rb') as f:
test_cluster_data = pickle.load(f)
print('Data loaded, starting to train')
train(train_cluster_data, val_cluster_data, test_cluster_data, output_path, eval_steps, epochs, warmup_fraction,
lambda_val, reg, gpu_eval, max_train_size=max_sample_size, train_psg_model=train_psg_model,
model_name=model_name)
if __name__ == '__main__':
main()
|
[
"torch.nn.Tanh",
"sentence_transformers.models.Transformer",
"transformers.get_constant_schedule_with_warmup",
"sentence_transformers.util.batch_to_device",
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.Sigmoid",
"numpy.mean",
"torch.unique",
"argparse.ArgumentParser",
"transformers.get_constant_schedule",
"numpy.max",
"model.BBCluster.CustomSentenceTransformer",
"numpy.random.seed",
"model.BBCluster.OptimCluster",
"random.shuffle",
"transformers.get_cosine_with_hard_restarts_schedule_with_warmup",
"clearml.Task.init",
"pickle.load",
"torch.norm",
"model.BBCluster.euclid_dist",
"numpy.std",
"torch.device",
"experiments.treccar_run.get_paratext_dict",
"torch.manual_seed",
"transformers.get_cosine_schedule_with_warmup",
"sentence_transformers.SentenceTransformer",
"pickle.dump",
"transformers.get_linear_schedule_with_warmup",
"random.seed",
"torch.tensor",
"experiments.treccar_run.get_trec_dat",
"torch.utils.data.DataLoader",
"torch.zeros"
] |
[((960, 975), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (971, 975), False, 'import random\n'), ((976, 997), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (993, 997), False, 'import torch\n'), ((998, 1016), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (1012, 1016), True, 'import numpy as np\n'), ((1128, 1168), 'experiments.treccar_run.get_trec_dat', 'get_trec_dat', (['art_qrels', 'top_qrels', 'None'], {}), '(art_qrels, top_qrels, None)\n', (1140, 1168), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((1186, 1213), 'experiments.treccar_run.get_paratext_dict', 'get_paratext_dict', (['paratext'], {}), '(paratext)\n', (1203, 1213), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((2170, 2210), 'experiments.treccar_run.get_trec_dat', 'get_trec_dat', (['art_qrels', 'top_qrels', 'None'], {}), '(art_qrels, top_qrels, None)\n', (2182, 2210), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((2427, 2454), 'experiments.treccar_run.get_paratext_dict', 'get_paratext_dict', (['paratext'], {}), '(paratext)\n', (2444, 2454), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((15382, 15417), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['"""./tensorboard_logs"""'], {}), "('./tensorboard_logs')\n", (15395, 15417), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((15429, 15524), 'clearml.Task.init', 'Task.init', ([], {'project_name': '"""Query Specific BB Clustering"""', 'task_name': '"""query_bbc_fixed_lambda"""'}), "(project_name='Query Specific BB Clustering', task_name=\n 'query_bbc_fixed_lambda')\n", (15438, 15524), False, 'from clearml import Task\n'), ((15628, 15653), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15651, 15653), False, 'import torch\n'), ((16099, 16129), 'sentence_transformers.models.Transformer', 'models.Transformer', (['model_name'], {}), '(model_name)\n', (16117, 16129), False, 'from sentence_transformers import models\n'), ((16764, 16794), 'sentence_transformers.models.Transformer', 'models.Transformer', (['model_name'], {}), '(model_name)\n', (16782, 16794), False, 'from sentence_transformers import models\n'), ((17424, 17531), 'model.BBCluster.CustomSentenceTransformer', 'CustomSentenceTransformer', ([], {'modules': '[query_word_embedding_model, query_pooling_model, query_dense_model]'}), '(modules=[query_word_embedding_model,\n query_pooling_model, query_dense_model])\n', (17449, 17531), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((17597, 17692), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', ([], {'modules': '[psg_word_embedding_model, psg_pooling_model, psg_dense_model]'}), '(modules=[psg_word_embedding_model, psg_pooling_model,\n psg_dense_model])\n', (17616, 17692), False, 'from sentence_transformers import SentenceTransformer\n'), ((17825, 17883), 'torch.utils.data.DataLoader', 'DataLoader', (['train_cluster_data'], {'shuffle': '(True)', 'batch_size': '(1)'}), '(train_cluster_data, shuffle=True, batch_size=1)\n', (17835, 17883), False, 'from torch.utils.data import DataLoader\n'), ((23219, 23259), 'experiments.treccar_run.get_trec_dat', 'get_trec_dat', (['art_qrels', 'top_qrels', 'None'], {}), '(art_qrels, top_qrels, None)\n', (23231, 23259), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((23277, 23304), 'experiments.treccar_run.get_paratext_dict', 'get_paratext_dict', (['paratext'], {}), '(paratext)\n', (23294, 23304), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((24912, 24945), 'random.shuffle', 'random.shuffle', (['test_cluster_data'], {}), '(test_cluster_data)\n', (24926, 24945), False, 'import random\n'), ((25710, 25750), 'experiments.treccar_run.get_trec_dat', 'get_trec_dat', (['art_qrels', 'top_qrels', 'None'], {}), '(art_qrels, top_qrels, None)\n', (25722, 25750), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((25768, 25795), 'experiments.treccar_run.get_paratext_dict', 'get_paratext_dict', (['paratext'], {}), '(paratext)\n', (25785, 25795), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((27491, 27524), 'random.shuffle', 'random.shuffle', (['test_cluster_data'], {}), '(test_cluster_data)\n', (27505, 27524), False, 'import random\n'), ((28267, 28304), 'sentence_transformers.SentenceTransformer', 'SentenceTransformer', (['sbert_model_name'], {}), '(sbert_model_name)\n', (28286, 28304), False, 'from sentence_transformers import SentenceTransformer\n'), ((28328, 28363), 'experiments.treccar_run.get_trec_dat', 'get_trec_dat', (['art_qrels', 'None', 'None'], {}), '(art_qrels, None, None)\n', (28340, 28363), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((28384, 28416), 'experiments.treccar_run.get_paratext_dict', 'get_paratext_dict', (['paratext_file'], {}), '(paratext_file)\n', (28401, 28416), False, 'from experiments.treccar_run import prepare_cluster_data_train_only, prepare_cluster_data2, get_trec_dat, get_paratext_dict\n'), ((28934, 28996), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run treccar experiments"""'}), "(description='Run treccar experiments')\n", (28957, 28996), False, 'import argparse\n'), ((6756, 6797), 'sentence_transformers.util.batch_to_device', 'batch_to_device', (['q_tokenized', 'self.device'], {}), '(q_tokenized, self.device)\n', (6771, 6797), False, 'from sentence_transformers.util import batch_to_device\n'), ((7991, 8005), 'model.BBCluster.OptimCluster', 'OptimCluster', ([], {}), '()\n', (8003, 8005), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((8115, 8134), 'torch.zeros', 'torch.zeros', (['(n, n)'], {}), '((n, n))\n', (8126, 8134), False, 'import torch\n'), ((10154, 10168), 'model.BBCluster.OptimCluster', 'OptimCluster', ([], {}), '()\n', (10166, 10168), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((10278, 10297), 'torch.zeros', 'torch.zeros', (['(n, n)'], {}), '((n, n))\n', (10289, 10297), False, 'import torch\n'), ((11045, 11062), 'torch.tensor', 'torch.tensor', (['[0]'], {}), '([0])\n', (11057, 11062), False, 'import torch\n'), ((12782, 12820), 'torch.norm', 'torch.norm', (['(x[:, None] - x)'], {'dim': '(2)', 'p': '(2)'}), '(x[:, None] - x, dim=2, p=2)\n', (12792, 12820), False, 'import torch\n'), ((15672, 15692), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (15684, 15692), False, 'import torch\n'), ((15786, 15805), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (15798, 15805), False, 'import torch\n'), ((25127, 25161), 'pickle.dump', 'pickle.dump', (['train_cluster_data', 'f'], {}), '(train_cluster_data, f)\n', (25138, 25161), False, 'import pickle\n'), ((25230, 25262), 'pickle.dump', 'pickle.dump', (['val_cluster_data', 'f'], {}), '(val_cluster_data, f)\n', (25241, 25262), False, 'import pickle\n'), ((25332, 25365), 'pickle.dump', 'pickle.dump', (['test_cluster_data', 'f'], {}), '(test_cluster_data, f)\n', (25343, 25365), False, 'import pickle\n'), ((26388, 26412), 'random.shuffle', 'random.shuffle', (['sections'], {}), '(sections)\n', (26402, 26412), False, 'import random\n'), ((27706, 27740), 'pickle.dump', 'pickle.dump', (['train_cluster_data', 'f'], {}), '(train_cluster_data, f)\n', (27717, 27740), False, 'import pickle\n'), ((27809, 27841), 'pickle.dump', 'pickle.dump', (['val_cluster_data', 'f'], {}), '(val_cluster_data, f)\n', (27820, 27841), False, 'import pickle\n'), ((27911, 27944), 'pickle.dump', 'pickle.dump', (['test_cluster_data', 'f'], {}), '(test_cluster_data, f)\n', (27922, 27944), False, 'import pickle\n'), ((28881, 28906), 'pickle.dump', 'pickle.dump', (['para_data', 'f'], {}), '(para_data, f)\n', (28892, 28906), False, 'import pickle\n'), ((4389, 4437), 'model.BBCluster.CustomSentenceTransformer', 'CustomSentenceTransformer', (["(path + '/query_model')"], {}), "(path + '/query_model')\n", (4414, 4437), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((4465, 4511), 'model.BBCluster.CustomSentenceTransformer', 'CustomSentenceTransformer', (["(path + '/psg_model')"], {}), "(path + '/psg_model')\n", (4490, 4511), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((5108, 5153), 'transformers.get_constant_schedule', 'transformers.get_constant_schedule', (['optimizer'], {}), '(optimizer)\n', (5142, 5153), False, 'import transformers\n'), ((6936, 6977), 'sentence_transformers.util.batch_to_device', 'batch_to_device', (['p_tokenized', 'self.device'], {}), '(p_tokenized, self.device)\n', (6951, 6977), False, 'from sentence_transformers.util import batch_to_device\n'), ((14550, 14571), 'numpy.array', 'np.array', (['rand_scores'], {}), '(rand_scores)\n', (14558, 14571), True, 'import numpy as np\n'), ((14600, 14620), 'numpy.array', 'np.array', (['nmi_scores'], {}), '(nmi_scores)\n', (14608, 14620), True, 'import numpy as np\n'), ((14649, 14669), 'numpy.array', 'np.array', (['ami_scores'], {}), '(ami_scores)\n', (14657, 14669), True, 'import numpy as np\n'), ((16719, 16731), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (16729, 16731), True, 'import torch.nn as nn\n'), ((17394, 17403), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (17401, 17403), True, 'import torch.nn as nn\n'), ((22440, 22465), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (22463, 22465), False, 'import torch\n'), ((30669, 30683), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (30680, 30683), False, 'import pickle\n'), ((30787, 30801), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (30798, 30801), False, 'import pickle\n'), ((30907, 30921), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (30918, 30921), False, 'import pickle\n'), ((2351, 2369), 'numpy.mean', 'np.mean', (['len_paras'], {}), '(len_paras)\n', (2358, 2369), True, 'import numpy as np\n'), ((2371, 2388), 'numpy.std', 'np.std', (['len_paras'], {}), '(len_paras)\n', (2377, 2388), True, 'import numpy as np\n'), ((2390, 2407), 'numpy.max', 'np.max', (['len_paras'], {}), '(len_paras)\n', (2396, 2407), True, 'import numpy as np\n'), ((5217, 5310), 'transformers.get_constant_schedule_with_warmup', 'transformers.get_constant_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'warmup_steps'}), '(optimizer, num_warmup_steps=\n warmup_steps)\n', (5263, 5310), False, 'import transformers\n'), ((6653, 6673), 'torch.tensor', 'torch.tensor', (['labels'], {}), '(labels)\n', (6665, 6673), False, 'import torch\n'), ((9166, 9203), 'model.BBCluster.euclid_dist', 'euclid_dist', (['scaled_psg_embeddings[i]'], {}), '(scaled_psg_embeddings[i])\n', (9177, 9203), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((11273, 11310), 'model.BBCluster.euclid_dist', 'euclid_dist', (['scaled_psg_embeddings[i]'], {}), '(scaled_psg_embeddings[i])\n', (11284, 11310), False, 'from model.BBCluster import CustomSentenceTransformer, OptimCluster, euclid_dist\n'), ((12584, 12615), 'torch.from_numpy', 'torch.from_numpy', (['example.label'], {}), '(example.label)\n', (12600, 12615), False, 'import torch\n'), ((13637, 13680), 'sentence_transformers.util.batch_to_device', 'batch_to_device', (['doc_features', 'model_device'], {}), '(doc_features, model_device)\n', (13652, 13680), False, 'from sentence_transformers.util import batch_to_device\n'), ((31058, 31072), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (31069, 31072), False, 'import pickle\n'), ((31176, 31190), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (31187, 31190), False, 'import pickle\n'), ((31296, 31310), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (31307, 31310), False, 'import pickle\n'), ((1930, 1950), 'numpy.array', 'np.array', (['top_labels'], {}), '(top_labels)\n', (1938, 1950), True, 'import numpy as np\n'), ((3849, 3869), 'numpy.array', 'np.array', (['top_labels'], {}), '(top_labels)\n', (3857, 3869), True, 'import numpy as np\n'), ((5367, 5486), 'transformers.get_linear_schedule_with_warmup', 'transformers.get_linear_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'warmup_steps', 'num_training_steps': 't_total'}), '(optimizer, num_warmup_steps=\n warmup_steps, num_training_steps=t_total)\n', (5411, 5486), False, 'import transformers\n'), ((8508, 8531), 'torch.unique', 'torch.unique', (['labels[i]'], {}), '(labels[i])\n', (8520, 8531), False, 'import torch\n'), ((10671, 10694), 'torch.unique', 'torch.unique', (['labels[i]'], {}), '(labels[i])\n', (10683, 10694), False, 'import torch\n'), ((22492, 22511), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (22504, 22511), False, 'import torch\n'), ((22635, 22654), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (22647, 22654), False, 'import torch\n'), ((24673, 24694), 'numpy.array', 'np.array', (['test_labels'], {}), '(test_labels)\n', (24681, 24694), True, 'import numpy as np\n'), ((24883, 24905), 'numpy.array', 'np.array', (['train_labels'], {}), '(train_labels)\n', (24891, 24905), True, 'import numpy as np\n'), ((27251, 27272), 'numpy.array', 'np.array', (['test_labels'], {}), '(test_labels)\n', (27259, 27272), True, 'import numpy as np\n'), ((27462, 27484), 'numpy.array', 'np.array', (['train_labels'], {}), '(train_labels)\n', (27470, 27484), True, 'import numpy as np\n'), ((5607, 5726), 'transformers.get_cosine_schedule_with_warmup', 'transformers.get_cosine_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'warmup_steps', 'num_training_steps': 't_total'}), '(optimizer, num_warmup_steps=\n warmup_steps, num_training_steps=t_total)\n', (5651, 5726), False, 'import transformers\n'), ((5863, 6000), 'transformers.get_cosine_with_hard_restarts_schedule_with_warmup', 'transformers.get_cosine_with_hard_restarts_schedule_with_warmup', (['optimizer'], {'num_warmup_steps': 'warmup_steps', 'num_training_steps': 't_total'}), '(optimizer,\n num_warmup_steps=warmup_steps, num_training_steps=t_total)\n', (5926, 6000), False, 'import transformers\n'), ((14042, 14066), 'torch.unique', 'torch.unique', (['true_label'], {}), '(true_label)\n', (14054, 14066), False, 'import torch\n')]
|
import solver.algorithms as alg
import numpy as np
def problem4(t0, tf, NA0, NB0, tauA, tauB, n, returnlist=False):
"""Uses Euler's method to model the solution to a radioactive decay problem where dNA/dt = -NA/tauA and dNB/dt = NA/tauA - NB/tauB.
Args:
t0 (float): Start time
tf (float): End time
NA0 (int): Initial number of NA nuclei
NB0 (int): Initial number of NB nuclei
tauA (float): Decay time constant for NA
tauB (float): Decay time constant for NB
n (int): Number of points to sample at
returnlist (bool) = Controls whether the function returns the list of points or not. Defaults to false
Returns:
solution (list): Points on the graph of the approximate solution. Each element in the list has the form (t, array([NA, NB]))
In the graph, NA is green and NB is blue
"""
print("Problem 4: ~Radioactive Decay~ dNA/dt = -NA/tauA & dNB/dt = NA/tauA - NB/tauA - NB/tauB")
N0 = np.array([NA0, NB0])
A = np.array([[-1/tauA, 0],[1/tauA, -1/tauB]])
def dN_dt(t, N):
return A @ N
h = (tf-t0)/(n-1)
print("Time step of %f seconds." % h)
solution = alg.euler(t0, tf, n, N0, dN_dt)
if returnlist:
return solution
|
[
"numpy.array",
"solver.algorithms.euler"
] |
[((985, 1005), 'numpy.array', 'np.array', (['[NA0, NB0]'], {}), '([NA0, NB0])\n', (993, 1005), True, 'import numpy as np\n'), ((1014, 1063), 'numpy.array', 'np.array', (['[[-1 / tauA, 0], [1 / tauA, -1 / tauB]]'], {}), '([[-1 / tauA, 0], [1 / tauA, -1 / tauB]])\n', (1022, 1063), True, 'import numpy as np\n'), ((1178, 1209), 'solver.algorithms.euler', 'alg.euler', (['t0', 'tf', 'n', 'N0', 'dN_dt'], {}), '(t0, tf, n, N0, dN_dt)\n', (1187, 1209), True, 'import solver.algorithms as alg\n')]
|
"""
File name: extracted_features_gridsearch.py
Author: <NAME>
Date created: 29.04.2019
"""
import numpy as np
import sys
import os
import yaml
import pickle
import pandas as pd
import pandas.core.indexes
sys.modules['pandas.indexes'] = pandas.core.indexes
import json
import time
import keras
import tensorflow as tf
from keras.models import load_model,Sequential, Model
from keras.layers import Dense, Dropout, Input, concatenate
from keras.callbacks import EarlyStopping
from keras.backend.tensorflow_backend import set_session
from sklearn.model_selection import ParameterGrid
from sklearn.metrics import roc_auc_score
from helper import dataset, model
from imaging_predictive_models import imaging_dataset
from clinical_predictive_models import clinical_dataset, MLP
from multimodal_prediction_helper import multimodal_dataset
from plotting_helper import plot_evolution
#### ENVIRONMENT AND SESSION SET UP ####################################################################
# set the environment variable
os.environ["KERAS_BACKEND"] = "tensorflow"
# Silence INFO logs
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
# create a configuration protocol
config = tf.ConfigProto()
# set the allow_growth option to true in the protocol
config.gpu_options.allow_growth = True
# define GPU to use
config.gpu_options.visible_device_list = "0,1"
# start a sesstion that uses the configuration protocol
set_session(tf.Session(config=config))
#### READ CONFIGURATION FILE ##########
def join(loader,node):
seq = loader.construct_sequence(node)
return ''.join(str(i) for i in seq)
yaml.add_constructor('!join',join)
cfg = yaml.load(open('config.yml', 'r'))
#### ASSIGN PATHS AND VARIABLES #########################################################################
dataset_name = cfg['dataset name']
data_path = 'data/'
clin_feat_splits_path = data_path+ cfg['clinical dataset']['feature splits path']
img_feat_splits_path = data_path + cfg['imaging dataset']['feature splits path']
num_splits = cfg['number of runs']
model_name = cfg['model name']
def_params = cfg['hyperparameters'][model_name]
tuning_params = cfg['tuning parameters'][model_name]
performance_scores = cfg['final performance measures']
save_models = cfg['save options']['models path']
save_params = cfg['save options']['params path']
save_scores = cfg['save options']['scores path']
save_figures = cfg['save options']['figures path']
##### GET TRAINING,VALIDATION AND TEST DATA ##############################################################
data = multimodal_dataset(dataset_name)
data.load_feature_sets(img_feat_splits_path, clin_feat_splits_path)
#feature_sets = data.combine_features(combining_method = 'concat_and_normalize')
##### TRAIN AND SAVE MODELS #################################################################################
for i in range(num_splits):
#### ASSIGN TRAINING, TEST AND VALIDATION SETS FOR CURRENT SPLIT ##########################################
current_split_num = i+1
img_X_tr = data.img_sets[i]['train_data']
img_X_val = data.img_sets[i]['val_data']
img_X_te = data.img_sets[i]['test_data']
clin_X_tr = data.clin_sets[i]['train_data']
clin_X_val = data.clin_sets[i]['val_data']
clin_X_te = data.clin_sets[i]['test_data']
y_tr = data.img_sets[i]['train_labels']
y_val = data.img_sets[i]['val_labels']
y_te = data.img_sets[i]['test_labels']
if def_params['out_activation'] == 'softmax':
y_tr = pd.get_dummies(y_tr)
y_val = pd.get_dummies(y_val)
y_te = pd.get_dummies(y_te)
model_path = save_models + '/best_model_on_outer_training_set_split_'+str(current_split_num)+'.h5'
#params_path = save_params + '/best_parameters_run_'+str(current_split_num)+'.json'
tune_params_path = save_params + '/best_tuning_parameters_split_'+str(current_split_num)+'.json'
if os.path.isfile(model_path):
pass
else:
if not os.path.exists(save_models):
os.makedirs(save_models)
#### START GRID SEARCH #####################################################################################
start = time.time()
best_AUC = 0.5
i = 0
for tune in ParameterGrid(tuning_params):
img_input = Input(shape= (img_X_tr.shape[1],), name='image_input')
clin_input = Input(shape= (clin_X_tr.shape[1],), name='clinical_input')
dense1 = Dense(tune['num_neurons_embedding'][0], kernel_initializer = def_params['weight_init'], activation = def_params['hidden_activation'],
kernel_regularizer= keras.regularizers.l2(tune['l2_ratio']))(clin_input)
dense2 = Dense(tune['num_neurons_embedding'][1], kernel_initializer = def_params['weight_init'], activation = def_params['hidden_activation'],
kernel_regularizer= keras.regularizers.l2(tune['l2_ratio']))(img_input)
x = concatenate([dense1, dense2])
x = Dense(tune['num_neurons_final'], kernel_initializer = def_params['weight_init'], activation = def_params['hidden_activation'],
kernel_regularizer= keras.regularizers.l2(tune['l2_ratio']))(x)
x= Dropout(tune['dropout_rate'])(x)
if def_params['out_activation'] == 'softmax':
output = Dense(2,kernel_initializer = def_params['weight_init'],activation= def_params['out_activation'],
kernel_regularizer= keras.regularizers.l2(tune['l2_ratio']))(x)
else:
output = Dense(1,kernel_initializer = def_params['weight_init'],activation= def_params['out_activation'],
kernel_regularizer= keras.regularizers.l2(tune['l2_ratio']))(x)
optimizer = keras.optimizers.Adam(lr = tune['learning_rate'])
model = Model(inputs=[img_input, clin_input], outputs=[output])
model.compile(loss=def_params['loss_func'], optimizer = optimizer)
e_stop = EarlyStopping(monitor = 'val_loss', min_delta = def_params['min_delta'], patience = def_params['iter_patience'], mode='auto')
callbacks = [e_stop]
history = model.fit({'image_input' : img_X_tr,'clinical_input' : clin_X_tr}, y_tr, callbacks = callbacks,validation_data= ([img_X_val, clin_X_val],y_val),
epochs=def_params['epochs'], batch_size= tune['batch_size'], verbose=0)
probs_val = model.predict([img_X_val,clin_X_val],batch_size = 8)
score_val = roc_auc_score(y_val, probs_val)
i +=1
if i%10 == 0:
print(i)
if score_val > best_AUC:
best_AUC = score_val
best_params = tune
loss_tr = history.history['loss']
loss_val = history.history['val_loss']
model.save(save_models + '/best_model_on_inner_training_set_split_'+str(current_split_num)+'.h5')
keras.backend.clear_session()
best_model = load_model(save_models + '/best_model_on_inner_training_set_split_'+str(current_split_num)+'.h5')
probs_tr = best_model.predict([img_X_tr,clin_X_tr],batch_size = 8)
probs_val = best_model.predict([img_X_val,clin_X_val],batch_size = 8)
probs_te = best_model.predict([img_X_te,clin_X_te],batch_size = 8)
score_tr = roc_auc_score(y_tr, probs_tr)
score_val = roc_auc_score(y_val, probs_val)
score_te = roc_auc_score(y_te, probs_te)
# Save tuning parameters that resulted in the best model:
if not os.path.exists(save_params):
os.makedirs(save_params)
json.dump(best_params,open(tune_params_path,'w'))
# Save loss and auc scores calculated at each epoch during training:
if not os.path.exists(save_scores):
os.makedirs(save_scores)
np.savetxt(save_scores+'/inner_loop_loss_over_epochs_split_'+str(current_split_num)+'.csv', [loss_tr,loss_val], delimiter=",")
np.savetxt(save_scores+ "/inner_loop_auc_scores_split_"+str(current_split_num)+".csv", [score_tr, score_val, score_te], delimiter=",")
end = time.time()
print('Training time for split %s: %i minutes.'%(str(current_split_num),np.floor(((end-start)%3600)/60)))
|
[
"helper.model.compile",
"sklearn.metrics.roc_auc_score",
"sklearn.model_selection.ParameterGrid",
"os.path.exists",
"tensorflow.Session",
"yaml.add_constructor",
"keras.layers.concatenate",
"keras.models.Model",
"keras.callbacks.EarlyStopping",
"keras.backend.clear_session",
"tensorflow.ConfigProto",
"keras.optimizers.Adam",
"numpy.floor",
"os.path.isfile",
"keras.regularizers.l2",
"pandas.get_dummies",
"time.time",
"keras.layers.Dropout",
"multimodal_prediction_helper.multimodal_dataset",
"os.makedirs",
"keras.layers.Input",
"helper.model.fit",
"helper.model.predict"
] |
[((1166, 1182), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (1180, 1182), True, 'import tensorflow as tf\n'), ((1587, 1622), 'yaml.add_constructor', 'yaml.add_constructor', (['"""!join"""', 'join'], {}), "('!join', join)\n", (1607, 1622), False, 'import yaml\n'), ((2523, 2555), 'multimodal_prediction_helper.multimodal_dataset', 'multimodal_dataset', (['dataset_name'], {}), '(dataset_name)\n', (2541, 2555), False, 'from multimodal_prediction_helper import multimodal_dataset\n'), ((1412, 1437), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (1422, 1437), True, 'import tensorflow as tf\n'), ((3794, 3820), 'os.path.isfile', 'os.path.isfile', (['model_path'], {}), '(model_path)\n', (3808, 3820), False, 'import os\n'), ((3420, 3440), 'pandas.get_dummies', 'pd.get_dummies', (['y_tr'], {}), '(y_tr)\n', (3434, 3440), True, 'import pandas as pd\n'), ((3451, 3472), 'pandas.get_dummies', 'pd.get_dummies', (['y_val'], {}), '(y_val)\n', (3465, 3472), True, 'import pandas as pd\n'), ((3482, 3502), 'pandas.get_dummies', 'pd.get_dummies', (['y_te'], {}), '(y_te)\n', (3496, 3502), True, 'import pandas as pd\n'), ((4023, 4034), 'time.time', 'time.time', ([], {}), '()\n', (4032, 4034), False, 'import time\n'), ((4077, 4105), 'sklearn.model_selection.ParameterGrid', 'ParameterGrid', (['tuning_params'], {}), '(tuning_params)\n', (4090, 4105), False, 'from sklearn.model_selection import ParameterGrid\n'), ((6815, 6844), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_tr', 'probs_tr'], {}), '(y_tr, probs_tr)\n', (6828, 6844), False, 'from sklearn.metrics import roc_auc_score\n'), ((6859, 6890), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_val', 'probs_val'], {}), '(y_val, probs_val)\n', (6872, 6890), False, 'from sklearn.metrics import roc_auc_score\n'), ((6904, 6933), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_te', 'probs_te'], {}), '(y_te, probs_te)\n', (6917, 6933), False, 'from sklearn.metrics import roc_auc_score\n'), ((7528, 7539), 'time.time', 'time.time', ([], {}), '()\n', (7537, 7539), False, 'import time\n'), ((3845, 3872), 'os.path.exists', 'os.path.exists', (['save_models'], {}), '(save_models)\n', (3859, 3872), False, 'import os\n'), ((3877, 3901), 'os.makedirs', 'os.makedirs', (['save_models'], {}), '(save_models)\n', (3888, 3901), False, 'import os\n'), ((4122, 4175), 'keras.layers.Input', 'Input', ([], {'shape': '(img_X_tr.shape[1],)', 'name': '"""image_input"""'}), "(shape=(img_X_tr.shape[1],), name='image_input')\n", (4127, 4175), False, 'from keras.layers import Dense, Dropout, Input, concatenate\n'), ((4193, 4250), 'keras.layers.Input', 'Input', ([], {'shape': '(clin_X_tr.shape[1],)', 'name': '"""clinical_input"""'}), "(shape=(clin_X_tr.shape[1],), name='clinical_input')\n", (4198, 4250), False, 'from keras.layers import Dense, Dropout, Input, concatenate\n'), ((4715, 4744), 'keras.layers.concatenate', 'concatenate', (['[dense1, dense2]'], {}), '([dense1, dense2])\n', (4726, 4744), False, 'from keras.layers import Dense, Dropout, Input, concatenate\n'), ((5431, 5478), 'keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'lr': "tune['learning_rate']"}), "(lr=tune['learning_rate'])\n", (5452, 5478), False, 'import keras\n'), ((5493, 5548), 'keras.models.Model', 'Model', ([], {'inputs': '[img_input, clin_input]', 'outputs': '[output]'}), '(inputs=[img_input, clin_input], outputs=[output])\n', (5498, 5548), False, 'from keras.models import load_model, Sequential, Model\n'), ((5552, 5616), 'helper.model.compile', 'model.compile', ([], {'loss': "def_params['loss_func']", 'optimizer': 'optimizer'}), "(loss=def_params['loss_func'], optimizer=optimizer)\n", (5565, 5616), False, 'from helper import dataset, model\n'), ((5632, 5755), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'min_delta': "def_params['min_delta']", 'patience': "def_params['iter_patience']", 'mode': '"""auto"""'}), "(monitor='val_loss', min_delta=def_params['min_delta'],\n patience=def_params['iter_patience'], mode='auto')\n", (5645, 5755), False, 'from keras.callbacks import EarlyStopping\n'), ((5795, 6016), 'helper.model.fit', 'model.fit', (["{'image_input': img_X_tr, 'clinical_input': clin_X_tr}", 'y_tr'], {'callbacks': 'callbacks', 'validation_data': '([img_X_val, clin_X_val], y_val)', 'epochs': "def_params['epochs']", 'batch_size': "tune['batch_size']", 'verbose': '(0)'}), "({'image_input': img_X_tr, 'clinical_input': clin_X_tr}, y_tr,\n callbacks=callbacks, validation_data=([img_X_val, clin_X_val], y_val),\n epochs=def_params['epochs'], batch_size=tune['batch_size'], verbose=0)\n", (5804, 6016), False, 'from helper import dataset, model\n'), ((6037, 6089), 'helper.model.predict', 'model.predict', (['[img_X_val, clin_X_val]'], {'batch_size': '(8)'}), '([img_X_val, clin_X_val], batch_size=8)\n', (6050, 6089), False, 'from helper import dataset, model\n'), ((6105, 6136), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_val', 'probs_val'], {}), '(y_val, probs_val)\n', (6118, 6136), False, 'from sklearn.metrics import roc_auc_score\n'), ((6447, 6476), 'keras.backend.clear_session', 'keras.backend.clear_session', ([], {}), '()\n', (6474, 6476), False, 'import keras\n'), ((7005, 7032), 'os.path.exists', 'os.path.exists', (['save_params'], {}), '(save_params)\n', (7019, 7032), False, 'import os\n'), ((7037, 7061), 'os.makedirs', 'os.makedirs', (['save_params'], {}), '(save_params)\n', (7048, 7061), False, 'import os\n'), ((7195, 7222), 'os.path.exists', 'os.path.exists', (['save_scores'], {}), '(save_scores)\n', (7209, 7222), False, 'import os\n'), ((7227, 7251), 'os.makedirs', 'os.makedirs', (['save_scores'], {}), '(save_scores)\n', (7238, 7251), False, 'import os\n'), ((4956, 4985), 'keras.layers.Dropout', 'Dropout', (["tune['dropout_rate']"], {}), "(tune['dropout_rate'])\n", (4963, 4985), False, 'from keras.layers import Dense, Dropout, Input, concatenate\n'), ((7615, 7650), 'numpy.floor', 'np.floor', (['((end - start) % 3600 / 60)'], {}), '((end - start) % 3600 / 60)\n', (7623, 7650), True, 'import numpy as np\n'), ((4427, 4466), 'keras.regularizers.l2', 'keras.regularizers.l2', (["tune['l2_ratio']"], {}), "(tune['l2_ratio'])\n", (4448, 4466), False, 'import keras\n'), ((4655, 4694), 'keras.regularizers.l2', 'keras.regularizers.l2', (["tune['l2_ratio']"], {}), "(tune['l2_ratio'])\n", (4676, 4694), False, 'import keras\n'), ((4906, 4945), 'keras.regularizers.l2', 'keras.regularizers.l2', (["tune['l2_ratio']"], {}), "(tune['l2_ratio'])\n", (4927, 4945), False, 'import keras\n'), ((5178, 5217), 'keras.regularizers.l2', 'keras.regularizers.l2', (["tune['l2_ratio']"], {}), "(tune['l2_ratio'])\n", (5199, 5217), False, 'import keras\n'), ((5371, 5410), 'keras.regularizers.l2', 'keras.regularizers.l2', (["tune['l2_ratio']"], {}), "(tune['l2_ratio'])\n", (5392, 5410), False, 'import keras\n')]
|
import pandas as pd
import json
import numpy as np
#DEFINITIONS
NAMESPACE = "it.gov.daf.dataset.opendata"
def getData(path):
if (path.lower().endswith((".json", ".geojson"))):
with open(path) as data_file:
dataJson = json.load(data_file)
return pd.io.json.json_normalize(dataJson, sep='.|.')
elif (path.lower().endswith((".csv", ".txt", ".text"))):
separator = csvInferSep(path)
return pd.read_csv(path, sep=separator)
else:
return "-1"
def getFieldsSchema(data):
fields = list()
for c, t in zip(data.columns, data.dtypes):
field = {"name": c, "type": formatConv(t)}
fields.append(field)
return fields;
def getDataSchema(path, datasetName):
data = getData(path)
fields = getFieldsSchema(data)
avro = {
"namespace": NAMESPACE,
"type": "record",
"name": datasetName,
"fields": fields
}
return avro
def formatConv(typeIn):
dic = {
np.dtype('O'): "String",
np.dtype('float64'): 'double',
np.dtype('float32'): 'double',
np.dtype('int64'): 'int',
np.dtype('int32'): 'int',
}
return dic.get(typeIn, "String");
def csvInferSep(path):
f = open(path)
sepList = [",", ';', ':', '|']
first = f.readline()
ordTupleSep = sorted([(x, first.count(x)) for x in sepList], key=lambda x: -x[1])
return ordTupleSep[0][0]
#print(getDataSchema("data.json", "testData"))
|
[
"json.load",
"numpy.dtype",
"pandas.io.json.json_normalize",
"pandas.read_csv"
] |
[((279, 325), 'pandas.io.json.json_normalize', 'pd.io.json.json_normalize', (['dataJson'], {'sep': '""".|."""'}), "(dataJson, sep='.|.')\n", (304, 325), True, 'import pandas as pd\n'), ((991, 1004), 'numpy.dtype', 'np.dtype', (['"""O"""'], {}), "('O')\n", (999, 1004), True, 'import numpy as np\n'), ((1024, 1043), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (1032, 1043), True, 'import numpy as np\n'), ((1063, 1082), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (1071, 1082), True, 'import numpy as np\n'), ((1102, 1119), 'numpy.dtype', 'np.dtype', (['"""int64"""'], {}), "('int64')\n", (1110, 1119), True, 'import numpy as np\n'), ((1136, 1153), 'numpy.dtype', 'np.dtype', (['"""int32"""'], {}), "('int32')\n", (1144, 1153), True, 'import numpy as np\n'), ((243, 263), 'json.load', 'json.load', (['data_file'], {}), '(data_file)\n', (252, 263), False, 'import json\n'), ((441, 473), 'pandas.read_csv', 'pd.read_csv', (['path'], {'sep': 'separator'}), '(path, sep=separator)\n', (452, 473), True, 'import pandas as pd\n')]
|
""" Reference: https://matheusfacure.github.io/python-causality-handbook/11-Propensity-Score.html#
"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import NearestNeighbors
import seaborn as sns
from matplotlib import pyplot as plt
from causalinference import CausalModel
pd.options.mode.chained_assignment = None # default='warn'
def get_pscore(data_frame, solver='liblinear'):
"""Calculate propensity score with logistic regression
Args:
data_frame (pandas.DataFrame): dataframe with input data
Returns:
pandas.DataFrame: dataframe with propensity score
"""
treatment = 'nudge'
outcome = 'outcome'
predictors = data_frame.columns.drop([treatment, outcome])
ps_model = LogisticRegression(solver=solver).fit(
data_frame[predictors].to_numpy().astype('int'),
data_frame[treatment].to_numpy().astype('int')
)
data_ps = data_frame.assign(pscore=ps_model.predict_proba(data_frame[predictors].values)[:, 1])
return data_ps
def check_weights(data_ps):
"""Check if sum of propensity score weights match sample size
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
Return:
tuple: sample size, treated size from weigths, untreated size froms weigths
"""
weight_t = 1./data_ps.query("nudge==1")["pscore"]
weight_nt = 1./(1.-data_ps.query("nudge==0")["pscore"])
print(f"Original sample size {data_ps.shape[0]}")
print("Original treatment sample size", data_ps.query("nudge==1").shape[0])
print("Original control sample size", data_ps.query("nudge==0").shape[0])
print(f"Weighted treatment sample size {round(sum(weight_t), 1)}")
print(f"Weighted control sample size {round(sum(weight_nt), 1)}")
return data_ps.shape[0], sum(weight_t), sum(weight_nt)
def plot_confounding_evidence(data_ps):
"""Use the propensity score to find evidence of confounding
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
"""
sns.boxplot(x="age", y="pscore", data=data_ps)
plt.title("Confounding Evidence")
plt.show()
sns.boxplot(x="gender", y="pscore", data=data_ps)
plt.title("Confounding Evidence")
plt.show()
def plot_overlap(data_ps):
""" check that there is overlap between the treated and untreated population
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
"""
sns.distplot(data_ps.query("nudge==0")["pscore"], kde=False, label="Non Nudged")
sns.distplot(data_ps.query("nudge==1")["pscore"], kde=False, label="Nudged")
plt.title("Positivity Check")
plt.legend()
plt.show()
def get_ate(data_ps):
"""Get ATE without bias correction
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
Returns:
float: average treatment effect
"""
result = data_ps.groupby("nudge")["outcome"].mean()
ate = result[1] - result[0]
# print("Calculate Average Treatment Effect:")
# print(f"Control: {round(result[0], 3)}")
# print(f"Treatment: {round(result[1], 3)}")
# print(f"ATE: {round(ate, 3)}")
return ate
def get_psw_ate(data_ps):
"""Get propensity score weigthed ATE
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
"""
weight = ((data_ps["nudge"] - data_ps["pscore"]) / (data_ps["pscore"]*(1. - data_ps["pscore"])))
ate = np.mean(weight * data_ps["outcome"])
# weight_t = 1./data_ps.query("nudge==1")["pscore"]
# weight_nt = 1./(1.-data_ps.query("nudge==0")["pscore"])
# treatment = sum(data_ps.query("nudge==1")["outcome"]*weight_t) / len(data_ps)
# control = sum(data_ps.query("nudge==0")["outcome"]*weight_nt) / len(data_ps)
# ate = treatment - control
# print(f"Propensity score weighted ATE: {round(ate, 3)}")
return ate
def get_psm_ate(data_ps):
"""Get propensity score matched ATE using CausalModel
Args:
data_ps (pandas.DataFrame): dataframe with propensity score
"""
cmodel = CausalModel(
Y=data_ps["outcome"].values,
D=data_ps["nudge"].values,
X=data_ps[["pscore"]].values
)
cmodel.est_via_ols()
cmodel.est_via_matching(matches=1, bias_adj=True)
print(cmodel.estimates)
def match_ps(data_ps):
"""Match participants in treatment group to control group by propensity score
Args:
data_ps (pandas.DataFrame): dataframe with propensity score of all participants
Returns:
pandas.DataFrame: dataframe with nudged participants and matched control
"""
df1 = data_ps.reset_index()[data_ps["nudge"] == 1]
df2 = data_ps.reset_index()[data_ps["nudge"] == 0]
result = pd.merge_asof(df1.sort_values('pscore'),
df2.sort_values('pscore'),
on='pscore',
direction='nearest',
suffixes=['', '_control'])
columns = list(df1) + ['control']
result = result.rename(columns={"outcome_control": "control"})
result = result[columns].sort_values('index').reset_index(drop=True).drop(
columns=['index', 'nudge', 'pscore'])
return result
|
[
"numpy.mean",
"causalinference.CausalModel",
"sklearn.linear_model.LogisticRegression",
"seaborn.boxplot",
"matplotlib.pyplot.title",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] |
[((2070, 2116), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""age"""', 'y': '"""pscore"""', 'data': 'data_ps'}), "(x='age', y='pscore', data=data_ps)\n", (2081, 2116), True, 'import seaborn as sns\n'), ((2121, 2154), 'matplotlib.pyplot.title', 'plt.title', (['"""Confounding Evidence"""'], {}), "('Confounding Evidence')\n", (2130, 2154), True, 'from matplotlib import pyplot as plt\n'), ((2159, 2169), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2167, 2169), True, 'from matplotlib import pyplot as plt\n'), ((2174, 2223), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': '"""gender"""', 'y': '"""pscore"""', 'data': 'data_ps'}), "(x='gender', y='pscore', data=data_ps)\n", (2185, 2223), True, 'import seaborn as sns\n'), ((2228, 2261), 'matplotlib.pyplot.title', 'plt.title', (['"""Confounding Evidence"""'], {}), "('Confounding Evidence')\n", (2237, 2261), True, 'from matplotlib import pyplot as plt\n'), ((2266, 2276), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2274, 2276), True, 'from matplotlib import pyplot as plt\n'), ((2643, 2672), 'matplotlib.pyplot.title', 'plt.title', (['"""Positivity Check"""'], {}), "('Positivity Check')\n", (2652, 2672), True, 'from matplotlib import pyplot as plt\n'), ((2677, 2689), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2687, 2689), True, 'from matplotlib import pyplot as plt\n'), ((2694, 2704), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2702, 2704), True, 'from matplotlib import pyplot as plt\n'), ((3462, 3498), 'numpy.mean', 'np.mean', (["(weight * data_ps['outcome'])"], {}), "(weight * data_ps['outcome'])\n", (3469, 3498), True, 'import numpy as np\n'), ((4082, 4184), 'causalinference.CausalModel', 'CausalModel', ([], {'Y': "data_ps['outcome'].values", 'D': "data_ps['nudge'].values", 'X': "data_ps[['pscore']].values"}), "(Y=data_ps['outcome'].values, D=data_ps['nudge'].values, X=\n data_ps[['pscore']].values)\n", (4093, 4184), False, 'from causalinference import CausalModel\n'), ((791, 824), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'solver': 'solver'}), '(solver=solver)\n', (809, 824), False, 'from sklearn.linear_model import LogisticRegression\n')]
|
import numpy as np
import theano
import theano.tensor as tensor
from utils import _p, numpy_floatX
from utils import ortho_weight, uniform_weight, zero_bias
""" Encoder using LSTM Recurrent Neural Network. """
def param_init_encoder(options, params, prefix='lstm_encoder'):
n_x = options['n_x']
n_h = options['n_h']
W = np.concatenate([uniform_weight(n_x,n_h),
uniform_weight(n_x,n_h),
uniform_weight(n_x,n_h),
uniform_weight(n_x,n_h)], axis=1)
params[_p(prefix, 'W')] = W
U = np.concatenate([ortho_weight(n_h),
ortho_weight(n_h),
ortho_weight(n_h),
ortho_weight(n_h)], axis=1)
params[_p(prefix, 'U')] = U
params[_p(prefix,'b')] = zero_bias(4*n_h)
# It is observed that setting a high initial forget gate bias for LSTMs can
# give slighly better results (Le et al., 2015). Hence, the initial forget
# gate bias is set to 3.
params[_p(prefix, 'b')][n_h:2*n_h] = 3*np.ones((n_h,)).astype(theano.config.floatX)
return params
def encoder(tparams, state_below, mask, seq_output=False, prefix='lstm_encoder'):
""" state_below: size of n_steps * n_samples * n_x
"""
n_steps = state_below.shape[0]
n_samples = state_below.shape[1]
n_h = tparams[_p(prefix,'U')].shape[0]
def _slice(_x, n, dim):
if _x.ndim == 3:
return _x[:, :, n*dim:(n+1)*dim]
return _x[:, n*dim:(n+1)*dim]
state_below_ = tensor.dot(state_below, tparams[_p(prefix, 'W')]) + \
tparams[_p(prefix, 'b')]
def _step(m_, x_, h_, c_, U):
preact = tensor.dot(h_, U)
preact += x_
i = tensor.nnet.sigmoid(_slice(preact, 0, n_h))
f = tensor.nnet.sigmoid(_slice(preact, 1, n_h))
o = tensor.nnet.sigmoid(_slice(preact, 2, n_h))
c = tensor.tanh(_slice(preact, 3, n_h))
c = f * c_ + i * c
c = m_[:, None] * c + (1. - m_)[:, None] * c_
h = o * tensor.tanh(c)
h = m_[:, None] * h + (1. - m_)[:, None] * h_
return h, c
seqs = [mask, state_below_]
rval, updates = theano.scan(_step,
sequences=seqs,
outputs_info=[tensor.alloc(numpy_floatX(0.),
n_samples,n_h),
tensor.alloc(numpy_floatX(0.),
n_samples,n_h)],
non_sequences = [tparams[_p(prefix, 'U')]],
name=_p(prefix, '_layers'),
n_steps=n_steps,
strict=True)
h_rval = rval[0]
if seq_output:
return h_rval
else:
# size of n_samples * n_h
return h_rval[-1]
|
[
"utils.zero_bias",
"utils.ortho_weight",
"numpy.ones",
"utils.uniform_weight",
"utils._p",
"theano.tensor.tanh",
"utils.numpy_floatX",
"theano.tensor.dot"
] |
[((826, 844), 'utils.zero_bias', 'zero_bias', (['(4 * n_h)'], {}), '(4 * n_h)\n', (835, 844), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((553, 568), 'utils._p', '_p', (['prefix', '"""W"""'], {}), "(prefix, 'W')\n", (555, 568), False, 'from utils import _p, numpy_floatX\n'), ((771, 786), 'utils._p', '_p', (['prefix', '"""U"""'], {}), "(prefix, 'U')\n", (773, 786), False, 'from utils import _p, numpy_floatX\n'), ((808, 823), 'utils._p', '_p', (['prefix', '"""b"""'], {}), "(prefix, 'b')\n", (810, 823), False, 'from utils import _p, numpy_floatX\n'), ((1725, 1742), 'theano.tensor.dot', 'tensor.dot', (['h_', 'U'], {}), '(h_, U)\n', (1735, 1742), True, 'import theano.tensor as tensor\n'), ((361, 385), 'utils.uniform_weight', 'uniform_weight', (['n_x', 'n_h'], {}), '(n_x, n_h)\n', (375, 385), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((410, 434), 'utils.uniform_weight', 'uniform_weight', (['n_x', 'n_h'], {}), '(n_x, n_h)\n', (424, 434), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((459, 483), 'utils.uniform_weight', 'uniform_weight', (['n_x', 'n_h'], {}), '(n_x, n_h)\n', (473, 483), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((508, 532), 'utils.uniform_weight', 'uniform_weight', (['n_x', 'n_h'], {}), '(n_x, n_h)\n', (522, 532), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((603, 620), 'utils.ortho_weight', 'ortho_weight', (['n_h'], {}), '(n_h)\n', (615, 620), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((646, 663), 'utils.ortho_weight', 'ortho_weight', (['n_h'], {}), '(n_h)\n', (658, 663), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((689, 706), 'utils.ortho_weight', 'ortho_weight', (['n_h'], {}), '(n_h)\n', (701, 706), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((732, 749), 'utils.ortho_weight', 'ortho_weight', (['n_h'], {}), '(n_h)\n', (744, 749), False, 'from utils import ortho_weight, uniform_weight, zero_bias\n'), ((1048, 1063), 'utils._p', '_p', (['prefix', '"""b"""'], {}), "(prefix, 'b')\n", (1050, 1063), False, 'from utils import _p, numpy_floatX\n'), ((1656, 1671), 'utils._p', '_p', (['prefix', '"""b"""'], {}), "(prefix, 'b')\n", (1658, 1671), False, 'from utils import _p, numpy_floatX\n'), ((2088, 2102), 'theano.tensor.tanh', 'tensor.tanh', (['c'], {}), '(c)\n', (2099, 2102), True, 'import theano.tensor as tensor\n'), ((2703, 2724), 'utils._p', '_p', (['prefix', '"""_layers"""'], {}), "(prefix, '_layers')\n", (2705, 2724), False, 'from utils import _p, numpy_floatX\n'), ((1080, 1095), 'numpy.ones', 'np.ones', (['(n_h,)'], {}), '((n_h,))\n', (1087, 1095), True, 'import numpy as np\n'), ((1392, 1407), 'utils._p', '_p', (['prefix', '"""U"""'], {}), "(prefix, 'U')\n", (1394, 1407), False, 'from utils import _p, numpy_floatX\n'), ((1606, 1621), 'utils._p', '_p', (['prefix', '"""W"""'], {}), "(prefix, 'W')\n", (1608, 1621), False, 'from utils import _p, numpy_floatX\n'), ((2358, 2375), 'utils.numpy_floatX', 'numpy_floatX', (['(0.0)'], {}), '(0.0)\n', (2370, 2375), False, 'from utils import _p, numpy_floatX\n'), ((2503, 2520), 'utils.numpy_floatX', 'numpy_floatX', (['(0.0)'], {}), '(0.0)\n', (2515, 2520), False, 'from utils import _p, numpy_floatX\n'), ((2647, 2662), 'utils._p', '_p', (['prefix', '"""U"""'], {}), "(prefix, 'U')\n", (2649, 2662), False, 'from utils import _p, numpy_floatX\n')]
|
import numpy as np
import statistics as stat
treshold = 3
def removeFalseData(input_data):
while(1):
try:
input_data.remove(False)
except ValueError:
break
return(input_data)
def removeNegatives(input_data):
processed_data = []
for val in input_data:
if val > 0:
processed_data.append(val)
return processed_data
def removeOutliers(input_data):
#dataset = removeNegatives(input_data)
processed_data = []
med = stat.median(input_data)
avg = np.mean(input_data)
stdev = np.std(input_data)
for val in input_data:
score = abs(val-med)
if score < 500:
processed_data.append(val)
# z_score = abs(((val) - avg)/stdev)
# if z_score < treshold:
# processed_data.append(val)
return processed_data
def filterData(input_data):
#print(input_data)
dataset = removeFalseData(input_data)
dataset = removeOutliers(dataset)
#print('filtered')
#print(dataset)
return np.mean(dataset)
|
[
"statistics.median",
"numpy.mean",
"numpy.std"
] |
[((528, 551), 'statistics.median', 'stat.median', (['input_data'], {}), '(input_data)\n', (539, 551), True, 'import statistics as stat\n'), ((563, 582), 'numpy.mean', 'np.mean', (['input_data'], {}), '(input_data)\n', (570, 582), True, 'import numpy as np\n'), ((596, 614), 'numpy.std', 'np.std', (['input_data'], {}), '(input_data)\n', (602, 614), True, 'import numpy as np\n'), ((1078, 1094), 'numpy.mean', 'np.mean', (['dataset'], {}), '(dataset)\n', (1085, 1094), True, 'import numpy as np\n')]
|
"""
This script contains several car-following control models for flow-controlled
vehicles.
Controllers can have their output delayed by some duration. Each controller
includes functions
get_accel(self, env) -> acc
- using the current state of the world and existing parameters,
uses the control model to return a vehicle acceleration.
reset_delay(self) -> None
- clears the queue of acceleration outputs used to generate
delayed output. used when the experiment is reset to clear out
old actions based on old states.
"""
import random
import math
from flow.controllers.base_controller import BaseController
import collections
import numpy as np
class CFMController(BaseController):
def __init__(self, veh_id, k_d=1, k_v=1, k_c=1, d_des=1, v_des=8,
accel_max=20, decel_max=-5, tau=0.5, dt=0.1, noise=0):
"""
Instantiates a CFM controller
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
k_d: float
headway gain (default: 1)
k_v: float, optional
gain on difference between lead velocity and current (default: 1)
k_c: float, optional
gain on difference from desired velocity to current (default: 1)
d_des: float, optional
desired headway (default: 1)
v_des: float, optional
desired velocity (default: 8)
accel_max: float
max acceleration (default: 20)
decel_max: float
max deceleration (default: -5)
tau: float, optional
time delay (default: 0)
dt: float, optional
timestep (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
controller_params = {"delay": tau/dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.veh_id = veh_id
self.k_d = k_d
self.k_v = k_v
self.k_c = k_c
self.d_des = d_des
self.v_des = v_des
self.accel_max = accel_max
self.accel_queue = collections.deque()
def get_accel(self, env):
lead_id = env.vehicles.get_leader(self.veh_id)
if not lead_id: # no car ahead
return self.accel_max
lead_vel = env.vehicles.get_speed(lead_id)
this_vel = env.vehicles.get_speed(self.veh_id)
d_l = env.vehicles.get_headway(self.veh_id)
acc = self.k_d*(d_l - self.d_des) + self.k_v*(lead_vel - this_vel) + \
self.k_c*(self.v_des - this_vel)
while len(self.accel_queue) <= self.delay:
# Some behavior here for initial states - extrapolation, dumb
# filling (currently), etc
self.accel_queue.appendleft(acc)
return min(self.accel_queue.pop(), self.accel_max)
def reset_delay(self, env):
self.accel_queue.clear()
class BCMController(BaseController):
def __init__(self, veh_id, k_d=1, k_v=1, k_c=1, d_des=1, v_des=8,
accel_max=15, decel_max=-5, tau=0.5, dt=0.1, noise=0):
"""
Instantiates a Bilateral car-following model controller. Looks ahead
and behind.
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
k_d: float, optional
gain on distances to lead/following cars (default: 1)
k_v: float, optional
gain on vehicle velocity differences (default: 1)
k_c: float, optional
gain on difference from desired velocity to current (default: 1)
d_des: float, optional
desired headway (default: 1)
v_des: float, optional
desired velocity (default: 8)
accel_max: float, optional
max acceleration (default: 15)
decel_max: float
max deceleration (default: -5)
tau: float, optional
time delay (default: 0.5)
dt: float, optional
timestep (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
controller_params = {"delay": tau / dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.veh_id = veh_id
self.k_d = k_d
self.k_v = k_v
self.k_c = k_c
self.d_des = d_des
self.v_des = v_des
self.accel_max = accel_max
self.accel_queue = collections.deque()
def get_accel(self, env):
"""
From the paper:
There would also be additional control rules that take
into account minimum safe separation, relative speeds,
speed limits, weather and lighting conditions, traffic density
and traffic advisories
"""
lead_id = env.vehicles.get_leader(self.veh_id)
if not lead_id: # no car ahead
return self.accel_max
lead_vel = env.vehicles.get_speed(lead_id)
this_vel = env.vehicles.get_speed(self.veh_id)
trail_id = env.vehicles.get_follower(self.veh_id)
trail_vel = env.vehicles.get_speed(trail_id)
headway = env.vehicles.get_headway(self.veh_id)
footway = env.vehicles.get_headway(trail_id)
acc = self.k_d * (headway - footway) + \
self.k_v * ((lead_vel - this_vel) - (this_vel - trail_vel)) + \
self.k_c * (self.v_des - this_vel)
while len(self.accel_queue) <= self.delay:
# Some behavior here for initial states - extrapolation, dumb
# filling (currently), etc
self.accel_queue.appendleft(acc)
return min(self.accel_queue.pop(), self.accel_max)
def reset_delay(self, env):
self.accel_queue.clear()
class OVMController(BaseController):
def __init__(self, veh_id, alpha=1, beta=1, h_st=2, h_go=15, v_max=30,
accel_max=15, decel_max=-5, tau=0.5, dt=0.1, noise=0):
"""
Instantiates an Optimal Vehicle Model controller.
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
alpha: float, optional
gain on desired velocity to current velocity difference
(default: 0.6)
beta: float, optional
gain on lead car velocity and self velocity difference
(default: 0.9)
h_st: float, optional
headway for stopping (default: 5)
h_go: float, optional
headway for full speed (default: 35)
v_max: float, optional
max velocity (default: 30)
accel_max: float, optional
max acceleration (default: 15)
decel_max: float, optional
max deceleration (default: -5)
tau: float, optional
time delay (default: 0.5)
dt: float, optional
timestep (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
controller_params = {"delay": tau/dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.accel_queue = collections.deque()
self.decel_max = decel_max
self.accel_max = accel_max
self.veh_id = veh_id
self.v_max = v_max
self.alpha = alpha
self.beta = beta
self.h_st = h_st
self.h_go = h_go
self.tau = tau
self.dt = dt
def get_accel(self, env):
lead_id = env.vehicles.get_leader(self.veh_id)
if not lead_id: # no car ahead
return self.accel_max
lead_vel = env.vehicles.get_speed(lead_id)
this_vel = env.vehicles.get_speed(self.veh_id)
h = env.vehicles.get_headway(self.veh_id)
h_dot = lead_vel - this_vel
# V function here - input: h, output : Vh
if h <= self.h_st:
Vh = 0
elif self.h_st < h < self.h_go:
Vh = self.v_max / 2 * (1 - math.cos(math.pi * (h - self.h_st) /
(self.h_go - self.h_st)))
else:
Vh = self.v_max
acc = self.alpha*(Vh - this_vel) + self.beta*(h_dot)
while len(self.accel_queue) <= self.delay:
# Some behavior here for initial states - extrapolation, dumb
# filling (currently), etc
self.accel_queue.appendleft(acc)
return max(min(self.accel_queue.pop(), self.accel_max),
-1 * abs(self.decel_max))
def reset_delay(self, env):
self.accel_queue.clear()
class LinearOVM(BaseController):
def __init__(self, veh_id, v_max=30, accel_max=15, decel_max=-5,
adaptation=0.65, h_st=5, tau=0.5, dt=0.1, noise=0):
"""
Instantiates a Linear OVM controller
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
v_max: float, optional
max velocity (default: 30)
accel_max: float, optional
max acceleration (default: 15)
decel_max: float, optional
max deceleration (default: -5)
adaptation: float
adaptation constant (default: 0.65)
h_st: float, optional
headway for stopping (default: 5)
tau: float, optional
time delay (default: 0.5)
dt: float, optional
timestep (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
controller_params = {"delay": tau / dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.accel_queue = collections.deque()
self.decel_max = decel_max
self.acc_max = accel_max
self.veh_id = veh_id
# 4.8*1.85 for case I, 3.8*1.85 for case II, per Nakayama
self.v_max = v_max
# TAU in Traffic Flow Dynamics textbook
self.adaptation = adaptation
self.h_st = h_st
self.delay_time = tau
self.dt = dt
def get_accel(self, env):
this_vel = env.vehicles.get_speed(self.veh_id)
h = env.vehicles.get_headway(self.veh_id)
# V function here - input: h, output : Vh
alpha = 1.689 # the average value from Nakayama paper
if h < self.h_st:
Vh = 0
elif self.h_st <= h <= self.h_st + self.v_max/alpha:
Vh = alpha * (h - self.h_st)
else:
Vh = self.v_max
acc = (Vh - this_vel) / self.adaptation
while len(self.accel_queue) <= self.delay:
# Some behavior here for initial states - extrapolation, dumb
# filling (currently), etc
self.accel_queue.appendleft(acc)
return max(min(self.accel_queue.pop(), self.acc_max),
-1 * abs(self.decel_max))
def reset_delay(self, env):
self.accel_queue.clear()
class IDMController(BaseController):
def __init__(self, veh_id, v0=30, T=1, a=1, b=1.5, delta=4, s0=2, s1=0,
decel_max=-5, dt=0.1, noise=0):
"""
Instantiates an Intelligent Driver Model (IDM) controller
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
v0: float, optional
desirable velocity, in m/s (default: 30)
T: float, optional
safe time headway, in s (default: 1)
a: float, optional
maximum acceleration, in m/s2 (default: 1)
b: float, optional
comfortable deceleration, in m/s2 (default: 1.5)
delta: float, optional
acceleration exponent (default: 4)
s0: float, optional
linear jam distance, in m (default: 2)
s1: float, optional
nonlinear jam distance, in m (default: 0)
decel_max: float, optional
max deceleration, in m/s2 (default: -5)
dt: float, optional
timestep, in s (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
tau = T # the time delay is taken to be the safe time headway
controller_params = {"delay": tau / dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.v0 = v0
self.T = T
self.a = a
self.b = b
self.delta = delta
self.s0 = s0
self.s1 = s1
self.max_deaccel = decel_max
self.dt = dt
def get_accel(self, env):
this_vel = env.vehicles.get_speed(self.veh_id)
lead_id = env.vehicles.get_leader(self.veh_id)
h = env.vehicles.get_headway(self.veh_id)
# negative headways may be registered by sumo at intersections/junctions
# setting them to 0 causes vehicles to not move; therefore, we maintain
# these negative headways to let sumo control the dynamics as it sees
# fit at these points
if abs(h) < 1e-3:
h = 1e-3
if lead_id is None or lead_id == '': # no car ahead
s_star = 0
else:
lead_vel = env.vehicles.get_speed(lead_id)
s_star = \
self.s0 + max([0, this_vel*self.T + this_vel*(this_vel-lead_vel)
/ (2 * np.sqrt(self.a * self.b))])
return self.a * (1 - (this_vel/self.v0)**self.delta - (s_star/h)**2)
def reset_delay(self, env):
pass
class RandomController(BaseController):
def __init__(self, veh_id, v0=30, T=1, a=1, b=1.5, delta=4, s0=2, s1=0,
decel_max=-5, dt=0.1, noise=0):
"""
Instantiates an Intelligent Driver Model (IDM) controller
Attributes
----------
veh_id: str
Vehicle ID for SUMO identification
v0: float, optional
desirable velocity, in m/s (default: 30)
T: float, optional
safe time headway, in s (default: 1)
a: float, optional
maximum acceleration, in m/s2 (default: 1)
b: float, optional
comfortable deceleration, in m/s2 (default: 1.5)
delta: float, optional
acceleration exponent (default: 4)
s0: float, optional
linear jam distance, in m (default: 2)
s1: float, optional
nonlinear jam distance, in m (default: 0)
decel_max: float, optional
max deceleration, in m/s2 (default: -5)
dt: float, optional
timestep, in s (default: 0.1)
noise: float, optional
std dev of normal perturbation to the acceleration (default: 0)
"""
tau = T # the time delay is taken to be the safe time headway
controller_params = {"delay": tau / dt, "max_deaccel": decel_max,
"noise": noise}
BaseController.__init__(self, veh_id, controller_params)
self.v0 = v0
self.T = T
self.a = a
self.b = b
self.delta = delta
self.s0 = s0
self.s1 = s1
self.max_deaccel = decel_max
self.dt = dt
def get_accel(self, env):
return np.clip(np.random.normal(self.a/2, 2*np.abs(self.a)), self.max_deaccel, self.a)
#return np.random.uniform(self.max_deaccel, self.a)
def reset_delay(self, env):
pass
|
[
"numpy.abs",
"flow.controllers.base_controller.BaseController.__init__",
"collections.deque",
"numpy.sqrt",
"math.cos"
] |
[((1966, 2022), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (1989, 2022), False, 'from flow.controllers.base_controller import BaseController\n'), ((2237, 2256), 'collections.deque', 'collections.deque', ([], {}), '()\n', (2254, 2256), False, 'import collections\n'), ((4403, 4459), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (4426, 4459), False, 'from flow.controllers.base_controller import BaseController\n'), ((4674, 4693), 'collections.deque', 'collections.deque', ([], {}), '()\n', (4691, 4693), False, 'import collections\n'), ((7337, 7393), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (7360, 7393), False, 'from flow.controllers.base_controller import BaseController\n'), ((7421, 7440), 'collections.deque', 'collections.deque', ([], {}), '()\n', (7438, 7440), False, 'import collections\n'), ((9941, 9997), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (9964, 9997), False, 'from flow.controllers.base_controller import BaseController\n'), ((10025, 10044), 'collections.deque', 'collections.deque', ([], {}), '()\n', (10042, 10044), False, 'import collections\n'), ((12657, 12713), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (12680, 12713), False, 'from flow.controllers.base_controller import BaseController\n'), ((15265, 15321), 'flow.controllers.base_controller.BaseController.__init__', 'BaseController.__init__', (['self', 'veh_id', 'controller_params'], {}), '(self, veh_id, controller_params)\n', (15288, 15321), False, 'from flow.controllers.base_controller import BaseController\n'), ((15610, 15624), 'numpy.abs', 'np.abs', (['self.a'], {}), '(self.a)\n', (15616, 15624), True, 'import numpy as np\n'), ((8250, 8311), 'math.cos', 'math.cos', (['(math.pi * (h - self.h_st) / (self.h_go - self.h_st))'], {}), '(math.pi * (h - self.h_st) / (self.h_go - self.h_st))\n', (8258, 8311), False, 'import math\n'), ((13723, 13747), 'numpy.sqrt', 'np.sqrt', (['(self.a * self.b)'], {}), '(self.a * self.b)\n', (13730, 13747), True, 'import numpy as np\n')]
|
"""
Unchanged from https://github.com/hughsalimbeni/DGPs_with_IWVI/blob/master/tests/test_gp_layer.py
"""
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.FATAL)
import gpflow
from dgps_with_iwvi.layers import GPLayer
from dgps_with_iwvi.models import DGP_VI
def test_gp_layer():
N = 10001
M = 100
Dy = 1
np.random.seed(0)
X = np.linspace(0, 1, N).reshape(-1, 1)
Z = np.linspace(0, 1, M).reshape(-1, 1)
Xs = np.linspace(0, 1, N - 1).reshape(-1, 1)
Y = np.concatenate([np.sin(10 * X), np.cos(10 * X)], 1)[:, 0:1]
kern = gpflow.kernels.Matern52(1, lengthscales=0.1)
mean_function = gpflow.mean_functions.Linear(A=np.random.randn(1, Dy))
lik = gpflow.likelihoods.Gaussian(variance=1e-1)
m_vgp = gpflow.models.SVGP(X, Y, kern, lik, Z=Z, mean_function=mean_function)
q_mu = np.random.randn(M, Dy)
q_sqrt = np.random.randn(Dy, M, M)
m_vgp.q_mu = q_mu
m_vgp.q_sqrt = q_sqrt
m1, v1 = m_vgp.predict_f_full_cov(Xs)
L1 = m_vgp.compute_log_likelihood()
m_dgp = DGP_VI(X, Y, [GPLayer(kern, Z, Dy, mean_function)], lik, num_samples=1)
m_dgp.layers[0].q_mu = q_mu
m_dgp.layers[0].q_sqrt = q_sqrt
m2, v2 = m_dgp.predict_f_full_cov(Xs)
L2 = m_dgp.compute_log_likelihood()
np.testing.assert_allclose(L1, L2)
np.testing.assert_allclose(m1, m2)
np.testing.assert_allclose(v1, v2)
def test_dgp_zero_inner_layers():
N = 10
Dy = 2
X = np.linspace(0, 1, N).reshape(-1, 1)
Xs = np.linspace(0, 1, N - 1).reshape(-1, 1)
Y = np.concatenate([np.sin(10 * X), np.cos(10 * X)], 1)
kern = gpflow.kernels.Matern52(1, lengthscales=0.1)
mean_function = gpflow.mean_functions.Linear(A=np.random.randn(1, 2))
lik = gpflow.likelihoods.Gaussian(variance=1e-1)
m_vgp = gpflow.models.SVGP(X, Y, kern, lik, Z=X, mean_function=mean_function)
q_mu = np.random.randn(N, Dy)
q_sqrt = np.random.randn(Dy, N, N)
m_vgp.q_mu = q_mu
m_vgp.q_sqrt = q_sqrt
m1, v1 = m_vgp.predict_f_full_cov(Xs)
custom_config = gpflow.settings.get_settings()
custom_config.numerics.jitter_level = 1e-18
with gpflow.settings.temp_settings(custom_config):
m_dgp = DGP_VI(
X,
Y,
[
GPLayer(
gpflow.kernels.RBF(1, variance=1e-6), X, 1, gpflow.mean_functions.Identity()
),
GPLayer(kern, X, Dy, mean_function),
],
lik,
)
m_dgp.layers[-1].q_mu = q_mu
m_dgp.layers[-1].q_sqrt = q_sqrt
m_dgp.layers[0].q_sqrt = m_dgp.layers[0].q_sqrt.read_value() * 1e-12
m2, v2 = m_dgp.predict_f_full_cov(Xs)
np.testing.assert_allclose(m1, m2, atol=1e-5, rtol=1e-5)
np.testing.assert_allclose(v1, v2, atol=1e-5, rtol=1e-5)
|
[
"gpflow.kernels.Matern52",
"gpflow.settings.get_settings",
"numpy.testing.assert_allclose",
"tensorflow.logging.set_verbosity",
"gpflow.settings.temp_settings",
"numpy.linspace",
"numpy.random.randn",
"gpflow.models.SVGP",
"numpy.random.seed",
"numpy.cos",
"gpflow.kernels.RBF",
"numpy.sin",
"dgps_with_iwvi.layers.GPLayer",
"gpflow.likelihoods.Gaussian",
"gpflow.mean_functions.Identity"
] |
[((152, 194), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.FATAL'], {}), '(tf.logging.FATAL)\n', (176, 194), True, 'import tensorflow as tf\n'), ((359, 376), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (373, 376), True, 'import numpy as np\n'), ((596, 640), 'gpflow.kernels.Matern52', 'gpflow.kernels.Matern52', (['(1)'], {'lengthscales': '(0.1)'}), '(1, lengthscales=0.1)\n', (619, 640), False, 'import gpflow\n'), ((726, 767), 'gpflow.likelihoods.Gaussian', 'gpflow.likelihoods.Gaussian', ([], {'variance': '(0.1)'}), '(variance=0.1)\n', (753, 767), False, 'import gpflow\n'), ((782, 851), 'gpflow.models.SVGP', 'gpflow.models.SVGP', (['X', 'Y', 'kern', 'lik'], {'Z': 'Z', 'mean_function': 'mean_function'}), '(X, Y, kern, lik, Z=Z, mean_function=mean_function)\n', (800, 851), False, 'import gpflow\n'), ((864, 886), 'numpy.random.randn', 'np.random.randn', (['M', 'Dy'], {}), '(M, Dy)\n', (879, 886), True, 'import numpy as np\n'), ((900, 925), 'numpy.random.randn', 'np.random.randn', (['Dy', 'M', 'M'], {}), '(Dy, M, M)\n', (915, 925), True, 'import numpy as np\n'), ((1300, 1334), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['L1', 'L2'], {}), '(L1, L2)\n', (1326, 1334), True, 'import numpy as np\n'), ((1339, 1373), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['m1', 'm2'], {}), '(m1, m2)\n', (1365, 1373), True, 'import numpy as np\n'), ((1378, 1412), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['v1', 'v2'], {}), '(v1, v2)\n', (1404, 1412), True, 'import numpy as np\n'), ((1638, 1682), 'gpflow.kernels.Matern52', 'gpflow.kernels.Matern52', (['(1)'], {'lengthscales': '(0.1)'}), '(1, lengthscales=0.1)\n', (1661, 1682), False, 'import gpflow\n'), ((1767, 1808), 'gpflow.likelihoods.Gaussian', 'gpflow.likelihoods.Gaussian', ([], {'variance': '(0.1)'}), '(variance=0.1)\n', (1794, 1808), False, 'import gpflow\n'), ((1823, 1892), 'gpflow.models.SVGP', 'gpflow.models.SVGP', (['X', 'Y', 'kern', 'lik'], {'Z': 'X', 'mean_function': 'mean_function'}), '(X, Y, kern, lik, Z=X, mean_function=mean_function)\n', (1841, 1892), False, 'import gpflow\n'), ((1905, 1927), 'numpy.random.randn', 'np.random.randn', (['N', 'Dy'], {}), '(N, Dy)\n', (1920, 1927), True, 'import numpy as np\n'), ((1941, 1966), 'numpy.random.randn', 'np.random.randn', (['Dy', 'N', 'N'], {}), '(Dy, N, N)\n', (1956, 1966), True, 'import numpy as np\n'), ((2080, 2110), 'gpflow.settings.get_settings', 'gpflow.settings.get_settings', ([], {}), '()\n', (2108, 2110), False, 'import gpflow\n'), ((2168, 2212), 'gpflow.settings.temp_settings', 'gpflow.settings.temp_settings', (['custom_config'], {}), '(custom_config)\n', (2197, 2212), False, 'import gpflow\n'), ((2731, 2789), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['m1', 'm2'], {'atol': '(1e-05)', 'rtol': '(1e-05)'}), '(m1, m2, atol=1e-05, rtol=1e-05)\n', (2757, 2789), True, 'import numpy as np\n'), ((2796, 2854), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['v1', 'v2'], {'atol': '(1e-05)', 'rtol': '(1e-05)'}), '(v1, v2, atol=1e-05, rtol=1e-05)\n', (2822, 2854), True, 'import numpy as np\n'), ((386, 406), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'N'], {}), '(0, 1, N)\n', (397, 406), True, 'import numpy as np\n'), ((430, 450), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'M'], {}), '(0, 1, M)\n', (441, 450), True, 'import numpy as np\n'), ((475, 499), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(N - 1)'], {}), '(0, 1, N - 1)\n', (486, 499), True, 'import numpy as np\n'), ((692, 714), 'numpy.random.randn', 'np.random.randn', (['(1)', 'Dy'], {}), '(1, Dy)\n', (707, 714), True, 'import numpy as np\n'), ((1085, 1120), 'dgps_with_iwvi.layers.GPLayer', 'GPLayer', (['kern', 'Z', 'Dy', 'mean_function'], {}), '(kern, Z, Dy, mean_function)\n', (1092, 1120), False, 'from dgps_with_iwvi.layers import GPLayer\n'), ((1480, 1500), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'N'], {}), '(0, 1, N)\n', (1491, 1500), True, 'import numpy as np\n'), ((1525, 1549), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(N - 1)'], {}), '(0, 1, N - 1)\n', (1536, 1549), True, 'import numpy as np\n'), ((1590, 1604), 'numpy.sin', 'np.sin', (['(10 * X)'], {}), '(10 * X)\n', (1596, 1604), True, 'import numpy as np\n'), ((1606, 1620), 'numpy.cos', 'np.cos', (['(10 * X)'], {}), '(10 * X)\n', (1612, 1620), True, 'import numpy as np\n'), ((1734, 1755), 'numpy.random.randn', 'np.random.randn', (['(1)', '(2)'], {}), '(1, 2)\n', (1749, 1755), True, 'import numpy as np\n'), ((540, 554), 'numpy.sin', 'np.sin', (['(10 * X)'], {}), '(10 * X)\n', (546, 554), True, 'import numpy as np\n'), ((556, 570), 'numpy.cos', 'np.cos', (['(10 * X)'], {}), '(10 * X)\n', (562, 570), True, 'import numpy as np\n'), ((2439, 2474), 'dgps_with_iwvi.layers.GPLayer', 'GPLayer', (['kern', 'X', 'Dy', 'mean_function'], {}), '(kern, X, Dy, mean_function)\n', (2446, 2474), False, 'from dgps_with_iwvi.layers import GPLayer\n'), ((2327, 2364), 'gpflow.kernels.RBF', 'gpflow.kernels.RBF', (['(1)'], {'variance': '(1e-06)'}), '(1, variance=1e-06)\n', (2345, 2364), False, 'import gpflow\n'), ((2371, 2403), 'gpflow.mean_functions.Identity', 'gpflow.mean_functions.Identity', ([], {}), '()\n', (2401, 2403), False, 'import gpflow\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.