code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
__description__ = \
"""
assembly_auto_inhibition.py
Model of ligand-mediated protein assembly and autoinhibition of the assembly, also
referred to as auto-regulated protein assembly and related to the prozone effect.
"""
__author__ = "<NAME>"
__date__ = "2018-02-22"
import inspect
import numpy as np
from scipy.optimize import root as solve_mass_balance
from scipy.optimize import OptimizeResult
from pytc.indiv_models.base import ITCModel
class AssemblyAutoInhibition(ITCModel):
"""
Model of ligand-mediated protein assembly and auto-inhibition of the assembly.
"""
def param_definition(Klig1=1e7,Klig2=1e5,Kolig=1e6,
dHlig1=-30.,dHlig2=-30.,dHolig=-210.,
m=2.,n_lig=5.,n_prot=4.,
fx_prot_competent=1.0,fx_lig_competent=1.0):
"""
Klig1: macroscopic association constant for binding of the first ligand (titrant)
to the protein monomer (stationary) (M-1)
Klig2: "average" macroscopic association constant for binding of the
remaining m-1 ligands (titrant) to the protein monomer (stationary) (M-1)
Kolig: "average" macroscopic association constant for formation of the
protein oligomer (M-1)
dHlig1: enthalpy for binding of the first ligand (titrant) to the protein
monomer (stationary)
dHlig2: enthalpy for binding of the remaining m-1 ligands (titrant) to the
protein monomer (stationary)
dHolig: enthalpy for formation of the protein oligomer
m: stoichiometry of ligands (titrant) in the ligand saturated protein monomer,
must be greater than or equal to 2
n_lig: stoichiometry of ligands (titrant) in the protein oligomer
n_prot: stoichiometry of proteins (stationary) in the protein oligomer
fx_prot_competent: fraction of binding competent protein
fx_lig_competent: fraction of binding competent ligand
"""
pass
def __init__(self,
S_cell=100e-6,S_syringe=0.0,
T_cell=0.0, T_syringe=1000e-6,
is_reverse=False,
cell_volume=300.0,
shot_volumes=[2.5 for i in range(30)]):
"""
S_cell: stationary concentration in cell in M
S_syringe: stationary concentration in syringe in M
T_cell: titrant concentration cell in M
T_syringe: titrant concentration syringe in M
is_reverse: is the experiment a reverse titration setup, boolean
(this will trigger a swapping of the 'titrant' and 'stationary' for the experiment)
cell_volume: cell volume, in uL
shot_volumes: list of shot volumes, in uL.
"""
super().__init__(S_cell,S_syringe,T_cell,T_syringe,cell_volume,shot_volumes)
self._is_reverse = is_reverse
# set initial bounds of certain parameters
self._params["m"]._bounds = (2.,100.)
self._params["n_lig"]._bounds = (0.1,100.)
self._params["n_prot"]._bounds = (0.1,100.)
@property
def dQ(self):
"""
Calculate the heats that would be observed across shots for a given set
of enthalpies and binding constants for each reaction.
"""
# if reverse titration setup swap the corrections for competent stationary and competent titrant
if(self._is_reverse):
S_conc_corr = self._S_conc*self.param_values["fx_lig_competent"]
T_conc_corr = self._T_conc*self.param_values["fx_prot_competent"]
else:
S_conc_corr = self._S_conc*self.param_values["fx_prot_competent"]
T_conc_corr = self._T_conc*self.param_values["fx_lig_competent"]
num_shots = len(S_conc_corr)
heat_array = np.zeros((num_shots-1),dtype=float)
prot_free = np.zeros((num_shots),dtype=float)
lig_free = np.zeros((num_shots),dtype=float)
# call function to compute the free species by numerical solution of the mass balance equations
(prot_free, lig_free) = solve_mb(self._is_reverse, num_shots,
self.param_values["Klig1"], self.param_values["Klig2"], self.param_values["Kolig"],
self.param_values["m"], self.param_values["n_lig"], self.param_values["n_prot"], S_conc_corr,
T_conc_corr)
# compute the heat of each injection
heat_array = self._cell_volume * \
(self.param_values["dHlig1"] * (self.param_values["Klig1"] * prot_free[1:] * lig_free[1:] - \
self.param_values["Klig1"] * prot_free[:-1] * lig_free[:-1] * (1. - self._shot_volumes/self._cell_volume)) + \
(self.param_values["dHlig1"] + self.param_values["dHlig2"]) * (self.param_values["Klig1"] * self.param_values["Klig2"]**(self.param_values["m"]-1) * prot_free[1:] * lig_free[1:]**self.param_values["m"] - \
self.param_values["Klig1"] * self.param_values["Klig2"]**(self.param_values["m"]-1) * prot_free[:-1] * lig_free[:-1]**self.param_values["m"] * (1. - self._shot_volumes/self._cell_volume)) + \
self.param_values["dHolig"] * (self.param_values["Kolig"]**(self.param_values["n_lig"] + self.param_values["n_prot"] - 1) * prot_free[1:]**self.param_values["n_prot"] * lig_free[1:]**self.param_values["n_lig"] - \
self.param_values["Kolig"]**(self.param_values["n_lig"] + self.param_values["n_prot"] - 1) * prot_free[:-1]**self.param_values["n_prot"] * lig_free[:-1]**self.param_values["n_lig"] * (1. - self._shot_volumes/self._cell_volume)))
# correct for the heats of dilution
return heat_array + self.dilution_heats
def solve_mb(reverse, N_points, K1, K2, K3, m, n_oligL, n_oligP, Pt, Lt):
"""
Solve mass balance equations for the Assembly AutoInhibition model.
Returns a tuple of arrays for the free protein and free ligand concentrations.
"""
p = np.zeros(N_points)
l = np.zeros(N_points)
# if reverse titration setup swap titrant and stationary
if(reverse):
tmp = Pt
Pt = Lt
Lt = tmp
p[0] = Pt[0]
l[0] = Lt[0]
for i in range(N_points-1):
# mass balance equations
def equations(x):
p,l = x
return [p + K1*p*l + K1*K2**(m-1.)*p*l**m + n_oligP*(K3**(n_oligL+n_oligP-1))*p**n_oligP*l**n_oligL - Pt[i+1], \
l + K1*p*l + m*K1*K2**(m-1.)*p*l**m + n_oligL*(K3**(n_oligL+n_oligP-1))*p**n_oligP*l**n_oligL - Lt[i+1]]
sol = OptimizeResult(success=False)
ptmp = -1
ltmp = -1
j = 1.
# try to solve using previous free concentrations as initial guesses. Maximum number of iterations is large as gradient may be very shallow
sol = solve_mass_balance(equations,(p[i],l[i]),method='lm',options={'maxiter':2000})
ptmp,ltmp = sol.x
# if no solution try to solve with different initial conditions and solver options
if(not sol.success):
sol = solve_mass_balance(equations,(Pt[i],Lt[i]),method='lm',options={'factor':1,'maxiter':8000})
ptmp,ltmp = sol.x
# if still no solution...bugger
if(not sol.success):
print("ERROR: Could not find solution...")
l[i+1] = ltmp
p[i+1] = ptmp
return (p,l)
| [
"scipy.optimize.root",
"numpy.zeros",
"scipy.optimize.OptimizeResult"
] | [((6148, 6166), 'numpy.zeros', 'np.zeros', (['N_points'], {}), '(N_points)\n', (6156, 6166), True, 'import numpy as np\n'), ((6175, 6193), 'numpy.zeros', 'np.zeros', (['N_points'], {}), '(N_points)\n', (6183, 6193), True, 'import numpy as np\n'), ((3913, 3949), 'numpy.zeros', 'np.zeros', (['(num_shots - 1)'], {'dtype': 'float'}), '(num_shots - 1, dtype=float)\n', (3921, 3949), True, 'import numpy as np\n'), ((3969, 4001), 'numpy.zeros', 'np.zeros', (['num_shots'], {'dtype': 'float'}), '(num_shots, dtype=float)\n', (3977, 4001), True, 'import numpy as np\n'), ((4022, 4054), 'numpy.zeros', 'np.zeros', (['num_shots'], {'dtype': 'float'}), '(num_shots, dtype=float)\n', (4030, 4054), True, 'import numpy as np\n'), ((6764, 6793), 'scipy.optimize.OptimizeResult', 'OptimizeResult', ([], {'success': '(False)'}), '(success=False)\n', (6778, 6793), False, 'from scipy.optimize import OptimizeResult\n'), ((7007, 7094), 'scipy.optimize.root', 'solve_mass_balance', (['equations', '(p[i], l[i])'], {'method': '"""lm"""', 'options': "{'maxiter': 2000}"}), "(equations, (p[i], l[i]), method='lm', options={'maxiter':\n 2000})\n", (7025, 7094), True, 'from scipy.optimize import root as solve_mass_balance\n'), ((7250, 7353), 'scipy.optimize.root', 'solve_mass_balance', (['equations', '(Pt[i], Lt[i])'], {'method': '"""lm"""', 'options': "{'factor': 1, 'maxiter': 8000}"}), "(equations, (Pt[i], Lt[i]), method='lm', options={\n 'factor': 1, 'maxiter': 8000})\n", (7268, 7353), True, 'from scipy.optimize import root as solve_mass_balance\n')] |
# -*- coding: utf-8 -*-
from operator import attrgetter
import datetime
import numpy as np
from ..distance import DistanceHypothesiser
from ...types.detection import Detection
from ...types.state import GaussianState
from ...types.track import Track
from ... import measures
def test_mahalanobis(predictor, updater):
timestamp = datetime.datetime.now()
track = Track([GaussianState(np.array([[0]]), np.array([[1]]), timestamp)])
detection1 = Detection(np.array([[2]]))
detection2 = Detection(np.array([[3]]))
detection3 = Detection(np.array([[10]]))
detections = {detection1, detection2, detection3}
measure = measures.Mahalanobis()
hypothesiser = DistanceHypothesiser(
predictor, updater, measure=measure, missed_distance=3)
hypotheses = hypothesiser.hypothesise(track, detections, timestamp)
# There are 3 hypotheses - Detection 1, Detection 2, Missed Detection
assert len(hypotheses) == 3
# And not detection3
assert detection3 not in {hypothesis.measurement
for hypothesis in hypotheses}
# There is a missed detection hypothesis
assert any(not hypothesis.measurement for hypothesis in hypotheses)
# Each hypothesis has a distance attribute
assert all(hypothesis.distance >= 0 for hypothesis in hypotheses)
# The hypotheses are sorted correctly
assert min(hypotheses, key=attrgetter('distance')) is hypotheses[0]
def test_distance_include_all(predictor, updater):
timestamp = datetime.datetime.now()
track = Track([GaussianState(np.array([[0]]), np.array([[1]]), timestamp)])
detection1 = Detection(np.array([[2]]))
detection2 = Detection(np.array([[3]]))
detection3 = Detection(np.array([[10]]))
detections = {detection1, detection2, detection3}
measure = measures.Mahalanobis()
hypothesiser = DistanceHypothesiser(
predictor, updater, measure=measure, missed_distance=1,
include_all=True)
hypotheses = hypothesiser.hypothesise(track, detections, timestamp)
# There are 4 hypotheses - Detections and Missed Detection
assert len(hypotheses) == 4
# detection3 is beyond missed distance and largest distance (last
# hypothesis in list)
last_hypothesis = hypotheses[-1]
assert last_hypothesis.measurement is detection3
assert last_hypothesis.distance > hypothesiser.missed_distance
| [
"numpy.array",
"operator.attrgetter",
"datetime.datetime.now"
] | [((338, 361), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (359, 361), False, 'import datetime\n'), ((1512, 1535), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1533, 1535), False, 'import datetime\n'), ((469, 484), 'numpy.array', 'np.array', (['[[2]]'], {}), '([[2]])\n', (477, 484), True, 'import numpy as np\n'), ((513, 528), 'numpy.array', 'np.array', (['[[3]]'], {}), '([[3]])\n', (521, 528), True, 'import numpy as np\n'), ((557, 573), 'numpy.array', 'np.array', (['[[10]]'], {}), '([[10]])\n', (565, 573), True, 'import numpy as np\n'), ((1643, 1658), 'numpy.array', 'np.array', (['[[2]]'], {}), '([[2]])\n', (1651, 1658), True, 'import numpy as np\n'), ((1687, 1702), 'numpy.array', 'np.array', (['[[3]]'], {}), '([[3]])\n', (1695, 1702), True, 'import numpy as np\n'), ((1731, 1747), 'numpy.array', 'np.array', (['[[10]]'], {}), '([[10]])\n', (1739, 1747), True, 'import numpy as np\n'), ((395, 410), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (403, 410), True, 'import numpy as np\n'), ((412, 427), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (420, 427), True, 'import numpy as np\n'), ((1401, 1423), 'operator.attrgetter', 'attrgetter', (['"""distance"""'], {}), "('distance')\n", (1411, 1423), False, 'from operator import attrgetter\n'), ((1569, 1584), 'numpy.array', 'np.array', (['[[0]]'], {}), '([[0]])\n', (1577, 1584), True, 'import numpy as np\n'), ((1586, 1601), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (1594, 1601), True, 'import numpy as np\n')] |
# Action policy module
# Constructs action probability distribution used by agent to sample action and calculate log_prob, entropy, etc.
from gym import spaces
from slm_lab.env.wrapper import LazyFrames
from slm_lab.lib import distribution, logger, math_util, util
from torch import distributions
import numpy as np
import pydash as ps
import torch
logger = logger.get_logger(__name__)
# register custom distributions
setattr(distributions, 'Argmax', distribution.Argmax)
setattr(distributions, 'GumbelSoftmax', distribution.GumbelSoftmax)
setattr(distributions, 'MultiCategorical', distribution.MultiCategorical)
# probability distributions constraints for different action types; the first in the list is the default
ACTION_PDS = {
'continuous': ['Normal', 'Beta', 'Gumbel', 'LogNormal'],
'multi_continuous': ['MultivariateNormal'],
'discrete': ['Categorical', 'Argmax', 'GumbelSoftmax'],
'multi_discrete': ['MultiCategorical'],
'multi_binary': ['Bernoulli'],
}
def get_action_type(action_space):
'''Method to get the action type to choose prob. dist. to sample actions from NN logits output'''
if isinstance(action_space, spaces.Box):
shape = action_space.shape
assert len(shape) == 1
if shape[0] == 1:
return 'continuous'
else:
return 'multi_continuous'
elif isinstance(action_space, spaces.Discrete):
return 'discrete'
elif isinstance(action_space, spaces.MultiDiscrete):
return 'multi_discrete'
elif isinstance(action_space, spaces.MultiBinary):
return 'multi_binary'
else:
raise NotImplementedError
# action_policy base methods
def get_action_pd_cls(action_pdtype, action_type):
'''
Verify and get the action prob. distribution class for construction
Called by body at init to set its own ActionPD
'''
pdtypes = ACTION_PDS[action_type]
assert action_pdtype in pdtypes, f'Pdtype {action_pdtype} is not compatible/supported with action_type {action_type}. Options are: {pdtypes}'
ActionPD = getattr(distributions, action_pdtype)
return ActionPD
def guard_tensor(state, body):
'''Guard-cast tensor before being input to network'''
if isinstance(state, LazyFrames):
state = state.__array__() # realize data
state = torch.from_numpy(state.astype(np.float32))
if not body.env.is_venv or util.in_eval_lab_modes():
# singleton state, unsqueeze as minibatch for net input
state = state.unsqueeze(dim=0)
return state
def calc_pdparam(state, algorithm, body):
'''
Prepare the state and run algorithm.calc_pdparam to get pdparam for action_pd
@param tensor:state For pdparam = net(state)
@param algorithm The algorithm containing self.net
@param body Body which links algorithm to the env which the action is for
@returns tensor:pdparam
@example
pdparam = calc_pdparam(state, algorithm, body)
action_pd = ActionPD(logits=pdparam) # e.g. ActionPD is Categorical
action = action_pd.sample()
'''
if not torch.is_tensor(state): # dont need to cast from numpy
state = guard_tensor(state, body)
state = state.to(algorithm.net.device)
pdparam = algorithm.calc_pdparam(state)
return pdparam
def init_action_pd(ActionPD, pdparam):
'''
Initialize the action_pd for discrete or continuous actions:
- discrete: action_pd = ActionPD(logits)
- continuous: action_pd = ActionPD(loc, scale)
'''
args = ActionPD.arg_constraints
if 'logits' in args: # discrete
# for relaxed discrete dist. with reparametrizable discrete actions
pd_kwargs = {'temperature': torch.tensor(1.0)} if hasattr(ActionPD, 'temperature') else {}
action_pd = ActionPD(logits=pdparam, **pd_kwargs)
else: # continuous, args = loc and scale
if isinstance(pdparam, list): # split output
loc, scale = pdparam
else:
loc, scale = pdparam.transpose(0, 1)
# scale (stdev) must be > 0, log-clamp-exp
scale = torch.clamp(scale, min=-20, max=2).exp()
if 'covariance_matrix' in args: # split output
# construct covars from a batched scale tensor
covars = torch.diag_embed(scale)
action_pd = ActionPD(loc=loc, covariance_matrix=covars)
else:
action_pd = ActionPD(loc=loc, scale=scale)
return action_pd
def sample_action(ActionPD, pdparam):
'''
Convenience method to sample action(s) from action_pd = ActionPD(pdparam)
Works with batched pdparam too
@returns tensor:action Sampled action(s)
@example
# policy contains:
pdparam = calc_pdparam(state, algorithm, body)
action = sample_action(body.ActionPD, pdparam)
'''
action_pd = init_action_pd(ActionPD, pdparam)
action = action_pd.sample()
return action
# action_policy used by agent
def default(state, algorithm, body):
'''Plain policy by direct sampling from a default action probability defined by body.ActionPD'''
pdparam = calc_pdparam(state, algorithm, body)
action = sample_action(body.ActionPD, pdparam)
return action
def random(state, algorithm, body):
'''Random action using gym.action_space.sample(), with the same format as default()'''
if body.env.is_venv and not util.in_eval_lab_modes():
_action = [body.action_space.sample() for _ in range(body.env.num_envs)]
else:
_action = [body.action_space.sample()]
action = torch.tensor(_action)
return action
def epsilon_greedy(state, algorithm, body):
'''Epsilon-greedy policy: with probability epsilon, do random action, otherwise do default sampling.'''
epsilon = body.explore_var
if epsilon > np.random.rand():
return random(state, algorithm, body)
else:
return default(state, algorithm, body)
def boltzmann(state, algorithm, body):
'''
Boltzmann policy: adjust pdparam with temperature tau; the higher the more randomness/noise in action.
'''
tau = body.explore_var
pdparam = calc_pdparam(state, algorithm, body)
pdparam /= tau
action = sample_action(body.ActionPD, pdparam)
return action
# multi-body/multi-env action_policy used by agent
# TODO rework
def multi_default(states, algorithm, body_list, pdparam):
'''
Apply default policy body-wise
Note, for efficiency, do a single forward pass to calculate pdparam, then call this policy like:
@example
pdparam = self.calc_pdparam(state)
action_a = self.action_policy(pdparam, self, body_list)
'''
# assert pdparam has been chunked
assert pdparam.dim() > 1 and len(pdparam) == len(body_list), f'pdparam shape: {pdparam.shape}, bodies: {len(body_list)}'
action_list = []
for idx, sub_pdparam in enumerate(pdparam):
body = body_list[idx]
guard_tensor(states[idx], body) # for consistency with singleton inner logic
action = sample_action(body.ActionPD, sub_pdparam)
action_list.append(action)
action_a = torch.tensor(action_list, device=algorithm.net.device).unsqueeze(dim=1)
return action_a
def multi_random(states, algorithm, body_list, pdparam):
'''Apply random policy body-wise.'''
action_list = []
for idx, body in body_list:
action = random(states[idx], algorithm, body)
action_list.append(action)
action_a = torch.tensor(action_list, device=algorithm.net.device).unsqueeze(dim=1)
return action_a
def multi_epsilon_greedy(states, algorithm, body_list, pdparam):
'''Apply epsilon-greedy policy body-wise'''
assert len(pdparam) > 1 and len(pdparam) == len(body_list), f'pdparam shape: {pdparam.shape}, bodies: {len(body_list)}'
action_list = []
for idx, sub_pdparam in enumerate(pdparam):
body = body_list[idx]
epsilon = body.explore_var
if epsilon > np.random.rand():
action = random(states[idx], algorithm, body)
else:
guard_tensor(states[idx], body) # for consistency with singleton inner logic
action = sample_action(body.ActionPD, sub_pdparam)
action_list.append(action)
action_a = torch.tensor(action_list, device=algorithm.net.device).unsqueeze(dim=1)
return action_a
def multi_boltzmann(states, algorithm, body_list, pdparam):
'''Apply Boltzmann policy body-wise'''
assert len(pdparam) > 1 and len(pdparam) == len(body_list), f'pdparam shape: {pdparam.shape}, bodies: {len(body_list)}'
action_list = []
for idx, sub_pdparam in enumerate(pdparam):
body = body_list[idx]
guard_tensor(states[idx], body) # for consistency with singleton inner logic
tau = body.explore_var
sub_pdparam /= tau
action = sample_action(body.ActionPD, sub_pdparam)
action_list.append(action)
action_a = torch.tensor(action_list, device=algorithm.net.device).unsqueeze(dim=1)
return action_a
# action policy update methods
class VarScheduler:
'''
Variable scheduler for decaying variables such as explore_var (epsilon, tau) and entropy
e.g. spec
"explore_var_spec": {
"name": "linear_decay",
"start_val": 1.0,
"end_val": 0.1,
"start_step": 0,
"end_step": 800,
},
'''
def __init__(self, var_decay_spec=None):
self._updater_name = 'no_decay' if var_decay_spec is None else var_decay_spec['name']
self._updater = getattr(math_util, self._updater_name)
util.set_attr(self, dict(
start_val=np.nan,
))
util.set_attr(self, var_decay_spec, [
'start_val',
'end_val',
'start_step',
'end_step',
])
if not getattr(self, 'end_val', None):
self.end_val = self.start_val
def update(self, algorithm, clock):
'''Get an updated value for var'''
if (util.in_eval_lab_modes()) or self._updater_name == 'no_decay':
return self.end_val
step = clock.get()
val = self._updater(self.start_val, self.end_val, self.start_step, self.end_step, step)
return val
| [
"slm_lab.lib.util.in_eval_lab_modes",
"slm_lab.lib.logger.get_logger",
"torch.clamp",
"numpy.random.rand",
"torch.diag_embed",
"torch.is_tensor",
"slm_lab.lib.util.set_attr",
"torch.tensor"
] | [((359, 386), 'slm_lab.lib.logger.get_logger', 'logger.get_logger', (['__name__'], {}), '(__name__)\n', (376, 386), False, 'from slm_lab.lib import distribution, logger, math_util, util\n'), ((5502, 5523), 'torch.tensor', 'torch.tensor', (['_action'], {}), '(_action)\n', (5514, 5523), False, 'import torch\n'), ((2386, 2410), 'slm_lab.lib.util.in_eval_lab_modes', 'util.in_eval_lab_modes', ([], {}), '()\n', (2408, 2410), False, 'from slm_lab.lib import distribution, logger, math_util, util\n'), ((3065, 3087), 'torch.is_tensor', 'torch.is_tensor', (['state'], {}), '(state)\n', (3080, 3087), False, 'import torch\n'), ((5744, 5760), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5758, 5760), True, 'import numpy as np\n'), ((9565, 9656), 'slm_lab.lib.util.set_attr', 'util.set_attr', (['self', 'var_decay_spec', "['start_val', 'end_val', 'start_step', 'end_step']"], {}), "(self, var_decay_spec, ['start_val', 'end_val', 'start_step',\n 'end_step'])\n", (9578, 9656), False, 'from slm_lab.lib import distribution, logger, math_util, util\n'), ((4237, 4260), 'torch.diag_embed', 'torch.diag_embed', (['scale'], {}), '(scale)\n', (4253, 4260), False, 'import torch\n'), ((5325, 5349), 'slm_lab.lib.util.in_eval_lab_modes', 'util.in_eval_lab_modes', ([], {}), '()\n', (5347, 5349), False, 'from slm_lab.lib import distribution, logger, math_util, util\n'), ((7043, 7097), 'torch.tensor', 'torch.tensor', (['action_list'], {'device': 'algorithm.net.device'}), '(action_list, device=algorithm.net.device)\n', (7055, 7097), False, 'import torch\n'), ((7392, 7446), 'torch.tensor', 'torch.tensor', (['action_list'], {'device': 'algorithm.net.device'}), '(action_list, device=algorithm.net.device)\n', (7404, 7446), False, 'import torch\n'), ((7878, 7894), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (7892, 7894), True, 'import numpy as np\n'), ((8171, 8225), 'torch.tensor', 'torch.tensor', (['action_list'], {'device': 'algorithm.net.device'}), '(action_list, device=algorithm.net.device)\n', (8183, 8225), False, 'import torch\n'), ((8844, 8898), 'torch.tensor', 'torch.tensor', (['action_list'], {'device': 'algorithm.net.device'}), '(action_list, device=algorithm.net.device)\n', (8856, 8898), False, 'import torch\n'), ((9897, 9921), 'slm_lab.lib.util.in_eval_lab_modes', 'util.in_eval_lab_modes', ([], {}), '()\n', (9919, 9921), False, 'from slm_lab.lib import distribution, logger, math_util, util\n'), ((3676, 3693), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (3688, 3693), False, 'import torch\n'), ((4060, 4094), 'torch.clamp', 'torch.clamp', (['scale'], {'min': '(-20)', 'max': '(2)'}), '(scale, min=-20, max=2)\n', (4071, 4094), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
@author: Gualandi
"""
import numpy as np
import networkx as nx
from math import sqrt
from time import sleep
from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set
from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals
# Residenza Collegiali a Pavia
Rs = [(45.1882789,9.1600456, '<NAME>o'),(45.2070857,9.1382623, 'Green Campus'),
(45.1961107,9.1395709, 'Golgi'),(45.1851618,9.1506323, 'Senatore'),
(45.1806049,9.1691651, '<NAME>'),(45.1857651,9.1473637, 'CSA'),
(45.1802511,9.1591663, 'Borromeo'),(45.1877192,9.1578934, 'Cairoli'),
(45.1870975,9.1588276, 'Castiglioni'),(45.1871301,9.1435067, 'Santa Caterina'),
(45.1863927,9.15947, 'Ghislieri'),(45.2007148,9.1325475, 'Nuovo'),
(45.1787292,9.1635482, 'Cardano'),(45.1864928,9.1560687, 'Fraccaro'),
(45.1989668,9.1775168, 'Griziotti'),(45.1838819,9.161318, 'Spallanzani'),
(45.1823523,9.1454315, 'Valla'),(45.2007816,9.1341354, 'Volta'),
(45.2070857,9.1382623, 'Residence Campus'),(45.2070857,9.1382623, 'Residenza Biomedica')]
# INSTANCES TAKE FROM THE TSPLIB:
# http://elib.zib.de/pub/mp-testdata/tsp/tsplib/tsp/
ULYSSES = [(38.24, 20.42), (39.57, 26.15), (40.56, 25.32), (36.26, 23.12),
(33.48, 10.54), (37.56, 12.19), (38.42, 13.11), (37.52, 20.44),
(41.23, 9.10), (41.17, 13.05), (36.08, -5.21), (38.47, 15.13),
(38.15, 15.35), (37.51, 15.17), (35.49, 14.32), (39.36, 19.56)]
BAVIERA = [(1150.0, 1760.0), (630.0, 1660.0), (40.0, 2090.0), (750.0, 1100.0),
(1030.0, 2070.0), (1650.0, 650.0), (1490.0, 1630.0), (790.0, 2260.0),
(710.0, 1310.0), (840.0, 550.0), (1170.0, 2300.0), (970.0, 1340.0),
(510.0, 700.0), (750.0, 900.0), (1280.0, 1200.0), (230.0, 590.0),
(460.0, 860.0), (1040.0, 950.0), (590.0, 1390.0), (830.0, 1770.0),
(490.0, 500.0), (1840.0, 1240.0), (1260.0, 1500.0), (1280.0, 790.0),
(490.0, 2130.0), (1460.0, 1420.0), (1260.0, 1910.0), (360.0, 1980.0),
(750.0, 2030.0)]
def PlotTour(Ps, Ls, values):
# Report solution value
import pylab as pl
from matplotlib import collections as mc
lines = [[Ps[i], Ps[j]] for i,j in Ls]
lc = mc.LineCollection(lines, linewidths=[1.5
if x > 0.501 else 1 for x in values],
colors=['blue' if x > 0.501 else 'orange' for x in values])
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.scatter([i for i,j in Ps], [j for i,j in Ps],
s=20, alpha=0.8, color='red')
ax.autoscale()
ax.margins(0.1)
ax.set_aspect('equal', 'box')
# pl.savefig('tspFrac.pdf')
pl.show()
def CostMatrix(Ls):
n = len(Ls)
C = 100000*np.ones((n,n))
for i, (a,b) in enumerate(Ls):
for j, (c,d) in enumerate(Ls[i+1:]):
C[i, i+j+1] = sqrt((a-c)**2 + (b-d)**2)
C[i+j+1, i] = C[i, i+j+1]
return C
def RandomTSP(n):
from numpy import random
random.seed(13)
return [(x,y) for x,y in zip(random.random(n), random.random(n))]
def BuildDiGraph(C):
# Build a directed graph out of the data
G = nx.DiGraph()
n,n = C.shape
for i in range(1,n+1):
for j in range(1,n+1):
if i != j:
G.add_edge(i, j, weight=C[i-1,j-1])
return G
def BuildGraph(C):
# Build a directed graph out of the data
G = nx.Graph()
n,n = C.shape
for i in range(1,n+1):
for j in range(1,n+1):
if i < j:
G.add_edge(i, j, weight=C[i-1,j-1])
return G
# Mixed Integer Programming Formulation
def TSP(G, TIME_LIMIT=600):
# Number of places
n = G.number_of_nodes()
# TODO: Implement the model of your choice
m = ConcreteModel()
# 1. Data and ranges
m.N = RangeSet(n)
m.A = Set(initialize=((i,j) for i,j in G.edges()), dimen=2)
# 2. Variables
# TODO: introduce only usefull variables (no arc, no variable)
m.x = Var(m.A, domain=NonNegativeReals, bounds=lambda m: (0,1))
# 3. Objective function
# Objective function of arc variables
m.obj = Objective(expr = sum(G[i][j]['weight']*m.x[i,j] for i,j in G.edges()))
# 4. Constraints
# Vincoli archi uscenti
m.outdegree = ConstraintList()
for i in m.N:
m.outdegree.add(expr = sum(m.x[v,w] for v,w in G.out_edges(i)) == 1)
# Vincoli archi entranti
m.indegree = ConstraintList()
for j in m.N:
m.indegree.add(expr = sum(m.x[v,w] for v,w in G.in_edges(j)) == 1)
# Arc constraint
m.arcs = ConstraintList()
for i,j in G.edges():
if i < j:
m.arcs.add( m.x[i,j] + m.x[j,i] <= 1 )
m.subtour = ConstraintList()
solver = SolverFactory('gurobi')
# 5. Solution
# Solve the model
SOLVER_NAME = 'gurobi'
# SOLVER_NAME = 'glpk'
solver = SolverFactory(SOLVER_NAME)
if SOLVER_NAME == 'glpk':
solver.options['tmlim'] = TIME_LIMIT
elif SOLVER_NAME == 'gurobi':
solver.options['TimeLimit'] = TIME_LIMIT
it = 0
Cold = []
while it <= 100:
it += 1
sol = solver.solve(m, tee=False, load_solutions=False)
# Get a JSON representation of the solution
sol_json = sol.json_repn()
# Check solution status
if sol_json['Solver'][0]['Status'] != 'ok':
return None, []
# Load the solution
m.solutions.load_from(sol)
print(it, m.obj())
selected = []
values = []
for i in m.N:
for j in m.N:
if i < j:
if m.x[i,j]() > 0 or m.x[j,i]() > 0:
selected.append( (i-1, j-1) )
values.append(m.x[i,j]()+m.x[j,i]())
PlotTour(Ls, selected, values)
# Build graph
H = nx.Graph()
for i in m.N:
for j in m.N:
if i < j:
if m.x[i,j]() > 0.00001 or m.x[j,i]() > 0.00001:
H.add_edge(i,j, weight=m.x[i,j])
Cs = nx.cycle_basis(H)
if Cs != Cold:
Cold = Cs
for cycle in Cs:
Es = []
for i in cycle:
for j in G.nodes():
if j not in cycle:
Es.append( (i,j) )
if len(Es) > 0:
m.subtour.add( sum(m.x[i,j] for i,j in Es ) >= 1 )
else:
break
selected = []
values = []
for i in m.N:
for j in m.N:
if i < j:
if m.x[i,j]() > 0 or m.x[j,i]() > 0:
selected.append( (i-1, j-1) )
values.append(m.x[i,j]()+m.x[j,i]())
PlotTour(Ls, selected, values)
return m.obj(), selected
# Mixed Integer Programming Formulation
def TSPSYM(G, TIME_LIMIT=600):
# Number of places
n = G.number_of_nodes()
# TODO: Implement the model of your choice
m = ConcreteModel()
# 1. Data and ranges
m.N = RangeSet(n)
m.A = Set(initialize=((i,j) for i,j in G.edges()), dimen=2)
# 2. Variables
# TODO: introduce only usefull variables (no arc, no variable)
m.x = Var(m.A, domain=NonNegativeReals, bounds=lambda m: (0,1))
# 3. Objective function
# Objective function of arc variables
m.obj = Objective(expr = sum(G[i][j]['weight']*m.x[i,j] for i,j in m.A))
# 4. Constraints
# Vincoli archi uscenti
m.degree = ConstraintList()
for i in m.N:
Es = []
for v,w in G.edges(i):
if v > w:
v, w = w, v
Es.append( (v,w) )
m.degree.add(expr = sum(m.x[v,w] for v, w in Es) == 2)
m.subtour = ConstraintList()
solver = SolverFactory('gurobi')
# 5. Solution
# Solve the model
SOLVER_NAME = 'gurobi'
# SOLVER_NAME = 'glpk'
solver = SolverFactory(SOLVER_NAME)
if SOLVER_NAME == 'glpk':
solver.options['tmlim'] = TIME_LIMIT
elif SOLVER_NAME == 'gurobi':
solver.options['TimeLimit'] = TIME_LIMIT
it = 0
Cold = []
while it <= 100:
it += 1
sol = solver.solve(m, tee=False, load_solutions=False)
# Get a JSON representation of the solution
sol_json = sol.json_repn()
# Check solution status
if sol_json['Solver'][0]['Status'] != 'ok':
return None, []
# Load the solution
m.solutions.load_from(sol)
selected = []
values = []
for i, j in m.A:
if m.x[i,j]() > 0:
selected.append( (i-1, j-1) )
values.append(m.x[i,j]())
PlotTour(Ls, selected, values)
# Build graph
H = nx.Graph()
for i,j in m.A:
H.add_edge(i,j, weight=m.x[i,j]())
# Cs = nx.connected_components(H)
# Cs = list(Cs)
# Cs = nx.cycle_basis(H)
cut_value, S = nx.stoer_wagner(H)
print(it, m.obj(), sum(values))
flag = True
if cut_value >= 2:
print(cut_value)
# Separate blossom
H = nx.Graph()
for i,j in m.A:
if m.x[i,j]() > 0.1 and m.x[i,j]() < 0.9:
if i < j:
H.add_edge(i, j)
else:
H.add_edge(j, i)
selected = []
values = []
for i,j in m.A:
selected.append( (i-1, j-1) )
values.append(m.x[i,j]())
Cs = nx.cycle_basis(H)
for cycle in Cs:
NS = len(cycle)
if NS == 3:
S = set()
for i in range(NS):
if cycle[i-1] < cycle[i]:
S.add( (cycle[i-1], cycle[i]) )
else:
S.add( (cycle[i], cycle[i-1]) )
for i in cycle:
for j in G.neighbors(i):
if (i,j) not in S:
v,w = i,j
if i > j:
v,w = j,i
if m.x[v,w]() > 0.9:
S.add( (v,w) )
if False and len(S) > NS+2:
m.subtour.add( sum(m.x[i,j] for i,j in S ) <= NS+1 )
flag = False
print('added', S)
else:
Es = []
for i in S[0]:
for j in S[1]:
if i < j:
Es.append( (i,j) )
else:
Es.append( (j,i) )
if len(Es) > 0:
m.subtour.add( sum(m.x[i,j] for i,j in Es ) >= 2 )
flag = False
if flag:
break
# sleep(1)
# if Cs == Cold:
# break
# Cold = Cs
# for cycle in Cs:
# Es = []
# for i,j in m.A:
# if (i in cycle and j not in cycle) or (i not in cycle and j in cycle):
# if i < j:
# Es.append( (i,j) )
# else:
# Es.append( (j,i) )
# Es.append( (i,j) )
# if len(Es) > 0:
# m.subtour.add( sum(m.x[i,j] for i,j in Es ) >= 2 )
selected = []
values = []
for i,j in m.A:
if m.x[i,j]() > 0:
selected.append( (i-1, j-1) )
values.append(m.x[i,j]())
print(values)
PlotTour(Ls, selected, values)
return m.obj(), selected
# -----------------------------------------------
# MAIN function
# -----------------------------------------------
if __name__ == "__main__":
Test = 2
# Compute Cost Matrix
if Test == 0:
Ls = [(b,a) for a,b,_ in Rs]
if Test == 1:
Ls = ULYSSES
if Test == 2:
Ls = BAVIERA
if Test == 3:
N = 100
Ls = RandomTSP(N)
# Compute cost matrix
C = CostMatrix(Ls)
# Solve problem
if True:
G = BuildGraph(C)
z_lp, tour = TSPSYM(G)
if False:
G = BuildDiGraph(C)
z_lp, tour = TSP(G) | [
"matplotlib.collections.LineCollection",
"pylab.show",
"numpy.random.seed",
"pyomo.environ.SolverFactory",
"math.sqrt",
"pyomo.environ.RangeSet",
"pyomo.environ.Var",
"networkx.stoer_wagner",
"numpy.ones",
"pylab.subplots",
"networkx.cycle_basis",
"networkx.Graph",
"numpy.random.random",
"... | [((2309, 2455), 'matplotlib.collections.LineCollection', 'mc.LineCollection', (['lines'], {'linewidths': '[(1.5 if x > 0.501 else 1) for x in values]', 'colors': "[('blue' if x > 0.501 else 'orange') for x in values]"}), "(lines, linewidths=[(1.5 if x > 0.501 else 1) for x in\n values], colors=[('blue' if x > 0.501 else 'orange') for x in values])\n", (2326, 2455), True, 'from matplotlib import collections as mc\n'), ((2540, 2553), 'pylab.subplots', 'pl.subplots', ([], {}), '()\n', (2551, 2553), True, 'import pylab as pl\n'), ((2795, 2804), 'pylab.show', 'pl.show', ([], {}), '()\n', (2802, 2804), True, 'import pylab as pl\n'), ((3127, 3142), 'numpy.random.seed', 'random.seed', (['(13)'], {}), '(13)\n', (3138, 3142), False, 'from numpy import random\n'), ((3288, 3300), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (3298, 3300), True, 'import networkx as nx\n'), ((3545, 3555), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (3553, 3555), True, 'import networkx as nx\n'), ((3906, 3921), 'pyomo.environ.ConcreteModel', 'ConcreteModel', ([], {}), '()\n', (3919, 3921), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((3962, 3973), 'pyomo.environ.RangeSet', 'RangeSet', (['n'], {}), '(n)\n', (3970, 3973), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((4149, 4207), 'pyomo.environ.Var', 'Var', (['m.A'], {'domain': 'NonNegativeReals', 'bounds': '(lambda m: (0, 1))'}), '(m.A, domain=NonNegativeReals, bounds=lambda m: (0, 1))\n', (4152, 4207), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((4434, 4450), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (4448, 4450), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((4593, 4609), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (4607, 4609), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((4739, 4755), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (4753, 4755), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((4896, 4912), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (4910, 4912), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((4931, 4954), 'pyomo.environ.SolverFactory', 'SolverFactory', (['"""gurobi"""'], {}), "('gurobi')\n", (4944, 4954), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((5076, 5102), 'pyomo.environ.SolverFactory', 'SolverFactory', (['SOLVER_NAME'], {}), '(SOLVER_NAME)\n', (5089, 5102), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((7340, 7355), 'pyomo.environ.ConcreteModel', 'ConcreteModel', ([], {}), '()\n', (7353, 7355), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((7396, 7407), 'pyomo.environ.RangeSet', 'RangeSet', (['n'], {}), '(n)\n', (7404, 7407), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((7583, 7641), 'pyomo.environ.Var', 'Var', (['m.A'], {'domain': 'NonNegativeReals', 'bounds': '(lambda m: (0, 1))'}), '(m.A, domain=NonNegativeReals, bounds=lambda m: (0, 1))\n', (7586, 7641), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((7859, 7875), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (7873, 7875), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((8102, 8118), 'pyomo.environ.ConstraintList', 'ConstraintList', ([], {}), '()\n', (8116, 8118), False, 'from pyomo.environ import maximize, Binary, RangeSet, PositiveReals, ConstraintList, NonNegativeReals\n'), ((8137, 8160), 'pyomo.environ.SolverFactory', 'SolverFactory', (['"""gurobi"""'], {}), "('gurobi')\n", (8150, 8160), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((8282, 8308), 'pyomo.environ.SolverFactory', 'SolverFactory', (['SOLVER_NAME'], {}), '(SOLVER_NAME)\n', (8295, 8308), False, 'from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory, Set\n'), ((2858, 2873), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (2865, 2873), True, 'import numpy as np\n'), ((6117, 6127), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (6125, 6127), True, 'import networkx as nx\n'), ((6363, 6380), 'networkx.cycle_basis', 'nx.cycle_basis', (['H'], {}), '(H)\n', (6377, 6380), True, 'import networkx as nx\n'), ((9184, 9194), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (9192, 9194), True, 'import networkx as nx\n'), ((9419, 9437), 'networkx.stoer_wagner', 'nx.stoer_wagner', (['H'], {}), '(H)\n', (9434, 9437), True, 'import networkx as nx\n'), ((2979, 3012), 'math.sqrt', 'sqrt', (['((a - c) ** 2 + (b - d) ** 2)'], {}), '((a - c) ** 2 + (b - d) ** 2)\n', (2983, 3012), False, 'from math import sqrt\n'), ((9602, 9612), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (9610, 9612), True, 'import networkx as nx\n'), ((10045, 10062), 'networkx.cycle_basis', 'nx.cycle_basis', (['H'], {}), '(H)\n', (10059, 10062), True, 'import networkx as nx\n'), ((3176, 3192), 'numpy.random.random', 'random.random', (['n'], {}), '(n)\n', (3189, 3192), False, 'from numpy import random\n'), ((3194, 3210), 'numpy.random.random', 'random.random', (['n'], {}), '(n)\n', (3207, 3210), False, 'from numpy import random\n')] |
# multithreaded code here
# put KLD computations in single function
import numpy as np
import multiprocessing as mp
from multiprocessing import Process, Manager
import ray
import time
from .models import BnnBase, BnnBinaryClassifier
from .projections import CovarianceProjection
from .logutils import TqdmLoggingHandler
import logging
logger = logging.getLogger(__name__)
logger.addHandler(TqdmLoggingHandler())
#############################################
# Using multithreading #
#############################################
# From https://research.wmz.ninja/articles/2018/03/on-sharing-large-arrays-when-using-pythons-multiprocessing.html
#############################################
# Using ray #
#############################################
@ray.remote
def KLD_ray(M_B_c, Lambda, j, nullify, exact):
p = Lambda.shape[0]
if nullify is not None:
j = np.array(np.unique(np.concatenate(([j], nullify)), axis=0))
m = M_B_c[j]
Lambda_red = np.delete(Lambda, j, axis=0)[:,j]
alpha = np.matmul(
Lambda_red.T,
np.linalg.lstsq(
np.delete(np.delete(Lambda, j, axis=0), j, axis=1),
Lambda_red,
rcond=None)[0])
# Approximation to the full KLD (equation S6 in AoAs supplemental)
if nullify is None:
kld = 0.5 * m**2.0 * alpha
else:
kld = 0.5 * np.matmul(np.matmul(m.T, alpha), m)
# Additional terms in the full KLD calculation (equation 9 in AoAS paper)
if exact:
sigma_lambda_product = np.matmul(
np.delete(np.delete(V_B[c], j, axis=0), j, axis=1),
np.delete(np.delete(Lambda, j, axis=0), j, axis=1))
kld += 0.5 * (
- np.log(np.linalg.det(sigma_lambda_product) + 1e-9)
+ np.trace(sigma_lambda_product)
+ 1.0 - p)
return kld
def RATE_ray(X, M_F, V_F, projection=CovarianceProjection(), nullify=None,
exact_KLD=False, jitter=1e-9, return_time=False, return_KLDs=False,
n_jobs=1):
if not (X.shape[0] == M_F.shape[1] == V_F.shape[1] == V_F.shape[2]):
raise ValueError("Inconsistent number of examples across X and logit posterior")
if M_F.shape[0] != V_F.shape[0]:
raise ValueError("Inconsistent number of classes between logit posterior mean and covariance")
# logger.info("Calculating RATE (using ray) values for {} classes, {} examples and {} variables and {} jobs".format(M_F.shape[0], X.shape[0], X.shape[1], n_jobs))
# logger.debug("Input shapes: X: {}, M_F: {}, V_F: {}".format(X.shape, M_F.shape, V_F.shape))
M_B, V_B = projection.esa_posterior(X, M_F, V_F)
C = M_F.shape[0]
p = X.shape[1]
J = np.arange(p)
if nullify is not None:
J = np.delete(J, nullify, axis=0)
KLDs = [np.zeros(J.shape[0]) for _ in range(C)]
ray.init(num_cpus=n_jobs)
start_time = time.time()
for c in range(C):
logger.info("Calculating RATE values for class {} of {}".format(c+1, C))
Lambda = np.linalg.pinv(V_B[c] + jitter*np.eye(V_B.shape[1]))
Lambda_id = ray.put(Lambda)
KLDs[c] = ray.get([KLD_ray.remote(M_B[c], Lambda_id, j, nullify, exact_KLD) for j in J])
ray.shutdown()
if (np.array(KLDs) < 0.0).any():
logger.warning("Some KLD values are negative - try a larger jitter value (current value: {})".format(jitter))
out = [klds / np.sum(klds) for klds in KLDs]
rate_time = time.time() - start_time
logger.info("The RATE calculation took {} seconds".format(round(rate_time, 3)))
if C==1:
out = out[0]
if return_KLDs:
out = [out, KLDs]
if return_time:
out = [out, rate_time]
return out | [
"ray.init",
"numpy.trace",
"numpy.sum",
"numpy.concatenate",
"numpy.zeros",
"time.time",
"ray.put",
"ray.shutdown",
"numpy.arange",
"numpy.matmul",
"numpy.array",
"numpy.linalg.det",
"numpy.eye",
"numpy.delete",
"logging.getLogger"
] | [((348, 375), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (365, 375), False, 'import logging\n'), ((2504, 2516), 'numpy.arange', 'np.arange', (['p'], {}), '(p)\n', (2513, 2516), True, 'import numpy as np\n'), ((2629, 2654), 'ray.init', 'ray.init', ([], {'num_cpus': 'n_jobs'}), '(num_cpus=n_jobs)\n', (2637, 2654), False, 'import ray\n'), ((2670, 2681), 'time.time', 'time.time', ([], {}), '()\n', (2679, 2681), False, 'import time\n'), ((2963, 2977), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (2975, 2977), False, 'import ray\n'), ((978, 1006), 'numpy.delete', 'np.delete', (['Lambda', 'j'], {'axis': '(0)'}), '(Lambda, j, axis=0)\n', (987, 1006), True, 'import numpy as np\n'), ((2548, 2577), 'numpy.delete', 'np.delete', (['J', 'nullify'], {'axis': '(0)'}), '(J, nullify, axis=0)\n', (2557, 2577), True, 'import numpy as np\n'), ((2588, 2608), 'numpy.zeros', 'np.zeros', (['J.shape[0]'], {}), '(J.shape[0])\n', (2596, 2608), True, 'import numpy as np\n'), ((2855, 2870), 'ray.put', 'ray.put', (['Lambda'], {}), '(Lambda)\n', (2862, 2870), False, 'import ray\n'), ((3234, 3245), 'time.time', 'time.time', ([], {}), '()\n', (3243, 3245), False, 'import time\n'), ((3190, 3202), 'numpy.sum', 'np.sum', (['klds'], {}), '(klds)\n', (3196, 3202), True, 'import numpy as np\n'), ((909, 939), 'numpy.concatenate', 'np.concatenate', (['([j], nullify)'], {}), '(([j], nullify))\n', (923, 939), True, 'import numpy as np\n'), ((1308, 1329), 'numpy.matmul', 'np.matmul', (['m.T', 'alpha'], {}), '(m.T, alpha)\n', (1317, 1329), True, 'import numpy as np\n'), ((1473, 1501), 'numpy.delete', 'np.delete', (['V_B[c]', 'j'], {'axis': '(0)'}), '(V_B[c], j, axis=0)\n', (1482, 1501), True, 'import numpy as np\n'), ((1531, 1559), 'numpy.delete', 'np.delete', (['Lambda', 'j'], {'axis': '(0)'}), '(Lambda, j, axis=0)\n', (1540, 1559), True, 'import numpy as np\n'), ((2984, 2998), 'numpy.array', 'np.array', (['KLDs'], {}), '(KLDs)\n', (2992, 2998), True, 'import numpy as np\n'), ((1082, 1110), 'numpy.delete', 'np.delete', (['Lambda', 'j'], {'axis': '(0)'}), '(Lambda, j, axis=0)\n', (1091, 1110), True, 'import numpy as np\n'), ((2819, 2839), 'numpy.eye', 'np.eye', (['V_B.shape[1]'], {}), '(V_B.shape[1])\n', (2825, 2839), True, 'import numpy as np\n'), ((1652, 1682), 'numpy.trace', 'np.trace', (['sigma_lambda_product'], {}), '(sigma_lambda_product)\n', (1660, 1682), True, 'import numpy as np\n'), ((1603, 1638), 'numpy.linalg.det', 'np.linalg.det', (['sigma_lambda_product'], {}), '(sigma_lambda_product)\n', (1616, 1638), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#Imports
import sys
sys.path.append('../../python/')
#import NGC5533_functions-newmag as nf
import numpy as np
import matplotlib.pyplot as plt
#import scipy.optimize as opt
import lmfit as lm
import dataPython as dp
import scipy.interpolate as inter
import NGC5533_functions as nf
from datetime import datetime
import time
from ipywidgets import interactive, fixed, FloatSlider, HBox, Layout, Button, Label, Output, VBox
from IPython.display import display, clear_output
from IPython.display import Javascript
import scipy.stats as stats
import warnings
warnings.filterwarnings("ignore") #ignore warnings
# In[2]:
#import data files:
#TRACING:**************************************
#data points:
data = dp.getXYdata_wXYerr('../NGC_5005/traced_data/ngc5005_data.txt')
r_dat = np.asarray(data['xx'])
v_dat = np.asarray(data['yy'])
v_err0 = np.asarray(data['ex'])
v_err1 = np.asarray(data['ey'])
#v_err1=v_err1[:len(v_err1)-1]
#r_dat=r_dat[:len(r_dat)-1]
#v_dat=v_dat[:len(v_dat)-1]
#gas rotmod:
gas_rdata = dp.getXYZdata('../testing/aygas.dat') #rotmod_gas.dat
rgasr = gas_rdata['xx']
rgasv = gas_rdata['zz']
rgasv=np.asarray(rgasv)
rgasv_spline = inter.InterpolatedUnivariateSpline(rgasr,rgasv,k=5)
rgasv_fit = rgasv_spline(r_dat)
#make gas array same length as data points array ????? how can I fit without doing this?????
'''
rgasv=rgasv[:len(rgasv)-9]
rgasv=rgasv[0::68]
rgasr=rgasr[:len(rgasr)-9]
rgasr=rgasr[0::68]
'''
rgasv_fit=rgasv
#bulge rotmod
bulge_rdata = dp.getXYZdata('../testing/aybulge.dat')
rbulger = bulge_rdata['xx']
rbulgev = bulge_rdata['zz']
rbulgev=np.asarray(rbulgev)
#rbulger = [x - 1.15 for x in rbulger]
#rbulger=rbulger[:len(rbulger)-5]
#rbulger=rbulger[0::72]
#rbulgev=rbulgev[:len(rbulgev)-5]
#rbulgev=rbulgev[0::72]
rbulgev_spline = inter.InterpolatedUnivariateSpline(rbulger,rbulgev,k=5)
rbulgev_fit = rbulgev_spline(r_dat)
rbulgev_fit=rbulgev
#manually replacing "peak" in bulge to true peak
#not sure if this makes a difference
#rbulger[1] = .58 #.409 from trace
#rbulgev[1]=653.7
#disk rotmod:
disk_rdata = dp.getXYZdata('../testing/aydisk.dat')
rdiskr = disk_rdata['xx']
rdiskv = disk_rdata['zz']
rdiskv=np.asarray(rdiskv)
#rdiskv=rdiskv[:len(rdiskv)-5]
#rdiskv=rdiskv[0::72]
rdiskv_spline = inter.InterpolatedUnivariateSpline(rdiskr,rdiskv,k=5)
rdiskv_fit = rdiskv_spline(r_dat)
rdiskv_fit=rdiskv
#Halo datathief trace:
halo_dt = dp.getXYdata('../NGC_5005/datatheif_halo_spline.txt')
halo_dtr = halo_dt['xx']
halo_dtv = halo_dt['yy']
halo_dtv=np.asarray(halo_dtv)
#halo_dtv=halo_dtv[:len(halo_dtv)-5]
#halo_dtv=halo_dtv[0::6]
halo_dtv_spline = inter.InterpolatedUnivariateSpline(halo_dtr,halo_dtv,k=5)
halo_dtv_fit = halo_dtv_spline(r_dat)
#rval = np.linspace(0,11.2,19)
rval=r_dat
# In[3]:
# Fitting function, just prefactors for all the components
def g(r,GX,BX,DX,rc,rho00):
return np.sqrt((GX*rgasv_fit)**2
+ (BX*rbulgev_fit)**2
+ (DX*rdiskv_fit)**2
+ (nf.h_v(rval,rc,rho00))**2)
# In[4]:
v_err1=v_err1
weightdata=1/v_err1
# LMFit
#Setup
g_mod = lm.Model(g)
g_params = g_mod.make_params()
#Gas
g_params.add('GX', value=.956, min=.956) #Mass
#Bulge
g_params.add('BX', value=1, min=0) #Prefactor
#Disk
g_params.add('DX', value=1, min=0) #Prefactor
#Halo
g_params.add('rc', value=2.5, min=2.5,max=2.51) #Core radius (kpc)
g_params.add('rho00', value=1e+08, min=0) #Central density
#Do fit
g_fit = g_mod.fit(v_dat,g_params,r=r_dat,weights=weightdata)
# In[5]:
# Define for plotting
bestg = g_fit.best_fit
#delg = g_fit.eval_uncertainty()
print('Fit information for all-component fit:')
g_fit
# In[6]:
#smoothing --> creating a spline
#print(bestg)
#rval = np.arange(0,15,0.1)
#for total fit curve
#r_dat = r_dat[r_dat.argsort()]
r_dat_andzero = np.append([0],r_dat)
idx = np.arange(0,np.shape(r_dat_andzero)[0])
bestg = bestg[r_dat.argsort()]
#f_v_T = inter.InterpolatedUnivariateSpline(r_dat_andzero[idx%1==0], np.append([0],bestg)[idx%1==0], k=3)
#f_v_T_v = np.vectorize(f_v_T)
rgasv_spline = inter.InterpolatedUnivariateSpline(rgasr,rgasv,k=5)
rgasv_fit = rgasv_spline(r_dat)
# In[7]:
# Define for plotting cont.
#rval = np.linspace(0,11.2,0.1)
g_dict = g_fit.best_values
g_g = g_dict['GX']
g_b = g_dict['BX']
g_d = g_dict['DX']
g_rc = g_dict['rc']
g_rho00 = g_dict['rho00']
halo_curve = nf.h_v(rval,g_rc,g_rho00)
plt.figure(figsize=(11,6))
plt.errorbar(r_dat,v_dat,yerr=v_err1,fmt='bo',label='Data')
#plt.plot(rval,f_v_T_v(rval),'k',label='Total Fit')
plt.plot(r_dat,bestg,'k',label='Total Fit')
plt.plot(rgasr,g_g*rgasv_fit,label='Fitted Gas') #plot doesn't look right if using rval to graph
plt.plot(rbulger,g_b*rbulgev,label='Fitted Bulge')
#plt.scatter(r_dat,g_b*rbulgev_spline(r_dat),label='Bulge Points') #confusion
plt.plot(rval,halo_curve,'r-',label='Halo Analytical')
#halo_curve=halo_curve[:len(halo_curve)-6]
#halo_curve=halo_curve[0::6]
plt.plot(rdiskr,g_d*rdiskv,label='Fitted Disk')
#plt.plot(halo_dtr,g_h*halo_dtv,label='Fitted Halo')
#ZZZ=np.append([0],bestg)
#bary=ZZZ-halo_curve
#plt.plot(r_dat_andzero,bary,'m',label='Baryonic (visible) matter')
plt.legend(loc='lower right')
plt.ylim(0,360)
plt.xlim(0,12)
#plt.show()
plt.close()
# In[8]:
# In[ ]:
| [
"sys.path.append",
"matplotlib.pyplot.xlim",
"scipy.interpolate.InterpolatedUnivariateSpline",
"matplotlib.pyplot.plot",
"warnings.filterwarnings",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.close",
"numpy.asarray",
"dataPython.getXYdata",
"matplotlib.pyplot.legend",
"numpy.shape",
"numpy.ap... | [((120, 152), 'sys.path.append', 'sys.path.append', (['"""../../python/"""'], {}), "('../../python/')\n", (135, 152), False, 'import sys\n'), ((659, 692), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (682, 692), False, 'import warnings\n'), ((814, 877), 'dataPython.getXYdata_wXYerr', 'dp.getXYdata_wXYerr', (['"""../NGC_5005/traced_data/ngc5005_data.txt"""'], {}), "('../NGC_5005/traced_data/ngc5005_data.txt')\n", (833, 877), True, 'import dataPython as dp\n'), ((886, 908), 'numpy.asarray', 'np.asarray', (["data['xx']"], {}), "(data['xx'])\n", (896, 908), True, 'import numpy as np\n'), ((917, 939), 'numpy.asarray', 'np.asarray', (["data['yy']"], {}), "(data['yy'])\n", (927, 939), True, 'import numpy as np\n'), ((949, 971), 'numpy.asarray', 'np.asarray', (["data['ex']"], {}), "(data['ex'])\n", (959, 971), True, 'import numpy as np\n'), ((981, 1003), 'numpy.asarray', 'np.asarray', (["data['ey']"], {}), "(data['ey'])\n", (991, 1003), True, 'import numpy as np\n'), ((1117, 1154), 'dataPython.getXYZdata', 'dp.getXYZdata', (['"""../testing/aygas.dat"""'], {}), "('../testing/aygas.dat')\n", (1130, 1154), True, 'import dataPython as dp\n'), ((1225, 1242), 'numpy.asarray', 'np.asarray', (['rgasv'], {}), '(rgasv)\n', (1235, 1242), True, 'import numpy as np\n'), ((1258, 1311), 'scipy.interpolate.InterpolatedUnivariateSpline', 'inter.InterpolatedUnivariateSpline', (['rgasr', 'rgasv'], {'k': '(5)'}), '(rgasr, rgasv, k=5)\n', (1292, 1311), True, 'import scipy.interpolate as inter\n'), ((1582, 1621), 'dataPython.getXYZdata', 'dp.getXYZdata', (['"""../testing/aybulge.dat"""'], {}), "('../testing/aybulge.dat')\n", (1595, 1621), True, 'import dataPython as dp\n'), ((1686, 1705), 'numpy.asarray', 'np.asarray', (['rbulgev'], {}), '(rbulgev)\n', (1696, 1705), True, 'import numpy as np\n'), ((1878, 1935), 'scipy.interpolate.InterpolatedUnivariateSpline', 'inter.InterpolatedUnivariateSpline', (['rbulger', 'rbulgev'], {'k': '(5)'}), '(rbulger, rbulgev, k=5)\n', (1912, 1935), True, 'import scipy.interpolate as inter\n'), ((2158, 2196), 'dataPython.getXYZdata', 'dp.getXYZdata', (['"""../testing/aydisk.dat"""'], {}), "('../testing/aydisk.dat')\n", (2171, 2196), True, 'import dataPython as dp\n'), ((2256, 2274), 'numpy.asarray', 'np.asarray', (['rdiskv'], {}), '(rdiskv)\n', (2266, 2274), True, 'import numpy as np\n'), ((2344, 2399), 'scipy.interpolate.InterpolatedUnivariateSpline', 'inter.InterpolatedUnivariateSpline', (['rdiskr', 'rdiskv'], {'k': '(5)'}), '(rdiskr, rdiskv, k=5)\n', (2378, 2399), True, 'import scipy.interpolate as inter\n'), ((2484, 2537), 'dataPython.getXYdata', 'dp.getXYdata', (['"""../NGC_5005/datatheif_halo_spline.txt"""'], {}), "('../NGC_5005/datatheif_halo_spline.txt')\n", (2496, 2537), True, 'import dataPython as dp\n'), ((2597, 2617), 'numpy.asarray', 'np.asarray', (['halo_dtv'], {}), '(halo_dtv)\n', (2607, 2617), True, 'import numpy as np\n'), ((2698, 2757), 'scipy.interpolate.InterpolatedUnivariateSpline', 'inter.InterpolatedUnivariateSpline', (['halo_dtr', 'halo_dtv'], {'k': '(5)'}), '(halo_dtr, halo_dtv, k=5)\n', (2732, 2757), True, 'import scipy.interpolate as inter\n'), ((3181, 3192), 'lmfit.Model', 'lm.Model', (['g'], {}), '(g)\n', (3189, 3192), True, 'import lmfit as lm\n'), ((3919, 3940), 'numpy.append', 'np.append', (['[0]', 'r_dat'], {}), '([0], r_dat)\n', (3928, 3940), True, 'import numpy as np\n'), ((4171, 4224), 'scipy.interpolate.InterpolatedUnivariateSpline', 'inter.InterpolatedUnivariateSpline', (['rgasr', 'rgasv'], {'k': '(5)'}), '(rgasr, rgasv, k=5)\n', (4205, 4224), True, 'import scipy.interpolate as inter\n'), ((4474, 4501), 'NGC5533_functions.h_v', 'nf.h_v', (['rval', 'g_rc', 'g_rho00'], {}), '(rval, g_rc, g_rho00)\n', (4480, 4501), True, 'import NGC5533_functions as nf\n'), ((4501, 4528), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(11, 6)'}), '(figsize=(11, 6))\n', (4511, 4528), True, 'import matplotlib.pyplot as plt\n'), ((4528, 4591), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['r_dat', 'v_dat'], {'yerr': 'v_err1', 'fmt': '"""bo"""', 'label': '"""Data"""'}), "(r_dat, v_dat, yerr=v_err1, fmt='bo', label='Data')\n", (4540, 4591), True, 'import matplotlib.pyplot as plt\n'), ((4640, 4686), 'matplotlib.pyplot.plot', 'plt.plot', (['r_dat', 'bestg', '"""k"""'], {'label': '"""Total Fit"""'}), "(r_dat, bestg, 'k', label='Total Fit')\n", (4648, 4686), True, 'import matplotlib.pyplot as plt\n'), ((4684, 4736), 'matplotlib.pyplot.plot', 'plt.plot', (['rgasr', '(g_g * rgasv_fit)'], {'label': '"""Fitted Gas"""'}), "(rgasr, g_g * rgasv_fit, label='Fitted Gas')\n", (4692, 4736), True, 'import matplotlib.pyplot as plt\n'), ((4783, 4837), 'matplotlib.pyplot.plot', 'plt.plot', (['rbulger', '(g_b * rbulgev)'], {'label': '"""Fitted Bulge"""'}), "(rbulger, g_b * rbulgev, label='Fitted Bulge')\n", (4791, 4837), True, 'import matplotlib.pyplot as plt\n'), ((4912, 4969), 'matplotlib.pyplot.plot', 'plt.plot', (['rval', 'halo_curve', '"""r-"""'], {'label': '"""Halo Analytical"""'}), "(rval, halo_curve, 'r-', label='Halo Analytical')\n", (4920, 4969), True, 'import matplotlib.pyplot as plt\n'), ((5041, 5092), 'matplotlib.pyplot.plot', 'plt.plot', (['rdiskr', '(g_d * rdiskv)'], {'label': '"""Fitted Disk"""'}), "(rdiskr, g_d * rdiskv, label='Fitted Disk')\n", (5049, 5092), True, 'import matplotlib.pyplot as plt\n'), ((5258, 5287), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (5268, 5287), True, 'import matplotlib.pyplot as plt\n'), ((5288, 5304), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(360)'], {}), '(0, 360)\n', (5296, 5304), True, 'import matplotlib.pyplot as plt\n'), ((5304, 5319), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(12)'], {}), '(0, 12)\n', (5312, 5319), True, 'import matplotlib.pyplot as plt\n'), ((5331, 5342), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5340, 5342), True, 'import matplotlib.pyplot as plt\n'), ((3958, 3981), 'numpy.shape', 'np.shape', (['r_dat_andzero'], {}), '(r_dat_andzero)\n', (3966, 3981), True, 'import numpy as np\n'), ((3083, 3106), 'NGC5533_functions.h_v', 'nf.h_v', (['rval', 'rc', 'rho00'], {}), '(rval, rc, rho00)\n', (3089, 3106), True, 'import NGC5533_functions as nf\n')] |
"""These classes hold methods to apply general filters to any data type.
By inheriting these classes into the wrapped VTK data structures, a user
can easily apply common filters in an intuitive manner.
Example
-------
>>> import pyvista
>>> from pyvista import examples
>>> dataset = examples.load_uniform()
>>> # Threshold
>>> thresh = dataset.threshold([100, 500])
>>> # Slice
>>> slc = dataset.slice()
>>> # Clip
>>> clp = dataset.clip(invert=True)
>>> # Contour
>>> iso = dataset.contour()
"""
import collections.abc
import logging
from functools import wraps
import numpy as np
import vtk
from vtk.util.numpy_support import vtk_to_numpy
import pyvista
from pyvista.utilities import (FieldAssociation, NORMALS, assert_empty_kwargs,
generate_plane, get_array, vtk_id_list_to_array,
wrap, ProgressMonitor, abstract_class)
from pyvista.utilities.cells import numpy_to_idarr
from pyvista.core.errors import NotAllTrianglesError
def _update_alg(alg, progress_bar=False, message=''):
"""Update an algorithm with or without a progress bar."""
if progress_bar:
with ProgressMonitor(alg, message=message):
alg.Update()
else:
alg.Update()
def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalars=None,
active_scalars_field='point'):
"""Get the algorithm's output and copy input's pyvista meta info."""
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
if not isinstance(data, pyvista.MultiBlock):
data.copy_meta_from(ido)
if not data.field_arrays and ido.field_arrays:
data.field_arrays.update(ido.field_arrays)
if active_scalars is not None:
data.set_active_scalars(active_scalars, preference=active_scalars_field)
return data
@abstract_class
class DataSetFilters:
"""A set of common filters that can be applied to any vtkDataSet."""
def _clip_with_function(dataset, function, invert=True, value=0.0):
"""Clip using an implicit function (internal helper)."""
if isinstance(dataset, vtk.vtkPolyData):
alg = vtk.vtkClipPolyData()
# elif isinstance(dataset, vtk.vtkImageData):
# alg = vtk.vtkClipVolume()
# alg.SetMixed3DCellGeneration(True)
else:
alg = vtk.vtkTableBasedClipDataSet()
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetValue(value)
alg.SetClipFunction(function) # the implicit function
alg.SetInsideOut(invert) # invert the clip if needed
alg.Update() # Perform the Cut
return _get_output(alg)
def clip(dataset, normal='x', origin=None, invert=True, value=0.0, inplace=False):
"""Clip a dataset by a plane by specifying the origin and normal.
If no parameters are given the clip will occur in the center of that dataset.
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)``, etc.
origin : tuple(float), optional
The center ``(x,y,z)`` coordinate of the plane on which the clip
occurs. The default is the center of the dataset.
invert : bool, optional
Flag on whether to flip/invert the clip.
value : float, optional
Set the clipping value along the normal direction.
The default value is 0.0.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Clipped mesh when ``inplace=False``. When
``inplace=True``, ``None``
Examples
--------
Clip a cube along the +X direction. ``triangulate`` is used as
the cube is initially composed of quadrilateral faces and
subdivide only works on triangles.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip()
Clip a cube in the +Z direction. This leaves half a cube
below the XY plane.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip('z')
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
# create the plane for clipping
function = generate_plane(normal, origin)
# run the clip
result = DataSetFilters._clip_with_function(dataset, function,
invert=invert, value=value)
if inplace:
dataset.overwrite(result)
else:
return result
def clip_box(dataset, bounds=None, invert=True, factor=0.35):
"""Clip a dataset by a bounding box defined by the bounds.
If no bounds are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float)
Length 6 sequence of floats: (xmin, xmax, ymin, ymax, zmin, zmax).
Length 3 sequence of floats: distances from the min coordinate of
of the input mesh. Single float value: uniform distance from the
min coordinate. Length 12 sequence of length 3 sequence of floats:
a plane collection (normal, center, ...).
:class:`pyvista.PolyData`: if a poly mesh is passed that represents
a box with 6 faces that all form a standard box, then planes will
be extracted from the box to define the clipping region.
invert : bool
Flag on whether to flip/invert the clip
factor : float, optional
If bounds are not given this is the factor along each axis to
extract the default box.
Examples
--------
Clip a corner of a cube. The bounds of a cube are normally
``[-0.5, 0.5, -0.5, 0.5, -0.5, 0.5]``, and this removes 1/8 of
the cube's surface.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip_box([0, 1, 0, 1, 0, 1])
"""
if bounds is None:
def _get_quarter(dmin, dmax):
"""Get a section of the given range (internal helper)."""
return dmax - ((dmax - dmin) * factor)
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
xmin = _get_quarter(xmin, xmax)
ymin = _get_quarter(ymin, ymax)
zmin = _get_quarter(zmin, zmax)
bounds = [xmin, xmax, ymin, ymax, zmin, zmax]
if isinstance(bounds, (float, int)):
bounds = [bounds, bounds, bounds]
elif isinstance(bounds, pyvista.PolyData):
poly = bounds
if poly.n_cells != 6:
raise ValueError("The bounds mesh must have only 6 faces.")
bounds = []
poly.compute_normals()
for cid in range(6):
cell = poly.extract_cells(cid)
normal = cell["Normals"][0]
bounds.append(normal)
bounds.append(cell.center)
if not isinstance(bounds, (np.ndarray, collections.abc.Sequence)):
raise TypeError('Bounds must be a sequence of floats with length 3, 6 or 12.')
if len(bounds) not in [3, 6, 12]:
raise ValueError('Bounds must be a sequence of floats with length 3, 6 or 12.')
if len(bounds) == 3:
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
bounds = (xmin,xmin+bounds[0], ymin,ymin+bounds[1], zmin,zmin+bounds[2])
alg = vtk.vtkBoxClipDataSet()
alg.SetInputDataObject(dataset)
alg.SetBoxClip(*bounds)
port = 0
if invert:
# invert the clip if needed
port = 1
alg.GenerateClippedOutputOn()
alg.Update()
return _get_output(alg, oport=port)
def compute_implicit_distance(dataset, surface, inplace=False):
"""Compute the implicit distance from the points to a surface.
This filter will comput the implicit distance from all of the nodes of
this mesh to a given surface. This distance will be added as a point
array called ``'implicit_distance'``.
Parameters
----------
surface : pyvista.Common
The surface used to compute the distance
inplace : bool
If True, a new scalar array will be added to the ``point_arrays``
of this mesh. Otherwise a copy of this mesh is returned with that
scalar field.
Examples
--------
Compute the distance between all the points on a sphere and a
plane.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plane = pv.Plane()
>>> sphere.compute_implicit_distance(plane, inplace=True)
>>> dist = sphere['implicit_distance']
>>> print(type(dist))
<class 'numpy.ndarray'>
Plot these distances as a heatmap
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(sphere, scalars='implicit_distance', cmap='bwr')
>>> _ = pl.add_mesh(plane, color='w', style='wireframe')
>>> pl.show() # doctest:+SKIP
"""
function = vtk.vtkImplicitPolyDataDistance()
function.SetInput(surface)
points = pyvista.convert_array(dataset.points)
dists = vtk.vtkDoubleArray()
function.FunctionValue(points, dists)
if inplace:
dataset.point_arrays['implicit_distance'] = pyvista.convert_array(dists)
return
result = dataset.copy()
result.point_arrays['implicit_distance'] = pyvista.convert_array(dists)
return result
def clip_scalar(dataset, scalars=None, invert=True, value=0.0, inplace=False):
"""Clip a dataset by a scalar.
Parameters
----------
scalars : str, optional
Name of scalars to clip on. Defaults to currently active scalars.
invert : bool, optional
Flag on whether to flip/invert the clip. When ``True``,
only the mesh below ``value`` will be kept. When
``False``, only values above ``value`` will be kept.
value : float, optional
Set the clipping value. The default value is 0.0.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
pdata : pyvista.PolyData
Clipped dataset.
Examples
--------
Remove the part of the mesh with "sample_point_scalars" above 100.
>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(scalars="sample_point_scalars", value=100)
Remove the part of the mesh with "sample_point_scalars" below
100. Since these scalars are already active, there's no need
to specify ``scalars=``
>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(value=100, invert=False)
"""
if isinstance(dataset, vtk.vtkPolyData):
alg = vtk.vtkClipPolyData()
else:
alg = vtk.vtkTableBasedClipDataSet()
alg.SetInputDataObject(dataset)
alg.SetValue(value)
if scalars is None:
field, scalars = dataset.active_scalars_info
_, field = get_array(dataset, scalars, preference='point', info=True)
# SetInputArrayToProcess(idx, port, connection, field, name)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
alg.SetInsideOut(invert) # invert the clip if needed
alg.Update() # Perform the Cut
result = _get_output(alg)
if inplace:
dataset.overwrite(result)
else:
return result
def clip_surface(dataset, surface, invert=True, value=0.0,
compute_distance=False):
"""Clip any mesh type using a :class:`pyvista.PolyData` surface mesh.
This will return a :class:`pyvista.UnstructuredGrid` of the clipped
mesh. Geometry of the input dataset will be preserved where possible -
geometries near the clip intersection will be triangulated/tessellated.
Parameters
----------
surface : pyvista.PolyData
The PolyData surface mesh to use as a clipping function. If this
mesh is not PolyData, the external surface will be extracted.
invert : bool
Flag on whether to flip/invert the clip
value : float:
Set the clipping value of the implicit function (if clipping with
implicit function) or scalar value (if clipping with scalars).
The default value is 0.0.
compute_distance : bool, optional
Compute the implicit distance from the mesh onto the input dataset.
A new array called ``'implicit_distance'`` will be added to the
output clipped mesh.
"""
if not isinstance(surface, vtk.vtkPolyData):
surface = DataSetFilters.extract_geometry(surface)
function = vtk.vtkImplicitPolyDataDistance()
function.SetInput(surface)
if compute_distance:
points = pyvista.convert_array(dataset.points)
dists = vtk.vtkDoubleArray()
function.FunctionValue(points, dists)
dataset['implicit_distance'] = pyvista.convert_array(dists)
# run the clip
result = DataSetFilters._clip_with_function(dataset, function,
invert=invert, value=value)
return result
def slice(dataset, normal='x', origin=None, generate_triangles=False,
contour=False):
"""Slice a dataset by a plane at the specified origin and normal vector orientation.
If no origin is specified, the center of the input dataset will be used.
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)```, etc.
origin : tuple(float)
The center (x,y,z) coordinate of the plane on which the slice occurs
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
# create the plane for clipping
plane = generate_plane(normal, origin)
# create slice
alg = vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetCutFunction(plane) # the cutter to use the plane we made
if not generate_triangles:
alg.GenerateTrianglesOff()
alg.Update() # Perform the Cut
output = _get_output(alg)
if contour:
return output.contour()
return output
def slice_orthogonal(dataset, x=None, y=None, z=None,
generate_triangles=False, contour=False):
"""Create three orthogonal slices through the dataset on the three cartesian planes.
Yields a MutliBlock dataset of the three slices.
Parameters
----------
x : float
The X location of the YZ slice
y : float
The Y location of the XZ slice
z : float
The Z location of the XY slice
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
# Create the three slices
if x is None:
x = dataset.center[0]
if y is None:
y = dataset.center[1]
if z is None:
z = dataset.center[2]
output = pyvista.MultiBlock()
if isinstance(dataset, pyvista.MultiBlock):
for i in range(dataset.n_blocks):
output[i] = dataset[i].slice_orthogonal(x=x, y=y, z=z,
generate_triangles=generate_triangles,
contour=contour)
return output
output[0, 'YZ'] = dataset.slice(normal='x', origin=[x,y,z], generate_triangles=generate_triangles)
output[1, 'XZ'] = dataset.slice(normal='y', origin=[x,y,z], generate_triangles=generate_triangles)
output[2, 'XY'] = dataset.slice(normal='z', origin=[x,y,z], generate_triangles=generate_triangles)
return output
def slice_along_axis(dataset, n=5, axis='x', tolerance=None,
generate_triangles=False, contour=False,
bounds=None, center=None):
"""Create many slices of the input dataset along a specified axis.
Parameters
----------
n : int
The number of slices to create
axis : str or int
The axis to generate the slices along. Perpendicular to the slices.
Can be string name (``'x'``, ``'y'``, or ``'z'``) or axis index
(``0``, ``1``, or ``2``).
tolerance : float, optional
The tolerance to the edge of the dataset bounds to create the slices
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
axes = {'x':0, 'y':1, 'z':2}
if isinstance(axis, int):
ax = axis
axis = list(axes.keys())[list(axes.values()).index(ax)]
elif isinstance(axis, str):
try:
ax = axes[axis]
except KeyError:
raise ValueError(f'Axis ({axis}) not understood')
# get the locations along that axis
if bounds is None:
bounds = dataset.bounds
if center is None:
center = dataset.center
if tolerance is None:
tolerance = (bounds[ax*2+1] - bounds[ax*2]) * 0.01
rng = np.linspace(bounds[ax*2]+tolerance, bounds[ax*2+1]-tolerance, n)
center = list(center)
# Make each of the slices
output = pyvista.MultiBlock()
if isinstance(dataset, pyvista.MultiBlock):
for i in range(dataset.n_blocks):
output[i] = dataset[i].slice_along_axis(n=n, axis=axis,
tolerance=tolerance, generate_triangles=generate_triangles,
contour=contour, bounds=bounds, center=center)
return output
for i in range(n):
center[ax] = rng[i]
slc = DataSetFilters.slice(dataset, normal=axis, origin=center,
generate_triangles=generate_triangles,
contour=contour)
output[i, f'slice{i}'] = slc
return output
def slice_along_line(dataset, line, generate_triangles=False,
contour=False):
"""Slice a dataset using a polyline/spline as the path.
This also works for lines generated with :func:`pyvista.Line`
Parameters
----------
line : pyvista.PolyData
A PolyData object containing one single PolyLine cell.
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
# check that we have a PolyLine cell in the input line
if line.GetNumberOfCells() != 1:
raise ValueError('Input line must have only one cell.')
polyline = line.GetCell(0)
if not isinstance(polyline, vtk.vtkPolyLine):
raise TypeError(f'Input line must have a PolyLine cell, not ({type(polyline)})')
# Generate PolyPlane
polyplane = vtk.vtkPolyPlane()
polyplane.SetPolyLine(polyline)
# Create slice
alg = vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetCutFunction(polyplane) # the cutter to use the poly planes
if not generate_triangles:
alg.GenerateTrianglesOff()
alg.Update() # Perform the Cut
output = _get_output(alg)
if contour:
return output.contour()
return output
def threshold(dataset, value=None, scalars=None, invert=False, continuous=False,
preference='cell', all_scalars=False):
"""Apply a ``vtkThreshold`` filter to the input dataset.
This filter will apply a ``vtkThreshold`` filter to the input dataset
and return the resulting object. This extracts cells where the scalar
value in each cell satisfies threshold criterion. If scalars is None,
the inputs active scalars is used.
Parameters
----------
value : float or sequence, optional
Single value or (min, max) to be used for the data threshold. If
a sequence, then length must be 2. If no value is specified, the
non-NaN data range will be used to remove any NaN values.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
If value is a single value, when invert is True cells are kept when
their values are below parameter "value". When invert is False
cells are kept when their value is above the threshold "value".
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maximum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the preferred array type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
all_scalars : bool, optional
If using scalars from point data, all scalars for all
points in a cell must satisfy the threshold when this
value is ``True``. When ``False``, any point of the cell
with a scalar value satisfying the threshold criterion
will extract the cell.
Examples
--------
>>> import pyvista
>>> import numpy as np
>>> volume = np.zeros([10, 10, 10])
>>> volume[:3] = 1
>>> v = pyvista.wrap(volume)
>>> threshed = v.threshold(0.1)
"""
# set the scalaras to threshold on
if scalars is None:
field, scalars = dataset.active_scalars_info
arr, field = get_array(dataset, scalars, preference=preference, info=True)
if all_scalars and scalars is not None:
raise ValueError('Setting `all_scalars=True` and designating `scalars` '
'is incompatible. Set one or the other but not both')
if arr is None:
raise ValueError('No arrays present to threshold.')
# If using an inverted range, merge the result of two filters:
if isinstance(value, (np.ndarray, collections.abc.Sequence)) and invert:
valid_range = [np.nanmin(arr), np.nanmax(arr)]
# Create two thresholds
t1 = dataset.threshold([valid_range[0], value[0]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
t2 = dataset.threshold([value[1], valid_range[1]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
# Use an AppendFilter to merge the two results
appender = vtk.vtkAppendFilter()
appender.AddInputData(t1)
appender.AddInputData(t2)
appender.Update()
return _get_output(appender)
# Run a standard threshold algorithm
alg = vtk.vtkThreshold()
alg.SetAllScalars(all_scalars)
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
# set thresholding parameters
alg.SetUseContinuousCellRange(continuous)
# use valid range if no value given
if value is None:
value = dataset.get_data_range(scalars)
# check if value is a sequence (if so threshold by min max range like ParaView)
if isinstance(value, (np.ndarray, collections.abc.Sequence)):
if len(value) != 2:
raise ValueError(f'Value range must be length one for a float value or two for min/max; not ({value}).')
alg.ThresholdBetween(value[0], value[1])
elif isinstance(value, collections.abc.Iterable):
raise TypeError('Value must either be a single scalar or a sequence.')
else:
# just a single value
if invert:
alg.ThresholdByLower(value)
else:
alg.ThresholdByUpper(value)
# Run the threshold
alg.Update()
return _get_output(alg)
def threshold_percent(dataset, percent=0.50, scalars=None, invert=False,
continuous=False, preference='cell'):
"""Threshold the dataset by a percentage of its range on the active scalars array or as specified.
Parameters
----------
percent : float or tuple(float), optional
The percentage (0,1) to threshold. If value is out of 0 to 1 range,
then it will be divided by 100 and checked to be in that range.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
When invert is True cells are kept when their values are below the
percentage of the range. When invert is False, cells are kept when
their value is above the percentage of the range.
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maximum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the preferred array type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
if scalars is None:
_, tscalars = dataset.active_scalars_info
else:
tscalars = scalars
dmin, dmax = dataset.get_data_range(arr=tscalars, preference=preference)
def _check_percent(percent):
"""Make sure percent is between 0 and 1 or fix if between 0 and 100."""
if percent >= 1:
percent = float(percent) / 100.0
if percent > 1:
raise ValueError(f'Percentage ({percent}) is out of range (0, 1).')
if percent < 1e-10:
raise ValueError(f'Percentage ({percent}) is too close to zero or negative.')
return percent
def _get_val(percent, dmin, dmax):
"""Get the value from a percentage of a range."""
percent = _check_percent(percent)
return dmin + float(percent) * (dmax - dmin)
# Compute the values
if isinstance(percent, (np.ndarray, collections.abc.Sequence)):
# Get two values
value = [_get_val(percent[0], dmin, dmax), _get_val(percent[1], dmin, dmax)]
elif isinstance(percent, collections.abc.Iterable):
raise TypeError('Percent must either be a single scalar or a sequence.')
else:
# Compute one value to threshold
value = _get_val(percent, dmin, dmax)
# Use the normal thresholding function on these values
return DataSetFilters.threshold(dataset, value=value, scalars=scalars,
invert=invert, continuous=continuous,
preference=preference)
def outline(dataset, generate_faces=False):
"""Produce an outline of the full extent for the input dataset.
Parameters
----------
generate_faces : bool, optional
Generate solid faces for the box. This is off by default
"""
alg = vtk.vtkOutlineFilter()
alg.SetInputDataObject(dataset)
alg.SetGenerateFaces(generate_faces)
alg.Update()
return wrap(alg.GetOutputDataObject(0))
def outline_corners(dataset, factor=0.2):
"""Produce an outline of the corners for the input dataset.
Parameters
----------
factor : float, optional
controls the relative size of the corners to the length of the
corresponding bounds
"""
alg = vtk.vtkOutlineCornerFilter()
alg.SetInputDataObject(dataset)
alg.SetCornerFactor(factor)
alg.Update()
return wrap(alg.GetOutputDataObject(0))
def extract_geometry(dataset):
"""Extract the outer surface of a volume or structured grid dataset as PolyData.
This will extract all 0D, 1D, and 2D cells producing the
boundary faces of the dataset.
"""
alg = vtk.vtkGeometryFilter()
alg.SetInputDataObject(dataset)
alg.Update()
return _get_output(alg)
def extract_all_edges(dataset, progress_bar=False):
"""Extract all the internal/external edges of the dataset as PolyData.
This produces a full wireframe representation of the input dataset.
Parameters
----------
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
alg = vtk.vtkExtractEdges()
alg.SetInputDataObject(dataset)
_update_alg(alg, progress_bar, 'Extracting All Edges')
return _get_output(alg)
def elevation(dataset, low_point=None, high_point=None, scalar_range=None,
preference='point', set_active=True, progress_bar=False):
"""Generate scalar values on a dataset.
The scalar values lie within a user specified range, and are
generated by computing a projection of each dataset point onto
a line. The line can be oriented arbitrarily. A typical
example is to generate scalars based on elevation or height
above a plane.
Parameters
----------
low_point : tuple(float), optional
The low point of the projection line in 3D space. Default is bottom
center of the dataset. Otherwise pass a length 3 ``tuple(float)``.
high_point : tuple(float), optional
The high point of the projection line in 3D space. Default is top
center of the dataset. Otherwise pass a length 3 ``tuple(float)``.
scalar_range : str or tuple(float), optional
The scalar range to project to the low and high points on the line
that will be mapped to the dataset. If None given, the values will
be computed from the elevation (Z component) range between the
high and low points. Min and max of a range can be given as a length
2 tuple(float). If ``str`` name of scalara array present in the
dataset given, the valid range of that array will be used.
preference : str, optional
When an array name is specified for ``scalar_range``, this is the
preferred array type to search for in the dataset.
Must be either 'point' or 'cell'.
set_active : bool, optional
A boolean flag on whether or not to set the new `Elevation` scalar
as the active scalars array on the output dataset.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Warning
-------
This will create a scalars array named `Elevation` on the point data of
the input dataset and overasdf write an array named `Elevation` if present.
"""
# Fix the projection line:
if low_point is None:
low_point = list(dataset.center)
low_point[2] = dataset.bounds[4]
if high_point is None:
high_point = list(dataset.center)
high_point[2] = dataset.bounds[5]
# Fix scalar_range:
if scalar_range is None:
scalar_range = (low_point[2], high_point[2])
elif isinstance(scalar_range, str):
scalar_range = dataset.get_data_range(arr=scalar_range, preference=preference)
elif isinstance(scalar_range, (np.ndarray, collections.abc.Sequence)):
if len(scalar_range) != 2:
raise ValueError('scalar_range must have a length of two defining the min and max')
else:
raise TypeError(f'scalar_range argument ({scalar_range}) not understood.')
# Construct the filter
alg = vtk.vtkElevationFilter()
alg.SetInputDataObject(dataset)
# Set the parameters
alg.SetScalarRange(scalar_range)
alg.SetLowPoint(low_point)
alg.SetHighPoint(high_point)
_update_alg(alg, progress_bar, 'Computing Elevation')
# Decide on updating active scalars array
name = 'Elevation' # Note that this is added to the PointData
if not set_active:
name = None
return _get_output(alg, active_scalars=name, active_scalars_field='point')
def contour(dataset, isosurfaces=10, scalars=None, compute_normals=False,
compute_gradients=False, compute_scalars=True, rng=None,
preference='point', method='contour', progress_bar=False):
"""Contour an input dataset by an array.
``isosurfaces`` can be an integer specifying the number of isosurfaces in
the data range or a sequence of values for explicitly setting the isosurfaces.
Parameters
----------
isosurfaces : int or sequence
Number of isosurfaces to compute across valid data range or a
sequence of float values to explicitly use as the isosurfaces.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
compute_normals : bool, optional
compute_gradients : bool, optional
Desc
compute_scalars : bool, optional
Preserves the scalar values that are being contoured
rng : tuple(float), optional
If an integer number of isosurfaces is specified, this is the range
over which to generate contours. Default is the scalars arrays' full
data range.
preference : str, optional
When scalars is specified, this is the preferred array type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
method : str, optional
Specify to choose which vtk filter is used to create the contour.
Must be one of ``'contour'``, ``'marching_cubes'`` and
``'flying_edges'``. Defaults to ``'contour'``.
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
if method is None or method == 'contour':
alg = vtk.vtkContourFilter()
elif method == 'marching_cubes':
alg = vtk.vtkMarchingCubes()
elif method == 'flying_edges':
alg = vtk.vtkFlyingEdges3D()
else:
raise ValueError(f"Method '{method}' is not supported")
# Make sure the input has scalars to contour on
if dataset.n_arrays < 1:
raise ValueError('Input dataset for the contour filter must have scalar data.')
alg.SetInputDataObject(dataset)
alg.SetComputeNormals(compute_normals)
alg.SetComputeGradients(compute_gradients)
alg.SetComputeScalars(compute_scalars)
# set the array to contour on
if scalars is None:
field, scalars = dataset.active_scalars_info
else:
_, field = get_array(dataset, scalars, preference=preference, info=True)
# NOTE: only point data is allowed? well cells works but seems buggy?
if field != FieldAssociation.POINT:
raise TypeError(f'Contour filter only works on Point data. Array ({scalars}) is in the Cell data.')
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
# set the isosurfaces
if isinstance(isosurfaces, int):
# generate values
if rng is None:
rng = dataset.get_data_range(scalars)
alg.GenerateValues(isosurfaces, rng)
elif isinstance(isosurfaces, (np.ndarray, collections.abc.Sequence)):
alg.SetNumberOfContours(len(isosurfaces))
for i, val in enumerate(isosurfaces):
alg.SetValue(i, val)
else:
raise TypeError('isosurfaces not understood.')
_update_alg(alg, progress_bar, 'Computing Contour')
return _get_output(alg)
def texture_map_to_plane(dataset, origin=None, point_u=None, point_v=None,
inplace=False, name='Texture Coordinates',
use_bounds=False):
"""Texture map this dataset to a user defined plane.
This is often used to define a plane to texture map an image to this dataset.
The plane defines the spatial reference and extent of that image.
Parameters
----------
origin : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM LEFT CORNER of the plane
point_u : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM RIGHT CORNER of the plane
point_v : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
TOP LEFT CORNER of the plane
inplace : bool, optional
If True, the new texture coordinates will be added to the dataset
inplace. If False (default), a new dataset is returned with the
textures coordinates
name : str, optional
The string name to give the new texture coordinates if applying
the filter inplace.
use_bounds : bool, optional
Use the bounds to set the mapping plane by default (bottom plane
of the bounding box).
"""
if use_bounds:
if isinstance(use_bounds, (int, bool)):
b = dataset.GetBounds()
origin = [b[0], b[2], b[4]] # BOTTOM LEFT CORNER
point_u = [b[1], b[2], b[4]] # BOTTOM RIGHT CORNER
point_v = [b[0], b[3], b[4]] # TOP LEFT CORNER
alg = vtk.vtkTextureMapToPlane()
if origin is None or point_u is None or point_v is None:
alg.SetAutomaticPlaneGeneration(True)
else:
alg.SetOrigin(origin) # BOTTOM LEFT CORNER
alg.SetPoint1(point_u) # BOTTOM RIGHT CORNER
alg.SetPoint2(point_v) # TOP LEFT CORNER
alg.SetInputDataObject(dataset)
alg.Update()
output = _get_output(alg)
if not inplace:
return output
t_coords = output.GetPointData().GetTCoords()
t_coords.SetName(name)
otc = dataset.GetPointData().GetTCoords()
dataset.GetPointData().SetTCoords(t_coords)
dataset.GetPointData().AddArray(t_coords)
# CRITICAL:
dataset.GetPointData().AddArray(otc) # Add old ones back at the end
return # No return type because it is inplace
def texture_map_to_sphere(dataset, center=None, prevent_seam=True,
inplace=False, name='Texture Coordinates'):
"""Texture map this dataset to a user defined sphere.
This is often used to define a sphere to texture map an image to this
dataset. The sphere defines the spatial reference and extent of that image.
Parameters
----------
center : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
center of the sphere. If ``None``, this will be automatically
calculated.
prevent_seam : bool
Default true. Control how the texture coordinates are generated.
If set, the s-coordinate ranges from 0->1 and 1->0 corresponding
to the theta angle variation between 0->180 and 180->0 degrees.
Otherwise, the s-coordinate ranges from 0->1 between 0->360
degrees.
inplace : bool, optional
If True, the new texture coordinates will be added to the dataset
inplace. If False (default), a new dataset is returned with the
textures coordinates
name : str, optional
The string name to give the new texture coordinates if applying
the filter inplace.
Examples
--------
Map a puppy texture to a sphere
>>> import pyvista
>>> sphere = pyvista.Sphere()
>>> sphere.texture_map_to_sphere(inplace=True)
>>> tex = examples.download_puppy_texture() # doctest:+SKIP
>>> sphere.plot(texture=tex) # doctest:+SKIP
"""
alg = vtk.vtkTextureMapToSphere()
if center is None:
alg.SetAutomaticSphereGeneration(True)
else:
alg.SetAutomaticSphereGeneration(False)
alg.SetCenter(center)
alg.SetPreventSeam(prevent_seam)
alg.SetInputDataObject(dataset)
alg.Update()
output = _get_output(alg)
if not inplace:
return output
t_coords = output.GetPointData().GetTCoords()
t_coords.SetName(name)
otc = dataset.GetPointData().GetTCoords()
dataset.GetPointData().SetTCoords(t_coords)
dataset.GetPointData().AddArray(t_coords)
# CRITICAL:
dataset.GetPointData().AddArray(otc) # Add old ones back at the end
return # No return type because it is inplace
def compute_cell_sizes(dataset, length=True, area=True, volume=True,
progress_bar=False):
"""Compute sizes for 1D (length), 2D (area) and 3D (volume) cells.
Parameters
----------
length : bool
Specify whether or not to compute the length of 1D cells.
area : bool
Specify whether or not to compute the area of 2D cells.
volume : bool
Specify whether or not to compute the volume of 3D cells.
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
alg = vtk.vtkCellSizeFilter()
alg.SetInputDataObject(dataset)
alg.SetComputeArea(area)
alg.SetComputeVolume(volume)
alg.SetComputeLength(length)
alg.SetComputeVertexCount(False)
_update_alg(alg, progress_bar, 'Computing Cell Sizes')
return _get_output(alg)
def cell_centers(dataset, vertex=True):
"""Generate points at the center of the cells in this dataset.
These points can be used for placing glyphs / vectors.
Parameters
----------
vertex : bool
Enable/disable the generation of vertex cells.
"""
alg = vtk.vtkCellCenters()
alg.SetInputDataObject(dataset)
alg.SetVertexCells(vertex)
alg.Update()
output = _get_output(alg)
return output
def glyph(dataset, orient=True, scale=True, factor=1.0, geom=None,
indices=None, tolerance=None, absolute=False, clamping=False,
rng=None, progress_bar=False):
"""Copy a geometric representation (called a glyph) to every point in the input dataset.
The glyph may be oriented along the input vectors, and it may be scaled according to scalar
data or vector magnitude. Passing a table of glyphs to choose from based on scalars or
vector magnitudes is also supported.
Parameters
----------
orient : bool
Use the active vectors array to orient the glyphs
scale : bool
Use the active scalars to scale the glyphs
factor : float
Scale factor applied to scaling array
geom : vtk.vtkDataSet or tuple(vtk.vtkDataSet), optional
The geometry to use for the glyph. If missing, an arrow glyph
is used. If a sequence, the datasets inside define a table of
geometries to choose from based on scalars or vectors. In this
case a sequence of numbers of the same length must be passed as
``indices``. The values of the range (see ``rng``) affect lookup
in the table.
indices : tuple(float), optional
Specifies the index of each glyph in the table for lookup in case
``geom`` is a sequence. If given, must be the same length as
``geom``. If missing, a default value of ``range(len(geom))`` is
used. Indices are interpreted in terms of the scalar range
(see ``rng``). Ignored if ``geom`` has length 1.
tolerance : float, optional
Specify tolerance in terms of fraction of bounding box length.
Float value is between 0 and 1. Default is None. If ``absolute``
is ``True`` then the tolerance can be an absolute distance.
If None, points merging as a preprocessing step is disabled.
absolute : bool, optional
Control if ``tolerance`` is an absolute distance or a fraction.
clamping: bool
Turn on/off clamping of "scalar" values to range.
rng: tuple(float), optional
Set the range of values to be considered by the filter when scalars
values are provided.
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
# Clean the points before glyphing
if tolerance is not None:
small = pyvista.PolyData(dataset.points)
small.point_arrays.update(dataset.point_arrays)
dataset = small.clean(point_merging=True, merge_tol=tolerance,
lines_to_points=False, polys_to_lines=False,
strips_to_polys=False, inplace=False,
absolute=absolute, progress_bar=progress_bar)
# Make glyphing geometry if necessary
if geom is None:
arrow = vtk.vtkArrowSource()
arrow.Update()
geom = arrow.GetOutput()
# Check if a table of geometries was passed
if isinstance(geom, (np.ndarray, collections.abc.Sequence)):
if indices is None:
# use default "categorical" indices
indices = np.arange(len(geom))
if not isinstance(indices, (np.ndarray, collections.abc.Sequence)):
raise TypeError('If "geom" is a sequence then "indices" must '
'also be a sequence of the same length.')
if len(indices) != len(geom) and len(geom) != 1:
raise ValueError('The sequence "indices" must be the same length '
'as "geom".')
else:
geom = [geom]
if any(not isinstance(subgeom, vtk.vtkPolyData) for subgeom in geom):
raise TypeError('Only PolyData objects can be used as glyphs.')
# Run the algorithm
alg = vtk.vtkGlyph3D()
if len(geom) == 1:
# use a single glyph, ignore indices
alg.SetSourceData(geom[0])
else:
for index, subgeom in zip(indices, geom):
alg.SetSourceData(index, subgeom)
if dataset.active_scalars is not None:
if dataset.active_scalars.ndim > 1:
alg.SetIndexModeToVector()
else:
alg.SetIndexModeToScalar()
else:
alg.SetIndexModeToOff()
if isinstance(scale, str):
dataset.active_scalars_name = scale
scale = True
if scale:
if dataset.active_scalars is not None:
if dataset.active_scalars.ndim > 1:
alg.SetScaleModeToScaleByVector()
else:
alg.SetScaleModeToScaleByScalar()
else:
alg.SetScaleModeToDataScalingOff()
if isinstance(orient, str):
dataset.active_vectors_name = orient
orient = True
if rng is not None:
alg.SetRange(rng)
alg.SetOrient(orient)
alg.SetInputData(dataset)
alg.SetVectorModeToUseVector()
alg.SetScaleFactor(factor)
alg.SetClamping(clamping)
_update_alg(alg, progress_bar, 'Computing Glyphs')
return _get_output(alg)
def connectivity(dataset, largest=False):
"""Find and label connected bodies/volumes.
This adds an ID array to the point and cell data to distinguish separate
connected bodies. This applies a ``vtkConnectivityFilter`` filter which
extracts cells that share common points and/or meet other connectivity
criterion.
(Cells that share vertices and meet other connectivity criterion such
as scalar range are known as a region.)
Parameters
----------
largest : bool
Extract the largest connected part of the mesh.
"""
alg = vtk.vtkConnectivityFilter()
alg.SetInputData(dataset)
if largest:
alg.SetExtractionModeToLargestRegion()
else:
alg.SetExtractionModeToAllRegions()
alg.SetColorRegions(True)
alg.Update()
return _get_output(alg)
def extract_largest(dataset, inplace=False):
"""
Extract largest connected set in mesh.
Can be used to reduce residues obtained when generating an isosurface.
Works only if residues are not connected (share at least one point with)
the main component of the image.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Largest connected set in mesh
"""
mesh = DataSetFilters.connectivity(dataset, largest=True)
if inplace:
dataset.overwrite(mesh)
else:
return mesh
def split_bodies(dataset, label=False):
"""Find, label, and split connected bodies/volumes.
This splits different connected bodies into blocks in a MultiBlock dataset.
Parameters
----------
label : bool
A flag on whether to keep the ID arrays given by the
``connectivity`` filter.
"""
# Get the connectivity and label different bodies
labeled = DataSetFilters.connectivity(dataset)
classifier = labeled.cell_arrays['RegionId']
bodies = pyvista.MultiBlock()
for vid in np.unique(classifier):
# Now extract it:
b = labeled.threshold([vid-0.5, vid+0.5], scalars='RegionId')
if not label:
# strange behavior:
# must use this method rather than deleting from the point_arrays
# or else object is collected.
b.cell_arrays.remove('RegionId')
b.point_arrays.remove('RegionId')
bodies.append(b)
return bodies
def warp_by_scalar(dataset, scalars=None, factor=1.0, normal=None,
inplace=False, **kwargs):
"""Warp the dataset's points by a point data scalars array's values.
This modifies point coordinates by moving points along point normals by
the scalar amount times the scale factor.
Parameters
----------
scalars : str, optional
Name of scalars to warp by. Defaults to currently active scalars.
factor : float, optional
A scaling factor to increase the scaling effect. Alias
``scale_factor`` also accepted - if present, overrides ``factor``.
normal : np.array, list, tuple of length 3
User specified normal. If given, data normals will be ignored and
the given normal will be used to project the warp.
inplace : bool
If True, the points of the give dataset will be updated.
"""
factor = kwargs.pop('scale_factor', factor)
assert_empty_kwargs(**kwargs)
if scalars is None:
field, scalars = dataset.active_scalars_info
arr, field = get_array(dataset, scalars, preference='point', info=True)
if field != FieldAssociation.POINT:
raise TypeError('Dataset can only by warped by a point data array.')
# Run the algorithm
alg = vtk.vtkWarpScalar()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
alg.SetScaleFactor(factor)
if normal is not None:
alg.SetNormal(normal)
alg.SetUseNormal(True)
alg.Update()
output = _get_output(alg)
if inplace:
if isinstance(dataset, (vtk.vtkImageData, vtk.vtkRectilinearGrid)):
raise TypeError("This filter cannot be applied inplace for this mesh type.")
dataset.overwrite(output)
return
return output
def warp_by_vector(dataset, vectors=None, factor=1.0, inplace=False):
"""Warp the dataset's points by a point data vectors array's values.
This modifies point coordinates by moving points along point vectors by
the local vector times the scale factor.
A classical application of this transform is to visualize eigenmodes in
mechanics.
Parameters
----------
vectors : str, optional
Name of vector to warp by. Defaults to currently active vector.
factor : float, optional
A scaling factor that multiplies the vectors to warp by. Can
be used to enhance the warping effect.
inplace : bool, optional
If True, the function will update the mesh in-place and
return ``None``.
Returns
-------
warped_mesh : mesh
The warped mesh resulting from the operation.
"""
if vectors is None:
field, vectors = dataset.active_vectors_info
arr, field = get_array(dataset, vectors, preference='point', info=True)
if arr is None:
raise TypeError('No active vectors')
# check that this is indeed a vector field
if arr.ndim != 2 or arr.shape[1] != 3:
raise ValueError(
'Dataset can only by warped by a 3D vector point data array.' + \
'The values you provided do not satisfy this requirement')
alg = vtk.vtkWarpVector()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field.value, vectors)
alg.SetScaleFactor(factor)
alg.Update()
warped_mesh = _get_output(alg)
if inplace:
dataset.overwrite(warped_mesh)
return
return warped_mesh
def cell_data_to_point_data(dataset, pass_cell_data=False):
"""Transform cell data into point data.
Point data are specified per node and cell data specified within cells.
Optionally, the input point data can be passed through to the output.
The method of transformation is based on averaging the data values of
all cells using a particular point. Optionally, the input cell data can
be passed through to the output as well.
See also: :func:`pyvista.DataSetFilters.point_data_to_cell_data`
Parameters
----------
pass_cell_data : bool
If enabled, pass the input cell data through to the output
"""
alg = vtk.vtkCellDataToPointData()
alg.SetInputDataObject(dataset)
alg.SetPassCellData(pass_cell_data)
alg.Update()
active_scalars = None
if not isinstance(dataset, pyvista.MultiBlock):
active_scalars = dataset.active_scalars_name
return _get_output(alg, active_scalars=active_scalars)
def ctp(dataset, pass_cell_data=False):
"""Transform cell data into point data.
Point data are specified per node and cell data specified within cells.
Optionally, the input point data can be passed through to the output.
An alias/shortcut for ``cell_data_to_point_data``.
"""
return DataSetFilters.cell_data_to_point_data(dataset, pass_cell_data=pass_cell_data)
def point_data_to_cell_data(dataset, pass_point_data=False):
"""Transform point data into cell data.
Point data are specified per node and cell data specified within cells.
Optionally, the input point data can be passed through to the output.
See also: :func:`pyvista.DataSetFilters.cell_data_to_point_data`
Parameters
----------
pass_point_data : bool
If enabled, pass the input point data through to the output
"""
alg = vtk.vtkPointDataToCellData()
alg.SetInputDataObject(dataset)
alg.SetPassPointData(pass_point_data)
alg.Update()
active_scalars = None
if not isinstance(dataset, pyvista.MultiBlock):
active_scalars = dataset.active_scalars_name
return _get_output(alg, active_scalars=active_scalars)
def ptc(dataset, pass_point_data=False):
"""Transform point data into cell data.
Point data are specified per node and cell data specified within cells.
Optionally, the input point data can be passed through to the output.
An alias/shortcut for ``point_data_to_cell_data``.
"""
return DataSetFilters.point_data_to_cell_data(dataset, pass_point_data=pass_point_data)
def triangulate(dataset, inplace=False):
"""Return an all triangle mesh.
More complex polygons will be broken down into triangles.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning ``None``.
Return
------
mesh : pyvista.UnstructuredGrid
Mesh containing only triangles. ``None`` when ``inplace=True``
"""
alg = vtk.vtkDataSetTriangleFilter()
alg.SetInputData(dataset)
alg.Update()
mesh = _get_output(alg)
if inplace:
dataset.overwrite(mesh)
else:
return mesh
def delaunay_3d(dataset, alpha=0, tol=0.001, offset=2.5, progress_bar=False):
"""Construct a 3D Delaunay triangulation of the mesh.
This helps smooth out a rugged mesh.
Parameters
----------
alpha : float, optional
Distance value to control output of this filter. For a non-zero
alpha value, only verts, edges, faces, or tetra contained within
the circumsphere (of radius alpha) will be output. Otherwise, only
tetrahedra will be output.
tol : float, optional
tolerance to control discarding of closely spaced points.
This tolerance is specified as a fraction of the diagonal length
of the bounding box of the points.
offset : float, optional
multiplier to control the size of the initial, bounding Delaunay
triangulation.
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
alg = vtk.vtkDelaunay3D()
alg.SetInputData(dataset)
alg.SetAlpha(alpha)
alg.SetTolerance(tol)
alg.SetOffset(offset)
_update_alg(alg, progress_bar, 'Computing 3D Triangulation')
return _get_output(alg)
def select_enclosed_points(dataset, surface, tolerance=0.001,
inside_out=False, check_surface=True):
"""Mark points as to whether they are inside a closed surface.
This evaluates all the input points to determine whether they are in an
enclosed surface. The filter produces a (0,1) mask
(in the form of a vtkDataArray) that indicates whether points are
outside (mask value=0) or inside (mask value=1) a provided surface.
(The name of the output vtkDataArray is "SelectedPoints".)
This filter produces and output data array, but does not modify the
input dataset. If you wish to extract cells or poinrs, various
threshold filters are available (i.e., threshold the output array).
Warning
-------
The filter assumes that the surface is closed and manifold. A boolean
flag can be set to force the filter to first check whether this is
true. If false, all points will be marked outside. Note that if this
check is not performed and the surface is not closed, the results are
undefined.
Parameters
----------
surface : pyvista.PolyData
Set the surface to be used to test for containment. This must be a
:class:`pyvista.PolyData` object.
tolerance : float
The tolerance on the intersection. The tolerance is expressed as a
fraction of the bounding box of the enclosing surface.
inside_out : bool
By default, points inside the surface are marked inside or sent
to the output. If ``inside_out`` is ``True``, then the points
outside the surface are marked inside.
check_surface : bool
Specify whether to check the surface for closure. If on, then the
algorithm first checks to see if the surface is closed and
manifold. If the surface is not closed and manifold, a runtime
error is raised.
"""
if not isinstance(surface, pyvista.PolyData):
raise TypeError("`surface` must be `pyvista.PolyData`")
if check_surface and surface.n_open_edges > 0:
raise RuntimeError("Surface is not closed. Please read the warning in the documentation for this function and either pass `check_surface=False` or repair the surface.")
alg = vtk.vtkSelectEnclosedPoints()
alg.SetInputData(dataset)
alg.SetSurfaceData(surface)
alg.SetTolerance(tolerance)
alg.SetInsideOut(inside_out)
alg.Update()
result = _get_output(alg)
out = dataset.copy()
bools = result['SelectedPoints'].astype(np.uint8)
if len(bools) < 1:
bools = np.zeros(out.n_points, dtype=np.uint8)
out['SelectedPoints'] = bools
return out
def probe(dataset, points, tolerance=None, pass_cell_arrays=True,
pass_point_arrays=True, categorical=False):
"""Sample data values at specified point locations.
This uses :class:`vtk.vtkProbeFilter`.
Parameters
----------
dataset: pyvista.Common
The mesh to probe from - point and cell arrays from
this object are probed onto the nodes of the ``points`` mesh
points: pyvista.Common
The points to probe values on to. This should be a PyVista mesh
or something :func:`pyvista.wrap` can handle.
tolerance: float, optional
Tolerance used to compute whether a point in the source is in a
cell of the input. If not given, tolerance is automatically generated.
pass_cell_arrays: bool, optional
Preserve source mesh's original cell data arrays
pass_point_arrays: bool, optional
Preserve source mesh's original point data arrays
categorical : bool, optional
Control whether the source point data is to be treated as
categorical. If the data is categorical, then the resultant data
will be determined by a nearest neighbor interpolation scheme.
Examples
--------
Probe the active scalars in ``grid`` at the points in ``mesh``
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = pyvista.Sphere(center=(4.5, 4.5, 4.5), radius=4.5)
>>> grid = examples.load_uniform()
>>> result = grid.probe(mesh)
>>> 'Spatial Point Data' in result.point_arrays
True
"""
if not pyvista.is_pyvista_dataset(points):
points = pyvista.wrap(points)
alg = vtk.vtkProbeFilter()
alg.SetInputData(points)
alg.SetSourceData(dataset)
alg.SetPassCellArrays(pass_cell_arrays)
alg.SetPassPointArrays(pass_point_arrays)
alg.SetCategoricalData(categorical)
if tolerance is not None:
alg.SetComputeTolerance(False)
alg.SetTolerance(tolerance)
alg.Update() # Perform the resampling
return _get_output(alg)
def sample(dataset, target, tolerance=None, pass_cell_arrays=True,
pass_point_arrays=True, categorical=False):
"""Resample array data from a passed mesh onto this mesh.
This uses :class:`vtk.vtkResampleWithDataSet`.
Parameters
----------
dataset: pyvista.Common
The source vtk data object as the mesh to sample values on to
target: pyvista.Common
The vtk data object to sample from - point and cell arrays from
this object are sampled onto the nodes of the ``dataset`` mesh
tolerance: float, optional
Tolerance used to compute whether a point in the source is in a
cell of the input. If not given, tolerance is automatically generated.
pass_cell_arrays: bool, optional
Preserve source mesh's original cell data arrays
pass_point_arrays: bool, optional
Preserve source mesh's original point data arrays
categorical : bool, optional
Control whether the source point data is to be treated as
categorical. If the data is categorical, then the resultant data
will be determined by a nearest neighbor interpolation scheme.
"""
if not pyvista.is_pyvista_dataset(target):
raise TypeError('`target` must be a PyVista mesh type.')
alg = vtk.vtkResampleWithDataSet() # Construct the ResampleWithDataSet object
alg.SetInputData(dataset) # Set the Input data (actually the source i.e. where to sample from)
alg.SetSourceData(target) # Set the Source data (actually the target, i.e. where to sample to)
alg.SetPassCellArrays(pass_cell_arrays)
alg.SetPassPointArrays(pass_point_arrays)
alg.SetCategoricalData(categorical)
if tolerance is not None:
alg.SetComputeTolerance(False)
alg.SetTolerance(tolerance)
alg.Update() # Perform the resampling
return _get_output(alg)
def interpolate(dataset, target, sharpness=2, radius=1.0,
strategy='null_value', null_value=0.0, n_points=None,
pass_cell_arrays=True, pass_point_arrays=True,
progress_bar=False, ):
"""Interpolate values onto this mesh from a given dataset.
The input dataset is typically a point cloud.
This uses a gaussian interpolation kernel. Use the ``sharpness`` and
``radius`` parameters to adjust this kernel. You can also switch this
kernel to use an N closest points approach.
Parameters
----------
target: pyvista.Common
The vtk data object to sample from - point and cell arrays from
this object are interpolated onto this mesh.
sharpness : float
Set / Get the sharpness (i.e., falloff) of the Gaussian. By
default Sharpness=2. As the sharpness increases the effects of
distant points are reduced.
radius : float
Specify the radius within which the basis points must lie.
n_points : int, optional
If given, specifies the number of the closest points used to form
the interpolation basis. This will invalidate the radius and
sharpness arguments in favor of an N closest points approach. This
typically has poorer results.
strategy : str, optional
Specify a strategy to use when encountering a "null" point during
the interpolation process. Null points occur when the local
neighborhood (of nearby points to interpolate from) is empty. If
the strategy is set to ``'mask_points'``, then an output array is
created that marks points as being valid (=1) or null (invalid
=0) (and the NullValue is set as well). If the strategy is set to
``'null_value'`` (this is the default), then the output data
value(s) are set to the ``null_value`` (specified in the output
point data). Finally, the strategy ``'closest_point'`` is to simply
use the closest point to perform the interpolation.
null_value : float, optional
Specify the null point value. When a null point is encountered
then all components of each null tuple are set to this value. By
default the null value is set to zero.
pass_cell_arrays: bool, optional
Preserve input mesh's original cell data arrays
pass_point_arrays: bool, optional
Preserve input mesh's original point data arrays
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
if not pyvista.is_pyvista_dataset(target):
raise TypeError('`target` must be a PyVista mesh type.')
# Must cast to UnstructuredGrid in some cases (e.g. vtkImageData/vtkRectilinearGrid)
# I believe the locator and the interpolator call `GetPoints` and not all mesh types have that method
if isinstance(target, (pyvista.UniformGrid, pyvista.RectilinearGrid)):
target = target.cast_to_unstructured_grid()
gaussian_kernel = vtk.vtkGaussianKernel()
gaussian_kernel.SetSharpness(sharpness)
gaussian_kernel.SetRadius(radius)
gaussian_kernel.SetKernelFootprintToRadius()
if n_points:
gaussian_kernel.SetNumberOfPoints(n_points)
gaussian_kernel.SetKernelFootprintToNClosest()
locator = vtk.vtkStaticPointLocator()
locator.SetDataSet(target)
locator.BuildLocator()
interpolator = vtk.vtkPointInterpolator()
interpolator.SetInputData(dataset)
interpolator.SetSourceData(target)
interpolator.SetKernel(gaussian_kernel)
interpolator.SetLocator(locator)
interpolator.SetNullValue(null_value)
if strategy == 'null_value':
interpolator.SetNullPointsStrategyToNullValue()
elif strategy == 'mask_points':
interpolator.SetNullPointsStrategyToMaskPoints()
elif strategy == 'closest_point':
interpolator.SetNullPointsStrategyToClosestPoint()
else:
raise ValueError(f'strategy `{strategy}` not supported.')
interpolator.SetPassPointArrays(pass_point_arrays)
interpolator.SetPassCellArrays(pass_cell_arrays)
_update_alg(interpolator, progress_bar, 'Interpolating')
return _get_output(interpolator)
def streamlines(dataset, vectors=None, source_center=None,
source_radius=None, n_points=100,
integrator_type=45, integration_direction='both',
surface_streamlines=False, initial_step_length=0.5,
step_unit='cl', min_step_length=0.01, max_step_length=1.0,
max_steps=2000, terminal_speed=1e-12, max_error=1e-6,
max_time=None, compute_vorticity=True, rotation_scale=1.0,
interpolator_type='point', start_position=(0.0, 0.0, 0.0),
return_source=False, pointa=None, pointb=None):
"""Integrate a vector field to generate streamlines.
The integration is performed using a specified integrator, by default
Runge-Kutta2. This supports integration through any type of dataset.
Thus if the dataset contains 2D cells like polygons or triangles, the
integration is constrained to lie on the surface defined by 2D cells.
This produces polylines as the output, with each cell
(i.e., polyline) representing a streamline. The attribute values
associated with each streamline are stored in the cell data, whereas
those associated with streamline-points are stored in the point data.
This uses a Sphere as the source - set it's location and radius via
the ``source_center`` and ``source_radius`` keyword arguments.
You can retrieve the source as :class:`pyvista.PolyData` by specifying
``return_source=True``.
Parameters
----------
vectors : str
The string name of the active vector field to integrate across
source_center : tuple(float)
Length 3 tuple of floats defining the center of the source
particles. Defaults to the center of the dataset
source_radius : float
Float radius of the source particle cloud. Defaults to one-tenth of
the diagonal of the dataset's spatial extent
n_points : int
Number of particles present in source sphere
integrator_type : int
The integrator type to be used for streamline generation.
The default is Runge-Kutta45. The recognized solvers are:
RUNGE_KUTTA2 (``2``), RUNGE_KUTTA4 (``4``), and RUNGE_KUTTA45
(``45``). Options are ``2``, ``4``, or ``45``. Default is ``45``.
integration_direction : str
Specify whether the streamline is integrated in the upstream or
downstream directions (or both). Options are ``'both'``,
``'backward'``, or ``'forward'``.
surface_streamlines : bool
Compute streamlines on a surface. Default ``False``
initial_step_length : float
Initial step size used for line integration, expressed ib length
unitsL or cell length units (see ``step_unit`` parameter).
either the starting size for an adaptive integrator, e.g., RK45, or
the constant / fixed size for non-adaptive ones, i.e., RK2 and RK4)
step_unit : str
Uniform integration step unit. The valid unit is now limited to
only LENGTH_UNIT (``'l'``) and CELL_LENGTH_UNIT (``'cl'``).
Default is CELL_LENGTH_UNIT: ``'cl'``.
min_step_length : float
Minimum step size used for line integration, expressed in length or
cell length units. Only valid for an adaptive integrator, e.g., RK45
max_step_length : float
Maximum step size used for line integration, expressed in length or
cell length units. Only valid for an adaptive integrator, e.g., RK45
max_steps : int
Maximum number of steps for integrating a streamline.
Defaults to ``2000``
terminal_speed : float
Terminal speed value, below which integration is terminated.
max_error : float
Maximum error tolerated throughout streamline integration.
max_time : float
Specify the maximum length of a streamline expressed in LENGTH_UNIT.
compute_vorticity : bool
Vorticity computation at streamline points (necessary for generating
proper stream-ribbons using the ``vtkRibbonFilter``.
interpolator_type : str
Set the type of the velocity field interpolator to locate cells
during streamline integration either by points or cells.
The cell locator is more robust then the point locator. Options
are ``'point'`` or ``'cell'`` (abbreviations of ``'p'`` and ``'c'``
are also supported).
rotation_scale : float
This can be used to scale the rate with which the streamribbons
twist. The default is 1.
start_position : tuple(float)
Set the start position. Default is ``(0.0, 0.0, 0.0)``
return_source : bool
Return the source particles as :class:`pyvista.PolyData` as well as the
streamlines. This will be the second value returned if ``True``.
pointa, pointb : tuple(float)
The coordinates of a start and end point for a line source. This
will override the sphere point source.
"""
integration_direction = str(integration_direction).strip().lower()
if integration_direction not in ['both', 'back', 'backward', 'forward']:
raise ValueError(f"integration direction must be one of: 'backward', 'forward', or 'both' - not '{integration_direction}'.")
if integrator_type not in [2, 4, 45]:
raise ValueError('integrator type must be one of `2`, `4`, or `45`.')
if interpolator_type not in ['c', 'cell', 'p', 'point']:
raise ValueError("interpolator type must be either 'cell' or 'point'")
if step_unit not in ['l', 'cl']:
raise ValueError("step unit must be either 'l' or 'cl'")
step_unit = {'cl': vtk.vtkStreamTracer.CELL_LENGTH_UNIT,
'l': vtk.vtkStreamTracer.LENGTH_UNIT}[step_unit]
if isinstance(vectors, str):
dataset.set_active_scalars(vectors)
dataset.set_active_vectors(vectors)
if max_time is None:
max_velocity = dataset.get_data_range()[-1]
max_time = 4.0 * dataset.GetLength() / max_velocity
# Generate the source
if source_center is None:
source_center = dataset.center
if source_radius is None:
source_radius = dataset.length / 10.0
if pointa is not None and pointb is not None:
source = vtk.vtkLineSource()
source.SetPoint1(pointa)
source.SetPoint2(pointb)
source.SetResolution(n_points)
else:
source = vtk.vtkPointSource()
source.SetCenter(source_center)
source.SetRadius(source_radius)
source.SetNumberOfPoints(n_points)
# Build the algorithm
alg = vtk.vtkStreamTracer()
# Inputs
alg.SetInputDataObject(dataset)
# NOTE: not sure why we can't pass a PolyData object
# setting the connection is the only I could get it to work
alg.SetSourceConnection(source.GetOutputPort())
# general parameters
alg.SetComputeVorticity(compute_vorticity)
alg.SetInitialIntegrationStep(initial_step_length)
alg.SetIntegrationStepUnit(step_unit)
alg.SetMaximumError(max_error)
alg.SetMaximumIntegrationStep(max_step_length)
alg.SetMaximumNumberOfSteps(max_steps)
alg.SetMaximumPropagation(max_time)
alg.SetMinimumIntegrationStep(min_step_length)
alg.SetRotationScale(rotation_scale)
alg.SetStartPosition(start_position)
alg.SetSurfaceStreamlines(surface_streamlines)
alg.SetTerminalSpeed(terminal_speed)
# Model parameters
if integration_direction == 'forward':
alg.SetIntegrationDirectionToForward()
elif integration_direction in ['backward', 'back']:
alg.SetIntegrationDirectionToBackward()
else:
alg.SetIntegrationDirectionToBoth()
# set integrator type
if integrator_type == 2:
alg.SetIntegratorTypeToRungeKutta2()
elif integrator_type == 4:
alg.SetIntegratorTypeToRungeKutta4()
else:
alg.SetIntegratorTypeToRungeKutta45()
# set interpolator type
if interpolator_type in ['c', 'cell']:
alg.SetInterpolatorTypeToCellLocator()
else:
alg.SetInterpolatorTypeToDataSetPointLocator()
# run the algorithm
alg.Update()
output = _get_output(alg)
if return_source:
source.Update()
src = pyvista.wrap(source.GetOutput())
return output, src
return output
def decimate_boundary(dataset, target_reduction=0.5):
"""Return a decimated version of a triangulation of the boundary.
Only the outer surface of the input dataset will be considered.
Parameters
----------
target_reduction : float
Fraction of the original mesh to remove. Default is ``0.5``
TargetReduction is set to ``0.9``, this filter will try to reduce
the data set to 10% of its original size and will remove 90%
of the input triangles.
"""
return dataset.extract_geometry().triangulate().decimate(target_reduction)
def sample_over_line(dataset, pointa, pointb, resolution=None, tolerance=None):
"""Sample a dataset onto a line.
Parameters
----------
pointa : np.ndarray or list
Location in [x, y, z].
pointb : np.ndarray or list
Location in [x, y, z].
resolution : int
Number of pieces to divide line into. Defaults to number of cells
in the input mesh. Must be a positive integer.
tolerance: float, optional
Tolerance used to compute whether a point in the source is in a
cell of the input. If not given, tolerance is automatically generated.
Return
------
sampled_line : pv.PolyData
Line object with sampled data from dataset.
"""
if resolution is None:
resolution = int(dataset.n_cells)
# Make a line and sample the dataset
line = pyvista.Line(pointa, pointb, resolution=resolution)
sampled_line = line.sample(dataset, tolerance=tolerance)
return sampled_line
def plot_over_line(dataset, pointa, pointb, resolution=None, scalars=None,
title=None, ylabel=None, figsize=None, figure=True,
show=True, tolerance=None):
"""Sample a dataset along a high resolution line and plot.
Plot the variables of interest in 2D where the X-axis is distance from
Point A and the Y-axis is the variable of interest. Note that this filter
returns None.
Parameters
----------
pointa : np.ndarray or list
Location in [x, y, z].
pointb : np.ndarray or list
Location in [x, y, z].
resolution : int
number of pieces to divide line into. Defaults to number of cells
in the input mesh. Must be a positive integer.
scalars : str
The string name of the variable in the input dataset to probe. The
active scalar is used by default.
title : str
The string title of the `matplotlib` figure
ylabel : str
The string label of the Y-axis. Defaults to variable name
figsize : tuple(int)
the size of the new figure
figure : bool
flag on whether or not to create a new figure
show : bool
Shows the matplotlib figure
tolerance: float, optional
Tolerance used to compute whether a point in the source is in a
cell of the input. If not given, tolerance is automatically generated.
"""
# Ensure matplotlib is available
try:
import matplotlib.pyplot as plt
except ImportError: # pragma: no cover
raise ImportError('matplotlib must be available to use this filter.')
# Sample on line
sampled = DataSetFilters.sample_over_line(dataset, pointa, pointb, resolution, tolerance)
# Get variable of interest
if scalars is None:
field, scalars = dataset.active_scalars_info
values = sampled.get_array(scalars)
distance = sampled['Distance']
# Remainder is plotting
if figure:
plt.figure(figsize=figsize)
# Plot it in 2D
if values.ndim > 1:
for i in range(values.shape[1]):
plt.plot(distance, values[:, i], label=f'Component {i}')
plt.legend()
else:
plt.plot(distance, values)
plt.xlabel('Distance')
if ylabel is None:
plt.ylabel(scalars)
else:
plt.ylabel(ylabel)
if title is None:
plt.title(f'{scalars} Profile')
else:
plt.title(title)
if show: # pragma: no cover
return plt.show()
def extract_cells(dataset, ind):
"""Return a subset of the grid.
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Return
------
subgrid : pyvista.UnstructuredGrid
Subselected grid
"""
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
selectionNode.SetSelectionList(numpy_to_idarr(ind))
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, dataset)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
subgrid = _get_output(extract_sel)
# extracts only in float32
if dataset.points.dtype is not np.dtype('float32'):
ind = subgrid.point_arrays['vtkOriginalPointIds']
subgrid.points = dataset.points[ind]
return subgrid
def extract_points(dataset, ind, adjacent_cells=True):
"""Return a subset of the grid (with cells) that contains any of the given point indices.
Parameters
----------
ind : np.ndarray, list, or sequence
Numpy array of point indices to be extracted.
adjacent_cells : bool, optional
If True, extract the cells that contain at least one of the
extracted points. If False, extract the cells that contain
exclusively points from the extracted points list. The default is
True.
Return
------
subgrid : pyvista.UnstructuredGrid
Subselected grid.
"""
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
if not adjacent_cells:
# Build array of point indices to be removed.
ind_rem = np.ones(dataset.n_points, dtype='bool')
ind_rem[ind] = False
ind = np.arange(dataset.n_points)[ind_rem]
# Invert selection
selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
selectionNode.SetSelectionList(numpy_to_idarr(ind))
selectionNode.GetProperties().Set(vtk.vtkSelectionNode.CONTAINING_CELLS(), 1)
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, dataset)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
return _get_output(extract_sel)
def extract_surface(dataset, pass_pointid=True, pass_cellid=True, inplace=False):
"""Extract surface mesh of the grid.
Parameters
----------
pass_pointid : bool, optional
Adds a point array "vtkOriginalPointIds" that idenfities which
original points these surface points correspond to
pass_cellid : bool, optional
Adds a cell array "vtkOriginalPointIds" that idenfities which
original cells these surface cells correspond to
Return
------
extsurf : pyvista.PolyData
Surface mesh of the grid
"""
surf_filter = vtk.vtkDataSetSurfaceFilter()
surf_filter.SetInputData(dataset)
if pass_pointid:
surf_filter.PassThroughCellIdsOn()
if pass_cellid:
surf_filter.PassThroughPointIdsOn()
surf_filter.Update()
# need to add
# surf_filter.SetNonlinearSubdivisionLevel(subdivision)
mesh = _get_output(surf_filter)
return mesh
def surface_indices(dataset):
"""Return the surface indices of a grid.
Return
------
surf_ind : np.ndarray
Indices of the surface points.
"""
surf = DataSetFilters.extract_surface(dataset, pass_cellid=True)
return surf.point_arrays['vtkOriginalPointIds']
def extract_feature_edges(dataset, feature_angle=30, boundary_edges=True,
non_manifold_edges=True, feature_edges=True,
manifold_edges=True, inplace=False):
"""Extract edges from the surface of the mesh.
If the given mesh is not PolyData, the external surface of the given
mesh is extracted and used.
From vtk documentation, the edges are one of the following
1) boundary (used by one polygon) or a line cell
2) non-manifold (used by three or more polygons)
3) feature edges (edges used by two triangles and whose
dihedral angle > feature_angle)
4) manifold edges (edges used by exactly two polygons).
Parameters
----------
feature_angle : float, optional
Defaults to 30 degrees.
boundary_edges : bool, optional
Defaults to True
non_manifold_edges : bool, optional
Defaults to True
feature_edges : bool, optional
Defaults to True
manifold_edges : bool, optional
Defaults to True
inplace : bool, optional
Return new mesh or overwrite input.
Return
------
edges : pyvista.vtkPolyData
Extracted edges. None if inplace=True.
"""
if not isinstance(dataset, vtk.vtkPolyData):
dataset = DataSetFilters.extract_surface(dataset)
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(dataset)
featureEdges.SetFeatureAngle(feature_angle)
featureEdges.SetManifoldEdges(manifold_edges)
featureEdges.SetNonManifoldEdges(non_manifold_edges)
featureEdges.SetBoundaryEdges(boundary_edges)
featureEdges.SetFeatureEdges(feature_edges)
featureEdges.SetColoring(False)
featureEdges.Update()
mesh = _get_output(featureEdges)
if inplace:
dataset.overwrite(mesh)
else:
return mesh
def merge(dataset, grid=None, merge_points=True, inplace=False,
main_has_priority=True):
"""Join one or many other grids to this grid.
Grid is updated in-place by default.
Can be used to merge points of adjacent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes. Warning: this can leave degenerate point data.
inplace : bool, optional
Updates grid inplace when True if the input type is an
:class:`pyvista.UnstructuredGrid`.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the arrays of the merging grids will be overwritten
by the original main mesh.
Return
------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
array must match or the arrays will be ignored and not
included in the final merged mesh.
"""
append_filter = vtk.vtkAppendFilter()
append_filter.SetMergePoints(merge_points)
if not main_has_priority:
append_filter.AddInputData(dataset)
if isinstance(grid, pyvista.Common):
append_filter.AddInputData(grid)
elif isinstance(grid, (list, tuple, pyvista.MultiBlock)):
grids = grid
for grid in grids:
append_filter.AddInputData(grid)
if main_has_priority:
append_filter.AddInputData(dataset)
append_filter.Update()
merged = _get_output(append_filter)
if inplace:
if type(dataset) == type(merged):
dataset.deep_copy(merged)
else:
raise TypeError(f"Mesh type {type(dataset)} cannot be overridden by output.")
else:
return merged
def __add__(dataset, grid):
"""Combine this mesh with another into an :class:`pyvista.UnstructuredGrid`."""
return DataSetFilters.merge(dataset, grid)
def compute_cell_quality(dataset, quality_measure='scaled_jacobian', null_value=-1.0):
"""Compute a function of (geometric) quality for each cell of a mesh.
The per-cell quality is added to the mesh's cell data, in an array
named "CellQuality". Cell types not supported by this filter or
undefined quality of supported cell types will have an entry of -1.
Defaults to computing the scaled jacobian.
Options for cell quality measure:
- ``'area'``
- ``'aspect_beta'``
- ``'aspect_frobenius'``
- ``'aspect_gamma'``
- ``'aspect_ratio'``
- ``'collapse_ratio'``
- ``'condition'``
- ``'diagonal'``
- ``'dimension'``
- ``'distortion'``
- ``'jacobian'``
- ``'max_angle'``
- ``'max_aspect_frobenius'``
- ``'max_edge_ratio'``
- ``'med_aspect_frobenius'``
- ``'min_angle'``
- ``'oddy'``
- ``'radius_ratio'``
- ``'relative_size_squared'``
- ``'scaled_jacobian'``
- ``'shape'``
- ``'shape_and_size'``
- ``'shear'``
- ``'shear_and_size'``
- ``'skew'``
- ``'stretch'``
- ``'taper'``
- ``'volume'``
- ``'warpage'``
Parameters
----------
quality_measure : str
The cell quality measure to use
null_value : float
Float value for undefined quality. Undefined quality are qualities
that could be addressed by this filter but is not well defined for
the particular geometry of cell in question, e.g. a volume query
for a triangle. Undefined quality will always be undefined.
The default value is -1.
"""
alg = vtk.vtkCellQuality()
measure_setters = {
'area': alg.SetQualityMeasureToArea,
'aspect_beta': alg.SetQualityMeasureToAspectBeta,
'aspect_frobenius': alg.SetQualityMeasureToAspectFrobenius,
'aspect_gamma': alg.SetQualityMeasureToAspectGamma,
'aspect_ratio': alg.SetQualityMeasureToAspectRatio,
'collapse_ratio': alg.SetQualityMeasureToCollapseRatio,
'condition': alg.SetQualityMeasureToCondition,
'diagonal': alg.SetQualityMeasureToDiagonal,
'dimension': alg.SetQualityMeasureToDimension,
'distortion': alg.SetQualityMeasureToDistortion,
'jacobian': alg.SetQualityMeasureToJacobian,
'max_angle': alg.SetQualityMeasureToMaxAngle,
'max_aspect_frobenius': alg.SetQualityMeasureToMaxAspectFrobenius,
'max_edge_ratio': alg.SetQualityMeasureToMaxEdgeRatio,
'med_aspect_frobenius': alg.SetQualityMeasureToMedAspectFrobenius,
'min_angle': alg.SetQualityMeasureToMinAngle,
'oddy': alg.SetQualityMeasureToOddy,
'radius_ratio': alg.SetQualityMeasureToRadiusRatio,
'relative_size_squared': alg.SetQualityMeasureToRelativeSizeSquared,
'scaled_jacobian': alg.SetQualityMeasureToScaledJacobian,
'shape': alg.SetQualityMeasureToShape,
'shape_and_size': alg.SetQualityMeasureToShapeAndSize,
'shear': alg.SetQualityMeasureToShear,
'shear_and_size': alg.SetQualityMeasureToShearAndSize,
'skew': alg.SetQualityMeasureToSkew,
'stretch': alg.SetQualityMeasureToStretch,
'taper': alg.SetQualityMeasureToTaper,
'volume': alg.SetQualityMeasureToVolume,
'warpage': alg.SetQualityMeasureToWarpage
}
try:
# Set user specified quality measure
measure_setters[quality_measure]()
except (KeyError, IndexError):
options = ', '.join([f"'{s}'" for s in list(measure_setters.keys())])
raise KeyError(f'Cell quality type ({quality_measure}) not available. Options are: {options}')
alg.SetInputData(dataset)
alg.SetUndefinedQuality(null_value)
alg.Update()
return _get_output(alg)
def compute_derivative(dataset, scalars=None, gradient=True,
divergence=None, vorticity=None, qcriterion=None,
faster=False, preference='point'):
"""Compute derivative-based quantities of point/cell scalar field.
Utilize ``vtkGradientFilter`` to compute derivative-based quantities,
such as gradient, divergence, vorticity, and Q-criterion, of the
selected point or cell scalar field.
Parameters
----------
scalars : str, optional
String name of the scalars array to use when computing the
derivative quantities.
gradient: bool, str, optional
Calculate gradient. If a string is passed, the string will be used
for the resulting array name. Otherwise, array name will be
'gradient'. Default: True
divergence: bool, str, optional
Calculate divergence. If a string is passed, the string will be
used for the resulting array name. Otherwise, array name will be
'divergence'. Default: None
vorticity: bool, str, optional
Calculate vorticity. If a string is passed, the string will be used
for the resulting array name. Otherwise, array name will be
'vorticity'. Default: None
qcriterion: bool, str, optional
Calculate qcriterion. If a string is passed, the string will be
used for the resulting array name. Otherwise, array name will be
'qcriterion'. Default: None
faster: bool, optional
Use faster algorithm for computing derivative quantities. Result is
less accurate and performs fewer derivative calculations,
increasing computation speed. The error will feature smoothing of
the output and possibly errors at boundaries. Option has no effect
if DataSet is not UnstructuredGrid. Default: False
preference: str, optional
Data type preference. Either 'point' or 'cell'.
"""
alg = vtk.vtkGradientFilter()
# Check if scalars array given
if scalars is None:
field, scalars = dataset.active_scalars_info
if scalars is None:
raise TypeError('No active scalars. Must input scalars array name')
if not isinstance(scalars, str):
raise TypeError('scalars array must be given as a string name')
if not any((gradient, divergence, vorticity, qcriterion)):
raise ValueError('must set at least one of gradient, divergence, vorticity, or qcriterion')
# bool(non-empty string/True) == True, bool(None/False) == False
alg.SetComputeGradient(bool(gradient))
if isinstance(gradient, bool):
gradient = 'gradient'
alg.SetResultArrayName(gradient)
alg.SetComputeDivergence(bool(divergence))
if isinstance(divergence, bool):
divergence = 'divergence'
alg.SetDivergenceArrayName(divergence)
alg.SetComputeVorticity(bool(vorticity))
if isinstance(vorticity, bool):
vorticity = 'vorticity'
alg.SetVorticityArrayName(vorticity)
alg.SetComputeQCriterion(bool(qcriterion))
if isinstance(qcriterion, bool):
qcriterion = 'qcriterion'
alg.SetQCriterionArrayName(qcriterion)
alg.SetFasterApproximation(faster)
_, field = dataset.get_array(scalars, preference=preference, info=True)
# args: (idx, port, connection, field, name)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
alg.SetInputData(dataset)
alg.Update()
return _get_output(alg)
def shrink(dataset, shrink_factor=1.0, progress_bar=False):
"""Shrink the individual faces of a mesh.
This filter shrinks the individual faces of a mesh rather than scaling
the entire mesh.
Parameters
----------
shrink_factor : float, optional
fraction of shrink for each cell.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Examples
--------
Extrude shrink mesh
>>> import pyvista
>>> mesh = pyvista.Sphere()
>>> shrunk_mesh = mesh.shrink(shrink_factor=0.8) # doctest:+SKIP
"""
if not (0.0 <= shrink_factor <= 1.0):
raise ValueError('`shrink_factor` should be between 0.0 and 1.0')
alg = vtk.vtkShrinkFilter()
alg.SetInputData(dataset)
alg.SetShrinkFactor(shrink_factor)
_update_alg(alg, progress_bar, 'Shrinking Mesh')
output = pyvista.wrap(alg.GetOutput())
if isinstance(dataset, vtk.vtkPolyData):
return output.extract_surface()
@abstract_class
class CompositeFilters:
"""An internal class to manage filtes/algorithms for composite datasets."""
def extract_geometry(composite):
"""Combine the geomertry of all blocks into a single ``PolyData`` object.
Place this filter at the end of a pipeline before a polydata
consumer such as a polydata mapper to extract geometry from all blocks
and append them to one polydata object.
"""
gf = vtk.vtkCompositeDataGeometryFilter()
gf.SetInputData(composite)
gf.Update()
return wrap(gf.GetOutputDataObject(0))
def combine(composite, merge_points=False):
"""Append all blocks into a single unstructured grid.
Parameters
----------
merge_points : bool, optional
Merge coincidental points.
"""
alg = vtk.vtkAppendFilter()
for block in composite:
if isinstance(block, vtk.vtkMultiBlockDataSet):
block = CompositeFilters.combine(block, merge_points=merge_points)
alg.AddInputData(block)
alg.SetMergePoints(merge_points)
alg.Update()
return wrap(alg.GetOutputDataObject(0))
clip = DataSetFilters.clip
clip_box = DataSetFilters.clip_box
slice = DataSetFilters.slice
slice_orthogonal = DataSetFilters.slice_orthogonal
slice_along_axis = DataSetFilters.slice_along_axis
slice_along_line = DataSetFilters.slice_along_line
extract_all_edges = DataSetFilters.extract_all_edges
elevation = DataSetFilters.elevation
compute_cell_sizes = DataSetFilters.compute_cell_sizes
cell_centers = DataSetFilters.cell_centers
cell_data_to_point_data = DataSetFilters.cell_data_to_point_data
point_data_to_cell_data = DataSetFilters.point_data_to_cell_data
triangulate = DataSetFilters.triangulate
def outline(composite, generate_faces=False, nested=False):
"""Produce an outline of the full extent for the all blocks in this composite dataset.
Parameters
----------
generate_faces : bool, optional
Generate solid faces for the box. This is off by default
nested : bool, optional
If True, these creates individual outlines for each nested dataset
"""
if nested:
return DataSetFilters.outline(composite, generate_faces=generate_faces)
box = pyvista.Box(bounds=composite.bounds)
return box.outline(generate_faces=generate_faces)
def outline_corners(composite, factor=0.2, nested=False):
"""Produce an outline of the corners for the all blocks in this composite dataset.
Parameters
----------
factor : float, optional
controls the relative size of the corners to the length of the
corresponding bounds
ested : bool, optional
If True, these creates individual outlines for each nested dataset
"""
if nested:
return DataSetFilters.outline_corners(composite, factor=factor)
box = pyvista.Box(bounds=composite.bounds)
return box.outline_corners(factor=factor)
@abstract_class
class PolyDataFilters(DataSetFilters):
"""An internal class to manage filtes/algorithms for polydata datasets."""
def edge_mask(poly_data, angle):
"""Return a mask of the points of a surface mesh that has a surface angle greater than angle.
Parameters
----------
angle : float
Angle to consider an edge.
"""
if not isinstance(poly_data, pyvista.PolyData): # pragma: no cover
poly_data = pyvista.PolyData(poly_data)
poly_data.point_arrays['point_ind'] = np.arange(poly_data.n_points)
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(poly_data)
featureEdges.FeatureEdgesOn()
featureEdges.BoundaryEdgesOff()
featureEdges.NonManifoldEdgesOff()
featureEdges.ManifoldEdgesOff()
featureEdges.SetFeatureAngle(angle)
featureEdges.Update()
edges = _get_output(featureEdges)
orig_id = pyvista.point_array(edges, 'point_ind')
return np.in1d(poly_data.point_arrays['point_ind'], orig_id,
assume_unique=True)
def boolean_cut(poly_data, cut, tolerance=1E-5, inplace=False):
"""Perform a Boolean cut using another mesh.
Parameters
----------
cut : pyvista.PolyData
Mesh making the cut
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
The cut mesh when inplace=False
"""
if not isinstance(cut, pyvista.PolyData):
raise TypeError("Input mesh must be PolyData.")
if not poly_data.is_all_triangles() or not cut.is_all_triangles():
raise NotAllTrianglesError("Make sure both the input and output are triangulated.")
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToIntersection()
# bfilter.SetOperationToDifference()
bfilter.SetInputData(1, cut)
bfilter.SetInputData(0, poly_data)
bfilter.ReorientDifferenceCellsOff()
bfilter.SetTolerance(tolerance)
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def boolean_add(poly_data, mesh, inplace=False):
"""Add a mesh to the current mesh.
Does not attempt to "join" the meshes.
Parameters
----------
mesh : pyvista.PolyData
The mesh to add.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
joinedmesh : pyvista.PolyData
Initial mesh and the new mesh when inplace=False.
"""
if not isinstance(mesh, pyvista.PolyData):
raise TypeError("Input mesh must be PolyData.")
vtkappend = vtk.vtkAppendPolyData()
vtkappend.AddInputData(poly_data)
vtkappend.AddInputData(mesh)
vtkappend.Update()
mesh = _get_output(vtkappend)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def __add__(poly_data, mesh):
"""Merge these two meshes."""
if not isinstance(mesh, vtk.vtkPolyData):
return DataSetFilters.__add__(poly_data, mesh)
return PolyDataFilters.boolean_add(poly_data, mesh)
def boolean_union(poly_data, mesh, inplace=False):
"""Combine two meshes and attempts to create a manifold mesh.
Parameters
----------
mesh : pyvista.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
union : pyvista.PolyData
The union mesh when inplace=False.
"""
if not isinstance(mesh, pyvista.PolyData):
raise TypeError("Input mesh must be PolyData.")
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToUnion()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, poly_data)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def boolean_difference(poly_data, mesh, inplace=False):
"""Combine two meshes and retains only the volume in common between the meshes.
Parameters
----------
mesh : pyvista.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
union : pyvista.PolyData
The union mesh when inplace=False.
"""
if not isinstance(mesh, pyvista.PolyData):
raise TypeError("Input mesh must be PolyData.")
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToDifference()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, poly_data)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def curvature(poly_data, curv_type='mean'):
"""Return the pointwise curvature of a mesh.
Parameters
----------
mesh : vtk.polydata
vtk polydata mesh
curvature string, optional
One of the following strings
Mean
Gaussian
Maximum
Minimum
Return
------
curvature : np.ndarray
Curvature values
"""
curv_type = curv_type.lower()
# Create curve filter and compute curvature
curvefilter = vtk.vtkCurvatures()
curvefilter.SetInputData(poly_data)
if curv_type == 'mean':
curvefilter.SetCurvatureTypeToMean()
elif curv_type == 'gaussian':
curvefilter.SetCurvatureTypeToGaussian()
elif curv_type == 'maximum':
curvefilter.SetCurvatureTypeToMaximum()
elif curv_type == 'minimum':
curvefilter.SetCurvatureTypeToMinimum()
else:
raise ValueError('Curv_Type must be either "Mean", '
'"Gaussian", "Maximum", or "Minimum"')
curvefilter.Update()
# Compute and return curvature
curv = _get_output(curvefilter)
return vtk_to_numpy(curv.GetPointData().GetScalars())
def plot_curvature(poly_data, curv_type='mean', **kwargs):
"""Plot the curvature.
Parameters
----------
curvtype : str, optional
One of the following strings indicating curvature type
- Mean
- Gaussian
- Maximum
- Minimum
**kwargs : optional
See :func:`pyvista.plot`
Return
------
cpos : list
List of camera position, focal point, and view up
"""
return poly_data.plot(scalars=poly_data.curvature(curv_type),
stitle=f'{curv_type}\nCurvature', **kwargs)
def triangulate(poly_data, inplace=False):
"""Return an all triangle mesh.
More complex polygons will be broken down into tetrahedrals.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
Mesh containing only triangles. None when inplace=True
"""
trifilter = vtk.vtkTriangleFilter()
trifilter.SetInputData(poly_data)
trifilter.PassVertsOff()
trifilter.PassLinesOff()
trifilter.Update()
mesh = _get_output(trifilter)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def smooth(poly_data, n_iter=20, relaxation_factor=0.01, convergence=0.0,
edge_angle=15, feature_angle=45,
boundary_smoothing=True, feature_smoothing=False, inplace=False):
"""Adjust point coordinates using Laplacian smoothing.
The effect is to "relax" the mesh, making the cells better shaped and
the vertices more evenly distributed.
Parameters
----------
n_iter : int
Number of iterations for Laplacian smoothing.
relaxation_factor : float, optional
Relaxation factor controls the amount of displacement in a single
iteration. Generally a lower relaxation factor and higher number of
iterations is numerically more stable.
convergence : float, optional
Convergence criterion for the iteration process. Smaller numbers
result in more smoothing iterations. Range from (0 to 1).
edge_angle : float, optional
Edge angle to control smoothing along edges (either interior or boundary).
feature_angle : float, optional
Feature angle for sharp edge identification.
boundary_smoothing : bool, optional
Boolean flag to control smoothing of boundary edges.
feature_smoothing : bool, optional
Boolean flag to control smoothing of feature edges.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
Smoothed mesh. None when inplace=True.
Examples
--------
Smooth the edges of an all triangular cube
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(5).clean()
>>> smooth_cube = cube.smooth(1000, feature_smoothing=False)
>>> n_edge_cells = cube.extract_feature_edges().n_cells
>>> n_smooth_cells = smooth_cube.extract_feature_edges().n_cells
>>> print(f'Sharp Edges on Cube: {n_edge_cells}')
Sharp Edges on Cube: 384
>>> print(f'Sharp Edges on Smooth Cube: {n_smooth_cells}')
Sharp Edges on Smooth Cube: 12
"""
alg = vtk.vtkSmoothPolyDataFilter()
alg.SetInputData(poly_data)
alg.SetNumberOfIterations(n_iter)
alg.SetConvergence(convergence)
alg.SetFeatureEdgeSmoothing(feature_smoothing)
alg.SetFeatureAngle(feature_angle)
alg.SetEdgeAngle(edge_angle)
alg.SetBoundarySmoothing(boundary_smoothing)
alg.SetRelaxationFactor(relaxation_factor)
alg.Update()
mesh = _get_output(alg)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def decimate_pro(poly_data, reduction, feature_angle=45.0, split_angle=75.0, splitting=True,
pre_split_mesh=False, preserve_topology=False, inplace=False):
"""Reduce the number of triangles in a triangular mesh.
It forms a good approximation to the original geometry. Based on the algorithm
originally described in "Decimation of Triangle Meshes", Proc Siggraph 92.
Parameters
----------
reduction : float
Reduction factor. A value of 0.9 will leave 10 % of the original number
of vertices.
feature_angle : float, optional
Angle used to define what an edge is (i.e., if the surface normal between
two adjacent triangles is >= feature_angle, an edge exists).
split_angle : float, optional
Angle used to control the splitting of the mesh. A split line exists
when the surface normals between two edge connected triangles are >= split_angle.
splitting : bool, optional
Controls the splitting of the mesh at corners, along edges, at non-manifold
points, or anywhere else a split is required. Turning splitting off
will better preserve the original topology of the mesh, but may not
necessarily give the exact requested decimation.
pre_split_mesh : bool, optional
Separates the mesh into semi-planar patches, which are disconnected
from each other. This can give superior results in some cases. If pre_split_mesh
is set to True, the mesh is split with the specified split_angle. Otherwise
mesh splitting is deferred as long as possible.
preserve_topology : bool, optional
Controls topology preservation. If on, mesh splitting and hole elimination
will not occur. This may limit the maximum reduction that may be achieved.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
Decimated mesh. None when inplace=True.
"""
alg = vtk.vtkDecimatePro()
alg.SetInputData(poly_data)
alg.SetTargetReduction(reduction)
alg.SetPreserveTopology(preserve_topology)
alg.SetFeatureAngle(feature_angle)
alg.SetSplitting(splitting)
alg.SetSplitAngle(split_angle)
alg.SetPreSplitMesh(pre_split_mesh)
alg.Update()
mesh = _get_output(alg)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def tube(poly_data, radius=None, scalars=None, capping=True, n_sides=20,
radius_factor=10, preference='point', inplace=False):
"""Generate a tube around each input line.
The radius of the tube can be set to linearly vary with a scalar value.
Parameters
----------
radius : float
Minimum tube radius (minimum because the tube radius may vary).
scalars : str, optional
scalars array by which the radius varies
capping : bool, optional
Turn on/off whether to cap the ends with polygons. Default ``True``.
n_sides : int, optional
Set the number of sides for the tube. Minimum of 3.
radius_factor : float, optional
Maximum tube radius in terms of a multiple of the minimum radius.
preference : str, optional
The field preference when searching for the scalars array by name.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
Tube-filtered mesh. None when inplace=True.
Examples
--------
Convert a single line to a tube
>>> import pyvista as pv
>>> line = pv.Line()
>>> tube = line.tube(radius=0.02)
>>> print('Line Cells:', line.n_cells)
Line Cells: 1
>>> print('Tube Cells:', tube.n_cells)
Tube Cells: 22
"""
if not isinstance(poly_data, pyvista.PolyData):
poly_data = pyvista.PolyData(poly_data)
if n_sides < 3:
n_sides = 3
tube = vtk.vtkTubeFilter()
tube.SetInputDataObject(poly_data)
# User Defined Parameters
tube.SetCapping(capping)
if radius is not None:
tube.SetRadius(radius)
tube.SetNumberOfSides(n_sides)
tube.SetRadiusFactor(radius_factor)
# Check if scalars array given
if scalars is not None:
if not isinstance(scalars, str):
raise TypeError('scalars array must be given as a string name')
_, field = poly_data.get_array(scalars, preference=preference, info=True)
# args: (idx, port, connection, field, name)
tube.SetInputArrayToProcess(0, 0, 0, field.value, scalars)
tube.SetVaryRadiusToVaryRadiusByScalar()
# Apply the filter
tube.Update()
mesh = _get_output(tube)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def subdivide(poly_data, nsub, subfilter='linear', inplace=False):
"""Increase the number of triangles in a single, connected triangular mesh.
Uses one of the following vtk subdivision filters to subdivide a mesh.
vtkButterflySubdivisionFilter
vtkLoopSubdivisionFilter
vtkLinearSubdivisionFilter
Linear subdivision results in the fastest mesh subdivision, but it
does not smooth mesh edges, but rather splits each triangle into 4
smaller triangles.
Butterfly and loop subdivision perform smoothing when dividing, and may
introduce artifacts into the mesh when dividing.
Subdivision filter appears to fail for multiple part meshes. Should
be one single mesh.
Parameters
----------
nsub : int
Number of subdivisions. Each subdivision creates 4 new triangles,
so the number of resulting triangles is nface*4**nsub where nface
is the current number of faces.
subfilter : string, optional
Can be one of the following: 'butterfly', 'loop', 'linear'
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : Polydata object
pyvista polydata object. None when inplace=True
Examples
--------
>>> from pyvista import examples
>>> import pyvista
>>> mesh = pyvista.PolyData(examples.planefile)
>>> submesh = mesh.subdivide(1, 'loop') # doctest:+SKIP
Alternatively, update the mesh in-place
>>> mesh.subdivide(1, 'loop', inplace=True) # doctest:+SKIP
"""
subfilter = subfilter.lower()
if subfilter == 'linear':
sfilter = vtk.vtkLinearSubdivisionFilter()
elif subfilter == 'butterfly':
sfilter = vtk.vtkButterflySubdivisionFilter()
elif subfilter == 'loop':
sfilter = vtk.vtkLoopSubdivisionFilter()
else:
raise ValueError("Subdivision filter must be one of the following: "
"'butterfly', 'loop', or 'linear'")
# Subdivide
sfilter.SetNumberOfSubdivisions(nsub)
sfilter.SetInputData(poly_data)
sfilter.Update()
submesh = _get_output(sfilter)
if inplace:
poly_data.overwrite(submesh)
else:
return submesh
def decimate(poly_data, target_reduction, volume_preservation=False,
attribute_error=False, scalars=True, vectors=True,
normals=False, tcoords=True, tensors=True, scalars_weight=0.1,
vectors_weight=0.1, normals_weight=0.1, tcoords_weight=0.1,
tensors_weight=0.1, inplace=False, progress_bar=False):
"""Reduce the number of triangles in a triangular mesh using vtkQuadricDecimation.
Parameters
----------
mesh : vtk.PolyData
Mesh to decimate
target_reduction : float
Fraction of the original mesh to remove.
TargetReduction is set to 0.9, this filter will try to reduce
the data set to 10% of its original size and will remove 90%
of the input triangles.
volume_preservation : bool, optional
Decide whether to activate volume preservation which greatly reduces
errors in triangle normal direction. If off, volume preservation is
disabled and if AttributeErrorMetric is active, these errors can be
large. Defaults to False.
attribute_error : bool, optional
Decide whether to include data attributes in the error metric. If
off, then only geometric error is used to control the decimation.
Defaults to False.
scalars : bool, optional
If attribute errors are to be included in the metric (i.e.,
AttributeErrorMetric is on), then the following flags control which
attributes are to be included in the error calculation. Defaults to
True.
vectors : bool, optional
See scalars parameter. Defaults to True.
normals : bool, optional
See scalars parameter. Defaults to False.
tcoords : bool, optional
See scalars parameter. Defaults to True.
tensors : bool, optional
See scalars parameter. Defaults to True.
scalars_weight : float, optional
The scaling weight contribution of the scalar attribute. These
values are used to weight the contribution of the attributes towards
the error metric. Defaults to 0.1.
vectors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
normals_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tcoords_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tensors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
inplace : bool, optional
Updates mesh in-place while returning nothing.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Return
------
outmesh : pyvista.PolyData
Decimated mesh. None when inplace=True.
Examples
--------
Decimate a sphere while preserving its volume
>>> import pyvista as pv
>>> sphere = pv.Sphere(theta_resolution=90, phi_resolution=90)
>>> print(sphere.n_cells)
15840
>>> dec_sphere = sphere.decimate(0.9, volume_preservation=True)
>>> print(dec_sphere.n_cells)
1584
Notes
-----
If you encounter a segmentation fault or other error, consider
using ``clean`` to remove any invalid cells before using this
filter.
"""
# create decimation filter
alg = vtk.vtkQuadricDecimation() # vtkDecimatePro as well
alg.SetVolumePreservation(volume_preservation)
alg.SetAttributeErrorMetric(attribute_error)
alg.SetScalarsAttribute(scalars)
alg.SetVectorsAttribute(vectors)
alg.SetNormalsAttribute(normals)
alg.SetTCoordsAttribute(tcoords)
alg.SetTensorsAttribute(tensors)
alg.SetScalarsWeight(scalars_weight)
alg.SetVectorsWeight(vectors_weight)
alg.SetNormalsWeight(normals_weight)
alg.SetTCoordsWeight(tcoords_weight)
alg.SetTensorsWeight(tensors_weight)
alg.SetTargetReduction(target_reduction)
alg.SetInputData(poly_data)
_update_alg(alg, progress_bar, 'Decimating')
mesh = _get_output(alg)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def compute_normals(poly_data, cell_normals=True, point_normals=True,
split_vertices=False, flip_normals=False,
consistent_normals=True,
auto_orient_normals=False,
non_manifold_traversal=True,
feature_angle=30.0, inplace=False):
"""Compute point and/or cell normals for a mesh.
The filter can reorder polygons to insure consistent orientation across
polygon neighbors. Sharp edges can be split and points duplicated
with separate normals to give crisp (rendered) surface definition. It is
also possible to globally flip the normal orientation.
The algorithm works by determining normals for each polygon and then
averaging them at shared points. When sharp edges are present, the edges
are split and new points generated to prevent blurry edges (due to
Gouraud shading).
Parameters
----------
cell_normals : bool, optional
Calculation of cell normals. Defaults to True.
point_normals : bool, optional
Calculation of point normals. Defaults to True.
split_vertices : bool, optional
Splitting of sharp edges. Defaults to False.
flip_normals : bool, optional
Set global flipping of normal orientation. Flipping modifies both
the normal direction and the order of a cell's points. Defaults to
False.
consistent_normals : bool, optional
Enforcement of consistent polygon ordering. Defaults to True.
auto_orient_normals : bool, optional
Turn on/off the automatic determination of correct normal
orientation. NOTE: This assumes a completely closed surface (i.e. no
boundary edges) and no non-manifold edges. If these constraints do
not hold, all bets are off. This option adds some computational
complexity, and is useful if you don't want to have to inspect the
rendered image to determine whether to turn on the FlipNormals flag.
However, this flag can work with the FlipNormals flag, and if both
are set, all the normals in the output will point "inward". Defaults
to False.
non_manifold_traversal : bool, optional
Turn on/off traversal across non-manifold edges. Changing this may
prevent problems where the consistency of polygonal ordering is
corrupted due to topological loops. Defaults to True.
feature_angle : float, optional
The angle that defines a sharp edge. If the difference in angle
across neighboring polygons is greater than this value, the shared
edge is considered "sharp". Defaults to 30.0.
inplace : bool, optional
Updates mesh in-place while returning nothing. Defaults to False.
Return
------
mesh : pyvista.PolyData
Updated mesh with cell and point normals if inplace=False
Examples
--------
Compute the point normals of the surface of a sphere
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere.compute_normals(cell_normals=False, inplace=True)
>>> normals = sphere['Normals']
>>> normals.shape
(842, 3)
Alternatively, create a new mesh when computing the normals
and compute both cell and point normals.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere_with_norm = sphere.compute_normals()
>>> sphere_with_norm.point_arrays['Normals'].shape
(842, 3)
>>> sphere_with_norm.cell_arrays['Normals'].shape
(1680, 3)
Notes
-----
Previous arrays named "Normals" will be overwritten.
Normals are computed only for polygons and triangle strips. Normals are
not computed for lines or vertices.
Triangle strips are broken up into triangle polygons. You may want to
restrip the triangles.
May be easier to run mesh.point_normals or mesh.cell_normals
"""
normal = vtk.vtkPolyDataNormals()
normal.SetComputeCellNormals(cell_normals)
normal.SetComputePointNormals(point_normals)
normal.SetSplitting(split_vertices)
normal.SetFlipNormals(flip_normals)
normal.SetConsistency(consistent_normals)
normal.SetAutoOrientNormals(auto_orient_normals)
normal.SetNonManifoldTraversal(non_manifold_traversal)
normal.SetFeatureAngle(feature_angle)
normal.SetInputData(poly_data)
normal.Update()
mesh = _get_output(normal)
if point_normals:
mesh.GetPointData().SetActiveNormals('Normals')
if cell_normals:
mesh.GetCellData().SetActiveNormals('Normals')
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def clip_closed_surface(poly_data, normal='x', origin=None,
tolerance=1e-06, inplace=False):
"""Clip a closed polydata surface with a plane.
This currently only supports one plane but could be implemented to
handle a plane collection.
It will produce a new closed surface by creating new polygonal faces
where the input data was clipped.
Non-manifold surfaces should not be used as input for this filter.
The input surface should have no open edges, and must not have any
edges that are shared by more than two faces. In addition, the input
surface should not self-intersect, meaning that the faces of the
surface should only touch at their edges.
Parameters
----------
normal : str, list, optional
Plane normal to clip with. Plane is centered at
``origin``. Normal can be either a 3 member list
(e.g. ``[0, 0, 1]``) or one of the following strings:
``'x'``, ``'y'``, ``'z'``, ``'-x'``, ``'-y'``, or
``'-z'``.
origin : list, optional
Coordinate of the origin (e.g. ``[1, 0, 0]``). Defaults
to ``[0, 0, 0]```
tolerance : float, optional
The tolerance for creating new points while clipping. If
the tolerance is too small, then degenerate triangles
might be produced.
inplace : bool, optional
Updates mesh in-place while returning nothing. Defaults to False.
Returns
-------
clipped_mesh : pyvista.PolyData
The clipped mesh resulting from this operation when
``inplace==False``. Otherwise, ``None``.
Examples
--------
Clip a sphere in the X direction centered at the origin. This
will leave behind half a sphere in the positive X direction.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> clipped_mesh = sphere.clip_closed_surface()
Clip the sphere at the xy plane and leave behind half the
sphere in the positive Z direction. Shift the clip upwards to
leave a smaller mesh behind.
>>> clipped_mesh = sphere.clip_closed_surface('z', origin=[0, 0, 0.3])
"""
# verify it is manifold
if poly_data.n_open_edges > 0:
raise ValueError("This surface appears to be non-manifold.")
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = poly_data.center
# create the plane for clipping
plane = generate_plane(normal, origin)
collection = vtk.vtkPlaneCollection()
collection.AddItem(plane)
alg = vtk.vtkClipClosedSurface()
alg.SetGenerateFaces(True)
alg.SetInputDataObject(poly_data)
alg.SetTolerance(tolerance)
alg.SetClippingPlanes(collection)
alg.Update() # Perform the Cut
result = _get_output(alg)
if inplace:
poly_data.overwrite(result)
else:
return result
def fill_holes(poly_data, hole_size, inplace=False, progress_bar=False): # pragma: no cover
"""
Fill holes in a pyvista.PolyData or vtk.vtkPolyData object.
Holes are identified by locating boundary edges, linking them together
into loops, and then triangulating the resulting loops. Note that you
can specify an approximate limit to the size of the hole that can be
filled.
Parameters
----------
hole_size : float
Specifies the maximum hole size to fill. This is represented as a
radius to the bounding circumsphere containing the hole. Note that
this is an approximate area; the actual area cannot be computed
without first triangulating the hole.
inplace : bool, optional
Return new mesh or overwrite input.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
mesh : pyvista.PolyData
Mesh with holes filled. None when inplace=True
Examples
--------
Create a partial sphere with a hole and then fill it
>>> import pyvista as pv
>>> sphere_with_hole = pv.Sphere(end_theta=330)
>>> sphere_with_hole.fill_holes(1000, inplace=True)
>>> edges = sphere_with_hole.extract_feature_edges(feature_edges=False, manifold_edges=False)
>>> assert edges.n_cells is 0
"""
logging.warning('pyvista.PolyData.fill_holes is known to segfault. '
'Use at your own risk')
alg = vtk.vtkFillHolesFilter()
alg.SetHoleSize(hole_size)
alg.SetInputData(poly_data)
_update_alg(alg, progress_bar, 'Filling Holes')
mesh = _get_output(alg)
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def clean(poly_data, point_merging=True, tolerance=None, lines_to_points=True,
polys_to_lines=True, strips_to_polys=True, inplace=False,
absolute=True, progress_bar=False, **kwargs):
"""Clean the mesh.
This merges duplicate points, removes unused points, and/or removes
degenerate cells.
Parameters
----------
point_merging : bool, optional
Enables point merging. On by default.
tolerance : float, optional
Set merging tolerance. When enabled merging is set to
absolute distance. If ``absolute`` is False, then the merging
tolerance is a fraction of the bounding box length. The alias
``merge_tol`` is also excepted.
lines_to_points : bool, optional
Turn on/off conversion of degenerate lines to points. Enabled by
default.
polys_to_lines : bool, optional
Turn on/off conversion of degenerate polys to lines. Enabled by
default.
strips_to_polys : bool, optional
Turn on/off conversion of degenerate strips to polys.
inplace : bool, optional
Updates mesh in-place while returning nothing. Default True.
absolute : bool, optional
Control if ``tolerance`` is an absolute distance or a fraction.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Return
------
mesh : pyvista.PolyData
Cleaned mesh. None when inplace=True
Examples
--------
Create a mesh with a degenerate face and then clean it,
removing the degenerate face
>>> import pyvista as pv
>>> points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]])
>>> faces = np.array([3, 0, 1, 2, 3, 0, 3, 3])
>>> mesh = pv.PolyData(points, faces)
>>> mout = mesh.clean()
>>> print(mout.faces)
[3 0 1 2]
"""
if tolerance is None:
tolerance = kwargs.pop('merge_tol', None)
assert_empty_kwargs(**kwargs)
alg = vtk.vtkCleanPolyData()
alg.SetPointMerging(point_merging)
alg.SetConvertLinesToPoints(lines_to_points)
alg.SetConvertPolysToLines(polys_to_lines)
alg.SetConvertStripsToPolys(strips_to_polys)
if isinstance(tolerance, (int, float)):
if absolute:
alg.ToleranceIsAbsoluteOn()
alg.SetAbsoluteTolerance(tolerance)
else:
alg.SetTolerance(tolerance)
alg.SetInputData(poly_data)
_update_alg(alg, progress_bar, 'Cleaning')
output = _get_output(alg)
# Check output so no segfaults occur
if output.n_points < 1:
raise ValueError('Clean tolerance is too high. Empty mesh returned.')
if inplace:
poly_data.overwrite(output)
else:
return output
def geodesic(poly_data, start_vertex, end_vertex, inplace=False):
"""Calculate the geodesic path between two vertices using Dijkstra's algorithm.
This will add an array titled `vtkOriginalPointIds` of the input
mesh's point ids to the output mesh.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Return
------
output : pyvista.PolyData
PolyData object consisting of the line segment between the
two given vertices.
Examples
--------
Plot the path between two points on a sphere
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(sphere)
>>> _ = pl.add_mesh(path, line_width=5, color='k')
>>> pl.show() # doctest:+SKIP
"""
if start_vertex < 0 or end_vertex > poly_data.n_points - 1:
raise IndexError('Invalid indices.')
if not poly_data.is_all_triangles():
raise NotAllTrianglesError("Input mesh for geodesic path must be all triangles.")
dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
dijkstra.SetInputData(poly_data)
dijkstra.SetStartVertex(start_vertex)
dijkstra.SetEndVertex(end_vertex)
dijkstra.Update()
original_ids = vtk_id_list_to_array(dijkstra.GetIdList())
output = _get_output(dijkstra)
output["vtkOriginalPointIds"] = original_ids
# Do not copy textures from input
output.clear_textures()
if inplace:
poly_data.overwrite(output)
else:
return output
def geodesic_distance(poly_data, start_vertex, end_vertex):
"""Calculate the geodesic distance between two vertices using Dijkstra's algorithm.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Return
------
length : float
Length of the geodesic segment.
Examples
--------
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> length = sphere.geodesic_distance(0, 100)
>>> print(f'Length is {length:.3f}')
Length is 0.812
"""
path = poly_data.geodesic(start_vertex, end_vertex)
sizes = path.compute_cell_sizes(length=True, area=False, volume=False)
distance = np.sum(sizes['Length'])
del path
del sizes
return distance
def ray_trace(poly_data, origin, end_point, first_point=False, plot=False,
off_screen=False):
"""Perform a single ray trace calculation.
This requires a mesh and a line segment defined by an origin
and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : np.ndarray or list
End of the line segment.
first_point : bool, optional
Returns intersection of first point only.
plot : bool, optional
Plots ray trace results
off_screen : bool, optional
Plots off screen when ``plot=True``. Used for unit testing.
Return
------
intersection_points : np.ndarray
Location of the intersection points. Empty array if no
intersections.
intersection_cells : np.ndarray
Indices of the intersection cells. Empty array if no
intersections.
Examples
--------
Compute the intersection between a ray from the origin and
[1, 0, 0] and a sphere with radius 0.5 centered at the origin
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> point, cell = sphere.ray_trace([0, 0, 0], [1, 0, 0], first_point=True)
>>> print(f'Intersected at {point[0]:.3f} {point[1]:.3f} {point[2]:.3f}')
Intersected at 0.499 0.000 0.000
"""
points = vtk.vtkPoints()
cell_ids = vtk.vtkIdList()
poly_data.obbTree.IntersectWithLine(np.array(origin),
np.array(end_point),
points, cell_ids)
intersection_points = vtk_to_numpy(points.GetData())
if first_point and intersection_points.shape[0] >= 1:
intersection_points = intersection_points[0]
intersection_cells = []
if intersection_points.any():
if first_point:
ncells = 1
else:
ncells = cell_ids.GetNumberOfIds()
for i in range(ncells):
intersection_cells.append(cell_ids.GetId(i))
intersection_cells = np.array(intersection_cells)
if plot:
plotter = pyvista.Plotter(off_screen=off_screen)
plotter.add_mesh(poly_data, label='Test Mesh')
segment = np.array([origin, end_point])
plotter.add_lines(segment, 'b', label='Ray Segment')
plotter.add_mesh(intersection_points, 'r', point_size=10,
label='Intersection Points')
plotter.add_legend()
plotter.add_axes()
plotter.show()
return intersection_points, intersection_cells
def multi_ray_trace(poly_data, origins, directions, first_point=False, retry=False):
"""Perform multiple ray trace calculations.
This requires a mesh with only triangular faces,
an array of origin points and an equal sized array of
direction vectors to trace along.
The embree library used for vectorisation of the ray traces is known to occasionally
return no intersections where the VTK implementation would return an intersection.
If the result appears to be missing some intersection points, set retry=True to run a second pass over rays
that returned no intersections, using the VTK ray_trace implementation.
Parameters
----------
origins : np.ndarray or list
Starting point for each trace.
directions : np.ndarray or list
direction vector for each trace.
first_point : bool, optional
Returns intersection of first point only.
retry : bool, optional
Will retry rays that return no intersections using the ray_trace
Return
------
intersection_points : np.ndarray
Location of the intersection points. Empty array if no
intersections.
intersection_rays : np.ndarray
Indices of the ray for each intersection point. Empty array if no
intersections.
intersection_cells : np.ndarray
Indices of the intersection cells. Empty array if no
intersections.
Examples
--------
Compute the intersection between rays from the origin in directions
[1, 0, 0], [0, 1, 0] and [0, 0, 1], and a sphere with radius 0.5 centered at the origin
>>> import pyvista as pv # doctest: +SKIP
... sphere = pv.Sphere()
... points, rays, cells = sphere.multi_ray_trace([[0, 0, 0]]*3, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], first_point=True)
... string = ", ".join([f"({point[0]:.3f}, {point[1]:.3f}, {point[2]:.3f})" for point in points])
... print(f'Rays intersected at {string}')
Rays intersected at (0.499, 0.000, 0.000), (0.000, 0.497, 0.000), (0.000, 0.000, 0.500)
"""
if not poly_data.is_all_triangles():
raise NotAllTrianglesError
try:
import trimesh, rtree, pyembree
except (ModuleNotFoundError, ImportError):
raise ImportError(
"To use multi_ray_trace please install trimesh, rtree and pyembree with:\n"
"\tconda install trimesh rtree pyembree"
)
faces_as_array = poly_data.faces.reshape((poly_data.number_of_faces, 4))[:, 1:]
tmesh = trimesh.Trimesh(poly_data.points, faces_as_array)
locations, index_ray, index_tri = tmesh.ray.intersects_location(
origins, directions, multiple_hits=not first_point
)
if retry:
ray_tuples = [(id_r, l, id_t) for id_r, l, id_t in zip(index_ray, locations, index_tri)]
for id_r in range(len(origins)):
if id_r not in index_ray:
origin = np.array(origins[id_r])
vector = np.array(directions[id_r])
unit_vector = vector / np.sqrt(np.sum(np.power(vector, 2)))
second_point = origin + (unit_vector * poly_data.length)
locs, indexes = poly_data.ray_trace(origin, second_point, first_point=first_point)
if locs.any():
if first_point:
locs = locs.reshape([1, 3])
for loc, id_t in zip(locs, indexes):
ray_tuples.append((id_r, loc, id_t))
sorted_results = sorted(ray_tuples, key=lambda x: x[0])
locations = np.array([loc for id_r, loc, id_t in sorted_results])
index_ray = np.array([id_r for id_r, loc, id_t in sorted_results])
index_tri = np.array([id_t for id_r, loc, id_t in sorted_results])
return locations, index_ray, index_tri
def plot_boundaries(poly_data, edge_color="red", **kwargs):
"""Plot boundaries of a mesh.
Parameters
----------
edge_color : str, etc.
The color of the edges when they are added to the plotter.
kwargs : optional
All additional keyword arguments will be passed to
:func:`pyvista.BasePlotter.add_mesh`
"""
edges = DataSetFilters.extract_feature_edges(poly_data)
plotter = pyvista.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
plotter.add_mesh(edges, color=edge_color, style='wireframe', label='Edges')
plotter.add_mesh(poly_data, label='Mesh', **kwargs)
plotter.add_legend()
return plotter.show()
def plot_normals(poly_data, show_mesh=True, mag=1.0, flip=False,
use_every=1, **kwargs):
"""Plot the point normals of a mesh."""
plotter = pyvista.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
if show_mesh:
plotter.add_mesh(poly_data, **kwargs)
normals = poly_data.point_normals
if flip:
normals *= -1
plotter.add_arrows(poly_data.points[::use_every],
normals[::use_every], mag=mag)
return plotter.show()
def remove_points(poly_data, remove, mode='any', keep_scalars=True, inplace=False):
"""Rebuild a mesh by removing points.
Only valid for all-triangle meshes.
Parameters
----------
remove : np.ndarray
If remove is a bool array, points that are True will be
removed. Otherwise, it is treated as a list of indices.
mode : str, optional
When 'all', only faces containing all points flagged for
removal will be removed. Default 'all'
keep_scalars : bool, optional
When True, point and cell scalars will be passed on to the
new mesh.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Return
------
mesh : pyvista.PolyData
Mesh without the points flagged for removal. Not returned
when inplace=False.
ridx : np.ndarray
Indices of new points relative to the original mesh. Not
returned when inplace=False.
Examples
--------
Remove the first 100 points from a sphere
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> reduced_sphere = sphere.remove_points(range(100))
"""
remove = np.asarray(remove)
# np.asarray will eat anything, so we have to weed out bogus inputs
if not issubclass(remove.dtype.type, (np.bool_, np.integer)):
raise TypeError('Remove must be either a mask or an integer array-like')
if remove.dtype == np.bool_:
if remove.size != poly_data.n_points:
raise ValueError('Mask different size than n_points')
remove_mask = remove
else:
remove_mask = np.zeros(poly_data.n_points, np.bool_)
remove_mask[remove] = True
if not poly_data.is_all_triangles():
raise NotAllTrianglesError
f = poly_data.faces.reshape(-1, 4)[:, 1:]
vmask = remove_mask.take(f)
if mode == 'all':
fmask = ~(vmask).all(1)
else:
fmask = ~(vmask).any(1)
# Regenerate face and point arrays
uni = np.unique(f.compress(fmask, 0), return_inverse=True)
new_points = poly_data.points.take(uni[0], 0)
nfaces = fmask.sum()
faces = np.empty((nfaces, 4), dtype=pyvista.ID_TYPE)
faces[:, 0] = 3
faces[:, 1:] = np.reshape(uni[1], (nfaces, 3))
newmesh = pyvista.PolyData(new_points, faces, deep=True)
ridx = uni[0]
# Add scalars back to mesh if requested
if keep_scalars:
for key in poly_data.point_arrays:
newmesh.point_arrays[key] = poly_data.point_arrays[key][ridx]
for key in poly_data.cell_arrays:
try:
newmesh.cell_arrays[key] = poly_data.cell_arrays[key][fmask]
except:
logging.warning(f'Unable to pass cell key {key} onto reduced mesh')
# Return vtk surface and reverse indexing array
if inplace:
poly_data.overwrite(newmesh)
else:
return newmesh, ridx
def flip_normals(poly_data):
"""Flip normals of a triangular mesh by reversing the point ordering.
Examples
--------
Flip the normals of a sphere and plot the normals before and
after the flip.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> sphere.plot_normals(mag=0.1) # doctest:+SKIP
>>> sphere.flip_normals()
>>> sphere.plot_normals(mag=0.1) # doctest:+SKIP
"""
if not poly_data.is_all_triangles:
raise NotAllTrianglesError('Can only flip normals on an all triangle mesh')
f = poly_data.faces.reshape((-1, 4))
f[:, 1:] = f[:, 1:][:, ::-1]
def delaunay_2d(poly_data, tol=1e-05, alpha=0.0, offset=1.0, bound=False,
inplace=False, edge_source=None, progress_bar=False):
"""Apply a delaunay 2D filter along the best fitting plane.
Parameters
----------
tol : float
Specify a tolerance to control discarding of closely spaced
points. This tolerance is specified as a fraction of the diagonal
length of the bounding box of the points.
alpha : float
Specify alpha (or distance) value to control output of this
filter. For a non-zero alpha value, only edges or triangles
contained within a sphere centered at mesh vertices will be
output. Otherwise, only triangles will be output.
offset : float
Specify a multiplier to control the size of the initial, bounding
Delaunay triangulation.
bound : bool
Boolean controls whether bounding triangulation points (and
associated triangles) are included in the output. (These are
introduced as an initial triangulation to begin the triangulation
process. This feature is nice for debugging output.)
inplace : bool
If True, overwrite this mesh with the triangulated mesh.
edge_source : pyvista.PolyData, optional
Specify the source object used to specify constrained edges and
loops. (This is optional.) If set, and lines/polygons are
defined, a constrained triangulation is created. The
lines/polygons are assumed to reference points in the input point
set (i.e. point ids are identical in the input and source). Note
that this method does not connect the pipeline. See
SetSourceConnection for connecting the pipeline.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Examples
--------
Extract the points of a sphere and then convert the point
cloud to a surface mesh. Note that only the bottom half is
converted to a mesh.
>>> import pyvista as pv
>>> points = pv.PolyData(pv.Sphere().points)
>>> mesh = points.delaunay_2d()
>>> mesh.is_all_triangles()
True
"""
alg = vtk.vtkDelaunay2D()
alg.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
alg.SetInputDataObject(poly_data)
alg.SetTolerance(tol)
alg.SetAlpha(alpha)
alg.SetOffset(offset)
alg.SetBoundingTriangulation(bound)
if edge_source is not None:
alg.SetSourceData(edge_source)
_update_alg(alg, progress_bar, 'Computing 2D Triangulation')
# Sometimes lines are given in the output. The
# `.triangulate()` filter cleans those
mesh = _get_output(alg).triangulate()
if inplace:
poly_data.overwrite(mesh)
else:
return mesh
def compute_arc_length(poly_data):
"""Compute the arc length over the length of the probed line.
It adds a new point-data array named "arc_length" with the
computed arc length for each of the polylines in the
input. For all other cell types, the arc length is set to 0.
Returns
-------
arc_length : float
Arc length of the length of the probed line
Examples
--------
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> length = path.compute_arc_length()['arc_length'][-1]
>>> print(f'Length is {length:.3f}')
Length is 0.812
This is identical to the geodesic_distance
>>> length = sphere.geodesic_distance(0, 100)
>>> print(f'Length is {length:.3f}')
Length is 0.812
You can also plot the arc_length
>>> arc = path.compute_arc_length()
>>> arc.plot(scalars="arc_length") # doctest:+SKIP
"""
alg = vtk.vtkAppendArcLength()
alg.SetInputData(poly_data)
alg.Update()
return _get_output(alg)
def project_points_to_plane(poly_data, origin=None, normal=(0,0,1), inplace=False):
"""Project points of this mesh to a plane.
Parameters
----------
origin : np.ndarray or collections.abc.Sequence, optional
Plane origin. Defaults the approximate center of the
input mesh minus half the length of the input mesh in the
direction of the normal.
normal : np.ndarray or collections.abc.Sequence, optional
Plane normal. Defaults to +Z ``[0, 0, 1]``
inplace : bool, optional
Overwrite the original mesh with the projected points
Examples
--------
Flatten a sphere to the XY plane
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> projected = sphere.project_points_to_plane([0, 0, 0])
"""
if not isinstance(normal, (np.ndarray, collections.abc.Sequence)) or len(normal) != 3:
raise TypeError('Normal must be a length three vector')
if origin is None:
origin = np.array(poly_data.center) - np.array(normal)*poly_data.length/2.
# choose what mesh to use
if not inplace:
mesh = poly_data.copy()
else:
mesh = poly_data
# Make plane
plane = generate_plane(normal, origin)
# Perform projection in place on the copied mesh
f = lambda p: plane.ProjectPoint(p, p)
np.apply_along_axis(f, 1, mesh.points)
if not inplace:
return mesh
return
def ribbon(poly_data, width=None, scalars=None, angle=0.0, factor=2.0,
normal=None, tcoords=False, preference='points'):
"""Create a ribbon of the lines in this dataset.
Note
----
If there are no lines in the input dataset, then the output will be
an empty PolyData mesh.
Parameters
----------
width : float
Set the "half" width of the ribbon. If the width is allowed to
vary, this is the minimum width. The default is 10% the length
scalars : str, optional
String name of the scalars array to use to vary the ribbon width.
This is only used if a scalars array is specified.
angle : float
Set the offset angle of the ribbon from the line normal. (The
angle is expressed in degrees.) The default is 0.0
factor : float
Set the maximum ribbon width in terms of a multiple of the
minimum width. The default is 2.0
normal : tuple(float), optional
Normal to use as default
tcoords : bool, str, optional
If True, generate texture coordinates along the ribbon. This can
also be specified to generate the texture coordinates in the
following ways: ``'length'``, ``'normalized'``,
Examples
--------
Convert a line to a ribbon and plot it.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> path = sphere.geodesic(0, 100)
>>> ribbon = path.ribbon()
>>> pv.plot([sphere, ribbon]) # doctest:+SKIP
"""
if scalars is not None:
arr, field = get_array(poly_data, scalars, preference=preference, info=True)
if width is None:
width = poly_data.length * 0.1
alg = vtk.vtkRibbonFilter()
alg.SetInputDataObject(poly_data)
alg.SetWidth(width)
if normal is not None:
alg.SetUseDefaultNormal(True)
alg.SetDefaultNormal(normal)
alg.SetAngle(angle)
if scalars is not None:
alg.SetVaryWidth(True)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
alg.SetWidthFactor(factor)
else:
alg.SetVaryWidth(False)
if tcoords:
alg.SetGenerateTCoords(True)
if isinstance(tcoords, str):
if tcoords.lower() == 'length':
alg.SetGenerateTCoordsToUseLength()
elif tcoords.lower() == 'normalized':
alg.SetGenerateTCoordsToNormalizedLength()
else:
alg.SetGenerateTCoordsToUseLength()
else:
alg.SetGenerateTCoordsToOff()
alg.Update()
return _get_output(alg)
def extrude(poly_data, vector, inplace=False, progress_bar=False):
"""Sweep polygonal data creating a "skirt" from free edges.
This will create a line from vertices.
This takes polygonal data as input and generates polygonal
data on output. The input dataset is swept according to some
extrusion function and creates new polygonal primitives. These
primitives form a "skirt" or swept surface. For example,
sweeping a line results in a quadrilateral, and sweeping a
triangle creates a "wedge".
There are a number of control parameters for this filter. You
can control whether the sweep of a 2D object (i.e., polygon or
triangle strip) is capped with the generating geometry via the
"Capping" parameter.
The skirt is generated by locating certain topological
features. Free edges (edges of polygons or triangle strips
only used by one polygon or triangle strips) generate
surfaces. This is true also of lines or polylines. Vertices
generate lines.
This filter can be used to create 3D fonts, 3D irregular bar
charts, or to model 2 1/2D objects like punched plates. It
also can be used to create solid objects from 2D polygonal
meshes.
Parameters
----------
mesh : pyvista.PolyData
Mesh to extrude.
vector : np.ndarray or list
Direction and length to extrude the mesh in.
inplace : bool, optional
Overwrites the original mesh inplace.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Examples
--------
Extrude a half arc circle
>>> import pyvista
>>> arc = pyvista.CircularArc([-1, 0, 0], [1, 0, 0], [0, 0, 0])
>>> mesh = arc.extrude([0, 0, 1])
>>> mesh.plot() # doctest:+SKIP
"""
alg = vtk.vtkLinearExtrusionFilter()
alg.SetExtrusionTypeToVectorExtrusion()
alg.SetVector(*vector)
alg.SetInputData(poly_data)
_update_alg(alg, progress_bar, 'Extruding')
output = pyvista.wrap(alg.GetOutput())
if not inplace:
return output
poly_data.overwrite(output)
def strip(poly_data, join=False, max_length=1000, pass_cell_data=False,
pass_cell_ids=False, pass_point_ids=False):
"""Strip poly data cells.
Generates triangle strips and/or poly-lines from input polygons,
triangle strips, and lines.
Polygons are assembled into triangle strips only if they are
triangles; other types of polygons are passed through to the output
and not stripped. (Use ``triangulate`` filter to triangulate
non-triangular polygons prior to running this filter if you need to
strip all the data.) The filter will pass through (to the output)
vertices if they are present in the input polydata. Also note that if
triangle strips or polylines are defined in the input they are passed
through and not joined nor extended. (If you wish to strip these use
``triangulate`` filter to fragment the input into triangles and lines
prior to running this filter.)
Parameters
----------
join : bool
If on, the output polygonal segments will be joined if they are
contiguous. This is useful after slicing a surface. The default
is off.
max_length : int
Specify the maximum number of triangles in a triangle strip,
and/or the maximum number of lines in a poly-line.
pass_cell_data : bool
Enable/Disable passing of the CellData in the input to the output
as FieldData. Note the field data is transformed.
pass_cell_ids : bool
If on, the output polygonal dataset will have a celldata array
that holds the cell index of the original 3D cell that produced
each output cell. This is useful for picking. The default is off
to conserve memory.
pass_point_ids : bool
If on, the output polygonal dataset will have a pointdata array
that holds the point index of the original vertex that produced
each output vertex. This is useful for picking. The default is
off to conserve memory.
Examples
--------
>>> from pyvista import examples
>>> mesh = examples.load_airplane()
>>> slc = mesh.slice(normal='z', origin=(0,0,-10))
>>> stripped = slc.strip()
>>> stripped.n_cells
1
"""
alg = vtk.vtkStripper()
alg.SetInputDataObject(poly_data)
alg.SetJoinContiguousSegments(join)
alg.SetMaximumLength(max_length)
alg.SetPassCellDataAsFieldData(pass_cell_data)
alg.SetPassThroughCellIds(pass_cell_ids)
alg.SetPassThroughPointIds(pass_point_ids)
alg.Update()
return _get_output(alg)
@abstract_class
class UnstructuredGridFilters(DataSetFilters):
"""An internal class to manage filtes/algorithms for unstructured grid datasets."""
def delaunay_2d(ugrid, tol=1e-05, alpha=0.0, offset=1.0, bound=False,
progress_bar=False):
"""Apply a delaunay 2D filter along the best fitting plane.
This extracts the grid's points and performs the triangulation on those alone.
Parameters
----------
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
return pyvista.PolyData(ugrid.points).delaunay_2d(tol=tol, alpha=alpha,
offset=offset,
bound=bound,
progress_bar=progress_bar)
@abstract_class
class UniformGridFilters(DataSetFilters):
"""An internal class to manage filtes/algorithms for uniform grid datasets."""
def gaussian_smooth(dataset, radius_factor=1.5, std_dev=2.,
scalars=None, preference='points', progress_bar=False):
"""Smooth the data with a Gaussian kernel.
Parameters
----------
radius_factor : float or iterable, optional
Unitless factor to limit the extent of the kernel.
std_dev : float or iterable, optional
Standard deviation of the kernel in pixel units.
scalars : str, optional
Name of scalars to process. Defaults to currently active scalars.
preference : str, optional
When scalars is specified, this is the preferred array type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
progress_bar : bool, optional
Display a progress bar to indicate progress.
"""
alg = vtk.vtkImageGaussianSmooth()
alg.SetInputDataObject(dataset)
if scalars is None:
field, scalars = dataset.active_scalars_info
else:
_, field = dataset.get_array(scalars, preference=preference, info=True)
alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
if isinstance(radius_factor, collections.abc.Iterable):
alg.SetRadiusFactors(radius_factor)
else:
alg.SetRadiusFactors(radius_factor, radius_factor, radius_factor)
if isinstance(std_dev, collections.abc.Iterable):
alg.SetStandardDeviations(std_dev)
else:
alg.SetStandardDeviations(std_dev, std_dev, std_dev)
_update_alg(alg, progress_bar, 'Performing Gaussian Smoothing')
return _get_output(alg)
def extract_subset(dataset, voi, rate=(1, 1, 1), boundary=False):
"""Select piece (e.g., volume of interest).
To use this filter set the VOI ivar which are i-j-k min/max indices
that specify a rectangular region in the data. (Note that these are
0-offset.) You can also specify a sampling rate to subsample the
data.
Typical applications of this filter are to extract a slice from a
volume for image processing, subsampling large volumes to reduce data
size, or extracting regions of a volume with interesting data.
Parameters
----------
voi : tuple(int)
Length 6 iterable of ints: ``(xmin, xmax, ymin, ymax, zmin, zmax)``.
These bounds specify the volume of interest in i-j-k min/max
indices.
rate : tuple(int)
Length 3 iterable of ints: ``(xrate, yrate, zrate)``.
Default: ``(1, 1, 1)``
boundary : bool
Control whether to enforce that the "boundary" of the grid is
output in the subsampling process. (This only has effect
when the rate in any direction is not equal to 1). When
this is on, the subsampling will always include the boundary of
the grid even though the sample rate is not an even multiple of
the grid dimensions. (By default this is off.)
"""
alg = vtk.vtkExtractVOI()
alg.SetVOI(voi)
alg.SetInputDataObject(dataset)
alg.SetSampleRate(rate)
alg.SetIncludeBoundary(boundary)
alg.Update()
result = _get_output(alg)
# Adjust for the confusing issue with the extents
# see https://gitlab.kitware.com/vtk/vtk/-/issues/17938
fixed = pyvista.UniformGrid()
fixed.origin = result.bounds[::2]
fixed.spacing = result.spacing
fixed.dimensions = result.dimensions
fixed.point_arrays.update(result.point_arrays)
fixed.cell_arrays.update(result.cell_arrays)
fixed.field_arrays.update(result.field_arrays)
fixed.copy_meta_from(result)
return fixed
| [
"numpy.sum",
"vtk.vtkArrowSource",
"vtk.vtkPoints",
"vtk.vtkSelectionNode.CONTAINING_CELLS",
"vtk.vtkShrinkFilter",
"numpy.ones",
"vtk.vtkSelectionNode.INVERSE",
"matplotlib.pyplot.figure",
"numpy.arange",
"pyvista.Line",
"vtk.vtkAppendPolyData",
"logging.warning",
"pyvista.Plotter",
"pyvi... | [((4773, 4803), 'pyvista.utilities.generate_plane', 'generate_plane', (['normal', 'origin'], {}), '(normal, origin)\n', (4787, 4803), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((8026, 8049), 'vtk.vtkBoxClipDataSet', 'vtk.vtkBoxClipDataSet', ([], {}), '()\n', (8047, 8049), False, 'import vtk\n'), ((9680, 9713), 'vtk.vtkImplicitPolyDataDistance', 'vtk.vtkImplicitPolyDataDistance', ([], {}), '()\n', (9711, 9713), False, 'import vtk\n'), ((9766, 9803), 'pyvista.convert_array', 'pyvista.convert_array', (['dataset.points'], {}), '(dataset.points)\n', (9787, 9803), False, 'import pyvista\n'), ((9820, 9840), 'vtk.vtkDoubleArray', 'vtk.vtkDoubleArray', ([], {}), '()\n', (9838, 9840), False, 'import vtk\n'), ((10094, 10122), 'pyvista.convert_array', 'pyvista.convert_array', (['dists'], {}), '(dists)\n', (10115, 10122), False, 'import pyvista\n'), ((11945, 12003), 'pyvista.utilities.get_array', 'get_array', (['dataset', 'scalars'], {'preference': '"""point"""', 'info': '(True)'}), "(dataset, scalars, preference='point', info=True)\n", (11954, 12003), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((13694, 13727), 'vtk.vtkImplicitPolyDataDistance', 'vtk.vtkImplicitPolyDataDistance', ([], {}), '()\n', (13725, 13727), False, 'import vtk\n'), ((15447, 15477), 'pyvista.utilities.generate_plane', 'generate_plane', (['normal', 'origin'], {}), '(normal, origin)\n', (15461, 15477), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((15515, 15530), 'vtk.vtkCutter', 'vtk.vtkCutter', ([], {}), '()\n', (15528, 15530), False, 'import vtk\n'), ((16968, 16988), 'pyvista.MultiBlock', 'pyvista.MultiBlock', ([], {}), '()\n', (16986, 16988), False, 'import pyvista\n'), ((19243, 19317), 'numpy.linspace', 'np.linspace', (['(bounds[ax * 2] + tolerance)', '(bounds[ax * 2 + 1] - tolerance)', 'n'], {}), '(bounds[ax * 2] + tolerance, bounds[ax * 2 + 1] - tolerance, n)\n', (19254, 19317), True, 'import numpy as np\n'), ((19389, 19409), 'pyvista.MultiBlock', 'pyvista.MultiBlock', ([], {}), '()\n', (19407, 19409), False, 'import pyvista\n'), ((21175, 21193), 'vtk.vtkPolyPlane', 'vtk.vtkPolyPlane', ([], {}), '()\n', (21191, 21193), False, 'import vtk\n'), ((21271, 21286), 'vtk.vtkCutter', 'vtk.vtkCutter', ([], {}), '()\n', (21284, 21286), False, 'import vtk\n'), ((24143, 24204), 'pyvista.utilities.get_array', 'get_array', (['dataset', 'scalars'], {'preference': 'preference', 'info': '(True)'}), '(dataset, scalars, preference=preference, info=True)\n', (24152, 24204), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((25391, 25409), 'vtk.vtkThreshold', 'vtk.vtkThreshold', ([], {}), '()\n', (25407, 25409), False, 'import vtk\n'), ((29916, 29938), 'vtk.vtkOutlineFilter', 'vtk.vtkOutlineFilter', ([], {}), '()\n', (29936, 29938), False, 'import vtk\n'), ((30415, 30443), 'vtk.vtkOutlineCornerFilter', 'vtk.vtkOutlineCornerFilter', ([], {}), '()\n', (30441, 30443), False, 'import vtk\n'), ((30846, 30869), 'vtk.vtkGeometryFilter', 'vtk.vtkGeometryFilter', ([], {}), '()\n', (30867, 30869), False, 'import vtk\n'), ((31337, 31358), 'vtk.vtkExtractEdges', 'vtk.vtkExtractEdges', ([], {}), '()\n', (31356, 31358), False, 'import vtk\n'), ((34557, 34581), 'vtk.vtkElevationFilter', 'vtk.vtkElevationFilter', ([], {}), '()\n', (34579, 34581), False, 'import vtk\n'), ((40470, 40496), 'vtk.vtkTextureMapToPlane', 'vtk.vtkTextureMapToPlane', ([], {}), '()\n', (40494, 40496), False, 'import vtk\n'), ((42994, 43021), 'vtk.vtkTextureMapToSphere', 'vtk.vtkTextureMapToSphere', ([], {}), '()\n', (43019, 43021), False, 'import vtk\n'), ((44406, 44429), 'vtk.vtkCellSizeFilter', 'vtk.vtkCellSizeFilter', ([], {}), '()\n', (44427, 44429), False, 'import vtk\n'), ((45040, 45060), 'vtk.vtkCellCenters', 'vtk.vtkCellCenters', ([], {}), '()\n', (45058, 45060), False, 'import vtk\n'), ((49262, 49278), 'vtk.vtkGlyph3D', 'vtk.vtkGlyph3D', ([], {}), '()\n', (49276, 49278), False, 'import vtk\n'), ((51275, 51302), 'vtk.vtkConnectivityFilter', 'vtk.vtkConnectivityFilter', ([], {}), '()\n', (51300, 51302), False, 'import vtk\n'), ((52827, 52847), 'pyvista.MultiBlock', 'pyvista.MultiBlock', ([], {}), '()\n', (52845, 52847), False, 'import pyvista\n'), ((52867, 52888), 'numpy.unique', 'np.unique', (['classifier'], {}), '(classifier)\n', (52876, 52888), True, 'import numpy as np\n'), ((54353, 54382), 'pyvista.utilities.assert_empty_kwargs', 'assert_empty_kwargs', ([], {}), '(**kwargs)\n', (54372, 54382), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((54489, 54547), 'pyvista.utilities.get_array', 'get_array', (['dataset', 'scalars'], {'preference': '"""point"""', 'info': '(True)'}), "(dataset, scalars, preference='point', info=True)\n", (54498, 54547), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((54715, 54734), 'vtk.vtkWarpScalar', 'vtk.vtkWarpScalar', ([], {}), '()\n', (54732, 54734), False, 'import vtk\n'), ((56403, 56461), 'pyvista.utilities.get_array', 'get_array', (['dataset', 'vectors'], {'preference': '"""point"""', 'info': '(True)'}), "(dataset, vectors, preference='point', info=True)\n", (56412, 56461), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((56835, 56854), 'vtk.vtkWarpVector', 'vtk.vtkWarpVector', ([], {}), '()\n', (56852, 56854), False, 'import vtk\n'), ((57886, 57914), 'vtk.vtkCellDataToPointData', 'vtk.vtkCellDataToPointData', ([], {}), '()\n', (57912, 57914), False, 'import vtk\n'), ((59161, 59189), 'vtk.vtkPointDataToCellData', 'vtk.vtkPointDataToCellData', ([], {}), '()\n', (59187, 59189), False, 'import vtk\n'), ((60383, 60413), 'vtk.vtkDataSetTriangleFilter', 'vtk.vtkDataSetTriangleFilter', ([], {}), '()\n', (60411, 60413), False, 'import vtk\n'), ((61614, 61633), 'vtk.vtkDelaunay3D', 'vtk.vtkDelaunay3D', ([], {}), '()\n', (61631, 61633), False, 'import vtk\n'), ((64274, 64303), 'vtk.vtkSelectEnclosedPoints', 'vtk.vtkSelectEnclosedPoints', ([], {}), '()\n', (64301, 64303), False, 'import vtk\n'), ((66528, 66548), 'vtk.vtkProbeFilter', 'vtk.vtkProbeFilter', ([], {}), '()\n', (66546, 66548), False, 'import vtk\n'), ((68346, 68374), 'vtk.vtkResampleWithDataSet', 'vtk.vtkResampleWithDataSet', ([], {}), '()\n', (68372, 68374), False, 'import vtk\n'), ((72184, 72207), 'vtk.vtkGaussianKernel', 'vtk.vtkGaussianKernel', ([], {}), '()\n', (72205, 72207), False, 'import vtk\n'), ((72506, 72533), 'vtk.vtkStaticPointLocator', 'vtk.vtkStaticPointLocator', ([], {}), '()\n', (72531, 72533), False, 'import vtk\n'), ((72624, 72650), 'vtk.vtkPointInterpolator', 'vtk.vtkPointInterpolator', ([], {}), '()\n', (72648, 72650), False, 'import vtk\n'), ((80544, 80565), 'vtk.vtkStreamTracer', 'vtk.vtkStreamTracer', ([], {}), '()\n', (80563, 80565), False, 'import vtk\n'), ((84003, 84054), 'pyvista.Line', 'pyvista.Line', (['pointa', 'pointb'], {'resolution': 'resolution'}), '(pointa, pointb, resolution=resolution)\n', (84015, 84054), False, 'import pyvista\n'), ((86592, 86614), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Distance"""'], {}), "('Distance')\n", (86602, 86614), True, 'import matplotlib.pyplot as plt\n'), ((87273, 87295), 'vtk.vtkSelectionNode', 'vtk.vtkSelectionNode', ([], {}), '()\n', (87293, 87295), False, 'import vtk\n'), ((87506, 87524), 'vtk.vtkSelection', 'vtk.vtkSelection', ([], {}), '()\n', (87522, 87524), False, 'import vtk\n'), ((87607, 87632), 'vtk.vtkExtractSelection', 'vtk.vtkExtractSelection', ([], {}), '()\n', (87630, 87632), False, 'import vtk\n'), ((88785, 88807), 'vtk.vtkSelectionNode', 'vtk.vtkSelectionNode', ([], {}), '()\n', (88805, 88807), False, 'import vtk\n'), ((89464, 89482), 'vtk.vtkSelection', 'vtk.vtkSelection', ([], {}), '()\n', (89480, 89482), False, 'import vtk\n'), ((89565, 89590), 'vtk.vtkExtractSelection', 'vtk.vtkExtractSelection', ([], {}), '()\n', (89588, 89590), False, 'import vtk\n'), ((90410, 90439), 'vtk.vtkDataSetSurfaceFilter', 'vtk.vtkDataSetSurfaceFilter', ([], {}), '()\n', (90437, 90439), False, 'import vtk\n'), ((92645, 92666), 'vtk.vtkFeatureEdges', 'vtk.vtkFeatureEdges', ([], {}), '()\n', (92664, 92666), False, 'import vtk\n'), ((94553, 94574), 'vtk.vtkAppendFilter', 'vtk.vtkAppendFilter', ([], {}), '()\n', (94572, 94574), False, 'import vtk\n'), ((97357, 97377), 'vtk.vtkCellQuality', 'vtk.vtkCellQuality', ([], {}), '()\n', (97375, 97377), False, 'import vtk\n'), ((101764, 101787), 'vtk.vtkGradientFilter', 'vtk.vtkGradientFilter', ([], {}), '()\n', (101785, 101787), False, 'import vtk\n'), ((104205, 104226), 'vtk.vtkShrinkFilter', 'vtk.vtkShrinkFilter', ([], {}), '()\n', (104224, 104226), False, 'import vtk\n'), ((104965, 105001), 'vtk.vtkCompositeDataGeometryFilter', 'vtk.vtkCompositeDataGeometryFilter', ([], {}), '()\n', (104999, 105001), False, 'import vtk\n'), ((105358, 105379), 'vtk.vtkAppendFilter', 'vtk.vtkAppendFilter', ([], {}), '()\n', (105377, 105379), False, 'import vtk\n'), ((106919, 106955), 'pyvista.Box', 'pyvista.Box', ([], {'bounds': 'composite.bounds'}), '(bounds=composite.bounds)\n', (106930, 106955), False, 'import pyvista\n'), ((107581, 107617), 'pyvista.Box', 'pyvista.Box', ([], {'bounds': 'composite.bounds'}), '(bounds=composite.bounds)\n', (107592, 107617), False, 'import pyvista\n'), ((108231, 108260), 'numpy.arange', 'np.arange', (['poly_data.n_points'], {}), '(poly_data.n_points)\n', (108240, 108260), True, 'import numpy as np\n'), ((108284, 108305), 'vtk.vtkFeatureEdges', 'vtk.vtkFeatureEdges', ([], {}), '()\n', (108303, 108305), False, 'import vtk\n'), ((108646, 108685), 'pyvista.point_array', 'pyvista.point_array', (['edges', '"""point_ind"""'], {}), "(edges, 'point_ind')\n", (108665, 108685), False, 'import pyvista\n'), ((108702, 108775), 'numpy.in1d', 'np.in1d', (["poly_data.point_arrays['point_ind']", 'orig_id'], {'assume_unique': '(True)'}), "(poly_data.point_arrays['point_ind'], orig_id, assume_unique=True)\n", (108709, 108775), True, 'import numpy as np\n'), ((109536, 109575), 'vtk.vtkBooleanOperationPolyDataFilter', 'vtk.vtkBooleanOperationPolyDataFilter', ([], {}), '()\n', (109573, 109575), False, 'import vtk\n'), ((110604, 110627), 'vtk.vtkAppendPolyData', 'vtk.vtkAppendPolyData', ([], {}), '()\n', (110625, 110627), False, 'import vtk\n'), ((111704, 111743), 'vtk.vtkBooleanOperationPolyDataFilter', 'vtk.vtkBooleanOperationPolyDataFilter', ([], {}), '()\n', (111741, 111743), False, 'import vtk\n'), ((112682, 112721), 'vtk.vtkBooleanOperationPolyDataFilter', 'vtk.vtkBooleanOperationPolyDataFilter', ([], {}), '()\n', (112719, 112721), False, 'import vtk\n'), ((113620, 113639), 'vtk.vtkCurvatures', 'vtk.vtkCurvatures', ([], {}), '()\n', (113637, 113639), False, 'import vtk\n'), ((115462, 115485), 'vtk.vtkTriangleFilter', 'vtk.vtkTriangleFilter', ([], {}), '()\n', (115483, 115485), False, 'import vtk\n'), ((117985, 118014), 'vtk.vtkSmoothPolyDataFilter', 'vtk.vtkSmoothPolyDataFilter', ([], {}), '()\n', (118012, 118014), False, 'import vtk\n'), ((120687, 120707), 'vtk.vtkDecimatePro', 'vtk.vtkDecimatePro', ([], {}), '()\n', (120705, 120707), False, 'import vtk\n'), ((122811, 122830), 'vtk.vtkTubeFilter', 'vtk.vtkTubeFilter', ([], {}), '()\n', (122828, 122830), False, 'import vtk\n'), ((129765, 129791), 'vtk.vtkQuadricDecimation', 'vtk.vtkQuadricDecimation', ([], {}), '()\n', (129789, 129791), False, 'import vtk\n'), ((134859, 134883), 'vtk.vtkPolyDataNormals', 'vtk.vtkPolyDataNormals', ([], {}), '()\n', (134881, 134883), False, 'import vtk\n'), ((138377, 138407), 'pyvista.utilities.generate_plane', 'generate_plane', (['normal', 'origin'], {}), '(normal, origin)\n', (138391, 138407), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((138429, 138453), 'vtk.vtkPlaneCollection', 'vtk.vtkPlaneCollection', ([], {}), '()\n', (138451, 138453), False, 'import vtk\n'), ((138503, 138529), 'vtk.vtkClipClosedSurface', 'vtk.vtkClipClosedSurface', ([], {}), '()\n', (138527, 138529), False, 'import vtk\n'), ((140346, 140440), 'logging.warning', 'logging.warning', (['"""pyvista.PolyData.fill_holes is known to segfault. Use at your own risk"""'], {}), "(\n 'pyvista.PolyData.fill_holes is known to segfault. Use at your own risk')\n", (140361, 140440), False, 'import logging\n'), ((140477, 140501), 'vtk.vtkFillHolesFilter', 'vtk.vtkFillHolesFilter', ([], {}), '()\n', (140499, 140501), False, 'import vtk\n'), ((142866, 142895), 'pyvista.utilities.assert_empty_kwargs', 'assert_empty_kwargs', ([], {}), '(**kwargs)\n', (142885, 142895), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((142910, 142932), 'vtk.vtkCleanPolyData', 'vtk.vtkCleanPolyData', ([], {}), '()\n', (142930, 142932), False, 'import vtk\n'), ((145087, 145121), 'vtk.vtkDijkstraGraphGeodesicPath', 'vtk.vtkDijkstraGraphGeodesicPath', ([], {}), '()\n', (145119, 145121), False, 'import vtk\n'), ((146506, 146529), 'numpy.sum', 'np.sum', (["sizes['Length']"], {}), "(sizes['Length'])\n", (146512, 146529), True, 'import numpy as np\n'), ((148086, 148101), 'vtk.vtkPoints', 'vtk.vtkPoints', ([], {}), '()\n', (148099, 148101), False, 'import vtk\n'), ((148121, 148136), 'vtk.vtkIdList', 'vtk.vtkIdList', ([], {}), '()\n', (148134, 148136), False, 'import vtk\n'), ((148828, 148856), 'numpy.array', 'np.array', (['intersection_cells'], {}), '(intersection_cells)\n', (148836, 148856), True, 'import numpy as np\n'), ((152101, 152150), 'trimesh.Trimesh', 'trimesh.Trimesh', (['poly_data.points', 'faces_as_array'], {}), '(poly_data.points, faces_as_array)\n', (152116, 152150), False, 'import trimesh, rtree, pyembree\n'), ((156221, 156239), 'numpy.asarray', 'np.asarray', (['remove'], {}), '(remove)\n', (156231, 156239), True, 'import numpy as np\n'), ((157276, 157320), 'numpy.empty', 'np.empty', (['(nfaces, 4)'], {'dtype': 'pyvista.ID_TYPE'}), '((nfaces, 4), dtype=pyvista.ID_TYPE)\n', (157284, 157320), True, 'import numpy as np\n'), ((157368, 157399), 'numpy.reshape', 'np.reshape', (['uni[1]', '(nfaces, 3)'], {}), '(uni[1], (nfaces, 3))\n', (157378, 157399), True, 'import numpy as np\n'), ((157419, 157465), 'pyvista.PolyData', 'pyvista.PolyData', (['new_points', 'faces'], {'deep': '(True)'}), '(new_points, faces, deep=True)\n', (157435, 157465), False, 'import pyvista\n'), ((161161, 161180), 'vtk.vtkDelaunay2D', 'vtk.vtkDelaunay2D', ([], {}), '()\n', (161178, 161180), False, 'import vtk\n'), ((162863, 162887), 'vtk.vtkAppendArcLength', 'vtk.vtkAppendArcLength', ([], {}), '()\n', (162885, 162887), False, 'import vtk\n'), ((164292, 164322), 'pyvista.utilities.generate_plane', 'generate_plane', (['normal', 'origin'], {}), '(normal, origin)\n', (164306, 164322), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((164435, 164473), 'numpy.apply_along_axis', 'np.apply_along_axis', (['f', '(1)', 'mesh.points'], {}), '(f, 1, mesh.points)\n', (164454, 164473), True, 'import numpy as np\n'), ((166383, 166404), 'vtk.vtkRibbonFilter', 'vtk.vtkRibbonFilter', ([], {}), '()\n', (166402, 166404), False, 'import vtk\n'), ((169353, 169383), 'vtk.vtkLinearExtrusionFilter', 'vtk.vtkLinearExtrusionFilter', ([], {}), '()\n', (169381, 169383), False, 'import vtk\n'), ((172106, 172123), 'vtk.vtkStripper', 'vtk.vtkStripper', ([], {}), '()\n', (172121, 172123), False, 'import vtk\n'), ((174364, 174392), 'vtk.vtkImageGaussianSmooth', 'vtk.vtkImageGaussianSmooth', ([], {}), '()\n', (174390, 174392), False, 'import vtk\n'), ((176646, 176665), 'vtk.vtkExtractVOI', 'vtk.vtkExtractVOI', ([], {}), '()\n', (176663, 176665), False, 'import vtk\n'), ((176998, 177019), 'pyvista.UniformGrid', 'pyvista.UniformGrid', ([], {}), '()\n', (177017, 177019), False, 'import pyvista\n'), ((1151, 1188), 'pyvista.utilities.ProgressMonitor', 'ProgressMonitor', (['alg'], {'message': 'message'}), '(alg, message=message)\n', (1166, 1188), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((2212, 2233), 'vtk.vtkClipPolyData', 'vtk.vtkClipPolyData', ([], {}), '()\n', (2231, 2233), False, 'import vtk\n'), ((2409, 2439), 'vtk.vtkTableBasedClipDataSet', 'vtk.vtkTableBasedClipDataSet', ([], {}), '()\n', (2437, 2439), False, 'import vtk\n'), ((9963, 9991), 'pyvista.convert_array', 'pyvista.convert_array', (['dists'], {}), '(dists)\n', (9984, 9991), False, 'import pyvista\n'), ((11687, 11708), 'vtk.vtkClipPolyData', 'vtk.vtkClipPolyData', ([], {}), '()\n', (11706, 11708), False, 'import vtk\n'), ((11741, 11771), 'vtk.vtkTableBasedClipDataSet', 'vtk.vtkTableBasedClipDataSet', ([], {}), '()\n', (11769, 11771), False, 'import vtk\n'), ((13813, 13850), 'pyvista.convert_array', 'pyvista.convert_array', (['dataset.points'], {}), '(dataset.points)\n', (13834, 13850), False, 'import pyvista\n'), ((13871, 13891), 'vtk.vtkDoubleArray', 'vtk.vtkDoubleArray', ([], {}), '()\n', (13889, 13891), False, 'import vtk\n'), ((13985, 14013), 'pyvista.convert_array', 'pyvista.convert_array', (['dists'], {}), '(dists)\n', (14006, 14013), False, 'import pyvista\n'), ((25162, 25183), 'vtk.vtkAppendFilter', 'vtk.vtkAppendFilter', ([], {}), '()\n', (25181, 25183), False, 'import vtk\n'), ((36906, 36928), 'vtk.vtkContourFilter', 'vtk.vtkContourFilter', ([], {}), '()\n', (36926, 36928), False, 'import vtk\n'), ((37699, 37760), 'pyvista.utilities.get_array', 'get_array', (['dataset', 'scalars'], {'preference': 'preference', 'info': '(True)'}), '(dataset, scalars, preference=preference, info=True)\n', (37708, 37760), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((47775, 47807), 'pyvista.PolyData', 'pyvista.PolyData', (['dataset.points'], {}), '(dataset.points)\n', (47791, 47807), False, 'import pyvista\n'), ((48265, 48285), 'vtk.vtkArrowSource', 'vtk.vtkArrowSource', ([], {}), '()\n', (48283, 48285), False, 'import vtk\n'), ((64636, 64674), 'numpy.zeros', 'np.zeros', (['out.n_points'], {'dtype': 'np.uint8'}), '(out.n_points, dtype=np.uint8)\n', (64644, 64674), True, 'import numpy as np\n'), ((66436, 66470), 'pyvista.is_pyvista_dataset', 'pyvista.is_pyvista_dataset', (['points'], {}), '(points)\n', (66462, 66470), False, 'import pyvista\n'), ((66493, 66513), 'pyvista.wrap', 'pyvista.wrap', (['points'], {}), '(points)\n', (66505, 66513), False, 'import pyvista\n'), ((68227, 68261), 'pyvista.is_pyvista_dataset', 'pyvista.is_pyvista_dataset', (['target'], {}), '(target)\n', (68253, 68261), False, 'import pyvista\n'), ((71713, 71747), 'pyvista.is_pyvista_dataset', 'pyvista.is_pyvista_dataset', (['target'], {}), '(target)\n', (71739, 71747), False, 'import pyvista\n'), ((80172, 80191), 'vtk.vtkLineSource', 'vtk.vtkLineSource', ([], {}), '()\n', (80189, 80191), False, 'import vtk\n'), ((80344, 80364), 'vtk.vtkPointSource', 'vtk.vtkPointSource', ([], {}), '()\n', (80362, 80364), False, 'import vtk\n'), ((86308, 86335), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (86318, 86335), True, 'import matplotlib.pyplot as plt\n'), ((86518, 86530), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (86528, 86530), True, 'import matplotlib.pyplot as plt\n'), ((86557, 86583), 'matplotlib.pyplot.plot', 'plt.plot', (['distance', 'values'], {}), '(distance, values)\n', (86565, 86583), True, 'import matplotlib.pyplot as plt\n'), ((86654, 86673), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['scalars'], {}), '(scalars)\n', (86664, 86673), True, 'import matplotlib.pyplot as plt\n'), ((86700, 86718), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (86710, 86718), True, 'import matplotlib.pyplot as plt\n'), ((86757, 86788), 'matplotlib.pyplot.title', 'plt.title', (['f"""{scalars} Profile"""'], {}), "(f'{scalars} Profile')\n", (86766, 86788), True, 'import matplotlib.pyplot as plt\n'), ((86815, 86831), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (86824, 86831), True, 'import matplotlib.pyplot as plt\n'), ((86888, 86898), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (86896, 86898), True, 'import matplotlib.pyplot as plt\n'), ((87464, 87483), 'pyvista.utilities.cells.numpy_to_idarr', 'numpy_to_idarr', (['ind'], {}), '(ind)\n', (87478, 87483), False, 'from pyvista.utilities.cells import numpy_to_idarr\n'), ((87872, 87891), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (87880, 87891), True, 'import numpy as np\n'), ((89049, 89088), 'numpy.ones', 'np.ones', (['dataset.n_points'], {'dtype': '"""bool"""'}), "(dataset.n_points, dtype='bool')\n", (89056, 89088), True, 'import numpy as np\n'), ((89328, 89347), 'pyvista.utilities.cells.numpy_to_idarr', 'numpy_to_idarr', (['ind'], {}), '(ind)\n', (89342, 89347), False, 'from pyvista.utilities.cells import numpy_to_idarr\n'), ((89391, 89430), 'vtk.vtkSelectionNode.CONTAINING_CELLS', 'vtk.vtkSelectionNode.CONTAINING_CELLS', ([], {}), '()\n', (89428, 89430), False, 'import vtk\n'), ((108157, 108184), 'pyvista.PolyData', 'pyvista.PolyData', (['poly_data'], {}), '(poly_data)\n', (108173, 108184), False, 'import pyvista\n'), ((109439, 109516), 'pyvista.core.errors.NotAllTrianglesError', 'NotAllTrianglesError', (['"""Make sure both the input and output are triangulated."""'], {}), "('Make sure both the input and output are triangulated.')\n", (109459, 109516), False, 'from pyvista.core.errors import NotAllTrianglesError\n'), ((122720, 122747), 'pyvista.PolyData', 'pyvista.PolyData', (['poly_data'], {}), '(poly_data)\n', (122736, 122747), False, 'import pyvista\n'), ((125528, 125560), 'vtk.vtkLinearSubdivisionFilter', 'vtk.vtkLinearSubdivisionFilter', ([], {}), '()\n', (125558, 125560), False, 'import vtk\n'), ((144991, 145066), 'pyvista.core.errors.NotAllTrianglesError', 'NotAllTrianglesError', (['"""Input mesh for geodesic path must be all triangles."""'], {}), "('Input mesh for geodesic path must be all triangles.')\n", (145011, 145066), False, 'from pyvista.core.errors import NotAllTrianglesError\n'), ((148181, 148197), 'numpy.array', 'np.array', (['origin'], {}), '(origin)\n', (148189, 148197), True, 'import numpy as np\n'), ((148243, 148262), 'numpy.array', 'np.array', (['end_point'], {}), '(end_point)\n', (148251, 148262), True, 'import numpy as np\n'), ((148897, 148935), 'pyvista.Plotter', 'pyvista.Plotter', ([], {'off_screen': 'off_screen'}), '(off_screen=off_screen)\n', (148912, 148935), False, 'import pyvista\n'), ((149017, 149046), 'numpy.array', 'np.array', (['[origin, end_point]'], {}), '([origin, end_point])\n', (149025, 149046), True, 'import numpy as np\n'), ((153221, 153274), 'numpy.array', 'np.array', (['[loc for id_r, loc, id_t in sorted_results]'], {}), '([loc for id_r, loc, id_t in sorted_results])\n', (153229, 153274), True, 'import numpy as np\n'), ((153299, 153353), 'numpy.array', 'np.array', (['[id_r for id_r, loc, id_t in sorted_results]'], {}), '([id_r for id_r, loc, id_t in sorted_results])\n', (153307, 153353), True, 'import numpy as np\n'), ((153378, 153432), 'numpy.array', 'np.array', (['[id_t for id_r, loc, id_t in sorted_results]'], {}), '([id_t for id_r, loc, id_t in sorted_results])\n', (153386, 153432), True, 'import numpy as np\n'), ((156703, 156741), 'numpy.zeros', 'np.zeros', (['poly_data.n_points', 'np.bool_'], {}), '(poly_data.n_points, np.bool_)\n', (156711, 156741), True, 'import numpy as np\n'), ((158644, 158713), 'pyvista.core.errors.NotAllTrianglesError', 'NotAllTrianglesError', (['"""Can only flip normals on an all triangle mesh"""'], {}), "('Can only flip normals on an all triangle mesh')\n", (158664, 158713), False, 'from pyvista.core.errors import NotAllTrianglesError\n'), ((166236, 166299), 'pyvista.utilities.get_array', 'get_array', (['poly_data', 'scalars'], {'preference': 'preference', 'info': '(True)'}), '(poly_data, scalars, preference=preference, info=True)\n', (166245, 166299), False, 'from pyvista.utilities import FieldAssociation, NORMALS, assert_empty_kwargs, generate_plane, get_array, vtk_id_list_to_array, wrap, ProgressMonitor, abstract_class\n'), ((24692, 24706), 'numpy.nanmin', 'np.nanmin', (['arr'], {}), '(arr)\n', (24701, 24706), True, 'import numpy as np\n'), ((24708, 24722), 'numpy.nanmax', 'np.nanmax', (['arr'], {}), '(arr)\n', (24717, 24722), True, 'import numpy as np\n'), ((36988, 37010), 'vtk.vtkMarchingCubes', 'vtk.vtkMarchingCubes', ([], {}), '()\n', (37008, 37010), False, 'import vtk\n'), ((86449, 86505), 'matplotlib.pyplot.plot', 'plt.plot', (['distance', 'values[:, i]'], {'label': 'f"""Component {i}"""'}), "(distance, values[:, i], label=f'Component {i}')\n", (86457, 86505), True, 'import matplotlib.pyplot as plt\n'), ((89140, 89167), 'numpy.arange', 'np.arange', (['dataset.n_points'], {}), '(dataset.n_points)\n', (89149, 89167), True, 'import numpy as np\n'), ((89254, 89284), 'vtk.vtkSelectionNode.INVERSE', 'vtk.vtkSelectionNode.INVERSE', ([], {}), '()\n', (89282, 89284), False, 'import vtk\n'), ((125622, 125657), 'vtk.vtkButterflySubdivisionFilter', 'vtk.vtkButterflySubdivisionFilter', ([], {}), '()\n', (125655, 125657), False, 'import vtk\n'), ((164052, 164078), 'numpy.array', 'np.array', (['poly_data.center'], {}), '(poly_data.center)\n', (164060, 164078), True, 'import numpy as np\n'), ((173044, 173074), 'pyvista.PolyData', 'pyvista.PolyData', (['ugrid.points'], {}), '(ugrid.points)\n', (173060, 173074), False, 'import pyvista\n'), ((37068, 37090), 'vtk.vtkFlyingEdges3D', 'vtk.vtkFlyingEdges3D', ([], {}), '()\n', (37088, 37090), False, 'import vtk\n'), ((125714, 125744), 'vtk.vtkLoopSubdivisionFilter', 'vtk.vtkLoopSubdivisionFilter', ([], {}), '()\n', (125742, 125744), False, 'import vtk\n'), ((152532, 152555), 'numpy.array', 'np.array', (['origins[id_r]'], {}), '(origins[id_r])\n', (152540, 152555), True, 'import numpy as np\n'), ((152585, 152611), 'numpy.array', 'np.array', (['directions[id_r]'], {}), '(directions[id_r])\n', (152593, 152611), True, 'import numpy as np\n'), ((157880, 157947), 'logging.warning', 'logging.warning', (['f"""Unable to pass cell key {key} onto reduced mesh"""'], {}), "(f'Unable to pass cell key {key} onto reduced mesh')\n", (157895, 157947), False, 'import logging\n'), ((164081, 164097), 'numpy.array', 'np.array', (['normal'], {}), '(normal)\n', (164089, 164097), True, 'import numpy as np\n'), ((152670, 152689), 'numpy.power', 'np.power', (['vector', '(2)'], {}), '(vector, 2)\n', (152678, 152689), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import aqml.cheminfo as co
import aqml.cheminfo.core as cc
import os
import numpy as np
T, F = True, False
def get_up_down(*path):
"""Get up and down electron numbers from ORCA output file.
Number of up&down electrons required in CASINO input.
"""
regexp1 = re.compile('Multiplicity Mult ....\s+(?P<mult>\d+)')
regexp2 = re.compile('Number of Electrons NEL ....\s+(?P<elec>\d+)')
with open(os.path.join(*path, 'mol.out'), 'r') as orca_out:
for line in orca_out:
m1 = re.search(regexp1, line)
if m1:
mult = int(m1.group('mult'))
m2 = re.search(regexp2, line)
if m2:
elec = int(m2.group('elec'))
neu = (elec + mult - 1)//2
ned = (elec - mult + 1)//2
return neu, ned
def get_nelec(*path):
"""Get total electron numbers from ORCA output file.
"""
regexp = re.compile('Number of Electrons NEL ....\s+(?P<elec>\d+)')
with open(os.path.join(*path, 'mol.out'), 'r') as orca_out:
for line in orca_out:
m = re.search(regexp, line)
if m:
elec = int(m.group('elec'))
return elec
def get_irrep(*path):
"""The symmetry of the initial guess is 1-Ag
"""
table = {
'Ag': 0, 'B1g': 1, 'B2g': 2, 'B3g': 3, 'Au': 4, 'B1u': 5, 'B2u': 6, 'B3u': 7,
'A1': 0, 'A2': 1, 'B1': 2, 'B2': 3,
'A': 0, 'B': 1,
}
irrep = 0
regexp = re.compile('The symmetry of the initial guess is \d-(?P<symmetry>\w+)')
with open(os.path.join(*path, 'mol.out'), 'r') as orca_out:
for line in orca_out:
m = re.search(regexp, line)
if m:
symmetry = m.group('symmetry')
irrep = table[symmetry]
return irrep
def pp_basis(basis):
"check if basis is pseudopotential basis"
return basis in ('aug-cc-pVDZ-CDF', 'aug-cc-pVTZ-CDF', 'aug-cc-pVQZ-CDF', 'aug-cc-pV5Z-CDF')
def write_orca_input(mol, method='MP2-CASSCF(N,M)', basis='cc-pvtz', nproc=1):
if 'casscf' in method.lower():
irrep = get_irrep(file_res_hf)
if method in ('MP2', 'OO-RI-MP2'):
moinp = 'mol.mp2nat'
else:
moinp = 'mol.qro'
with open('casscf.inp', 'w') as f:
offset = method.find('(') + 1
nel, norb = map(int, method[offset:-1].split(','))
f.write(open('orca_casscf.tmpl').read().format(
basis=basis,
molecule=mol,
moinp=moinp,
irrep=irrep,
charge=charge,
multiplicity=multiplicity,
nel=nel,
norb=norb,
procs='! PAL{}'.format(nproc),
))
postprocess = """
cd "$(dirname "{output}")"
$(which orca_2mkl) casscf -molden &&
ln -s casscf.molden.input mol.molden.input"""
if pp_basis(basis):
print('molden2qmc.py 3 "{input}" "{output}" --pseudoatoms all')
else:
print('molden2qmc.py 3 "{input}" "{output}"')
class cats(object):
dct_a = {'C':[4,2], 'N':[5,2], 'O':[5,3], 'F':[5,4], 'H':[1,0] }
def __init__(self, _obj, ipsp=F, ispin=F, order_trunk=3, mult=None, \
order_jastrow = {'trun':3, 'mu':8, 'chi':8, 'en':4, 'ee':4}, \
order_bf = {'mu':9, 'eta':9, 'en':3, 'ee':3} ):
self.ipsp = ipsp
if isinstance(_obj, str):
if _obj in co.chemical_symbols:
label = _obj
z1 = co.chemical_symbols.index(_obj)
obj = cc.molecules( cc.catoms([1], [z1], [[0.,0.,0.]]) )
else:
assert os.path.exists(_obj)
label = _obj[:-4]
obj = cc.molecules(_obj)
self.label = label
na = np.sum(obj.nas) #len(np.unique(zs)) # num atom type
zsu = obj.zsu
nat = len(zsu)
self.nat = nat # number of atom types
nzs = obj.nzs[0]
self.nzs = nzs
ias = np.arange(na)
if na == 1:
neu, ned = self.dct_a[ obj.symbols[0] ]
else:
tne = np.sum(obj.zs)
if ispin or ( tne % 2 != 0 ):
assert mult
neu = (elec + mult - 1)//2
ned = (elec - mult + 1)//2
else:
ispin = F
neu, ned = tne/2, tne/2
self.ispin = ispin
self.neu = neu
self.ned = ned
self.spin_dep = 1 if neu != ned else 0 ##
self.type_eN = 0 if ipsp else 1 #
lats = []
for iat in range(nat):
nai = nzs[iat]
atsi = ias[ obj.zsu[iat] == obj.zs ] + 1
latsi = ' '.join( [ '%d'%ai for ai in atsi ] )
lats.append( latsi )
self.lats = lats
self.order_jastrow = order_jastrow
self.order_bf = order_bf
self.order_trunk = order_trunk
def write(self, wd='.', bf=F):
opf = wd+'/'+self.label
print(' output file prefix: ', opf)
generate_inputs(self, opf, bf=bf)
def generate_jastraw(a):
"""
vars
-----------------------\
expansion_order: 4-8,
"""
sj = """ START HEADER
No title given.
END HEADER
START VERSION
1
END VERSION
START JASTROW
Title
None
Truncation order C
{order_jastrow[trun]}
START U TERM
Number of sets
1
START SET 1
Spherical harmonic l,m
0 0
Expansion order N_u
{order_jastrow[mu]}
Spin dep (0->uu=dd=ud; 1->uu=dd/=ud; 2->uu/=dd/=ud)
{spin_dep}
Cutoff (a.u.) ; Optimizable (0=NO; 1=YES)
3.d0 1
Parameter values ; Optimizable (0=NO; 1=YES)
END SET 1
END U TERM
START CHI TERM
Number of sets
{nat}""".format(order_jastrow=a.order_jastrow, spin_dep=a.spin_dep, nat=a.nat)
for iat in range(a.nat):
sj += """
START SET {iset}
Spherical harmonic l,m
0 0
Number of atoms in set
{nat}
Labels of the atoms in this set
{latsi}
Impose electron-nucleus cusp (0=NO; 1=YES)
0
Expansion order N_chi
{order_jastrow[chi]}
Spin dep (0->u=d; 1->u/=d)
{spin_dep}
Cutoff (a.u.) ; Optimizable (0=NO; 1=YES)
3.d0 1
Parameter values ; Optimizable (0=NO; 1=YES)
END SET {iset}""".format(iset=iat+1, nat=a.nzs[iat], latsi=a.lats[iat], order_jastrow=a.order_jastrow, spin_dep=a.spin_dep)
sj += """
END CHI TERM
START F TERM
Number of sets
{nat}""".format(nat=a.nat)
for iat in range(a.nat):
sj += """
START SET {iset}
Number of atoms in set
{nat}
Labels of the atoms in this set
{latsi}
Prevent duplication of u term (0=NO; 1=YES)
0
Prevent duplication of chi term (0=NO; 1=YES)
0
Electron-nucleus expansion order N_f_eN
{order_jastrow[en]}
Electron-electron expansion order N_f_ee
{order_jastrow[ee]}
Spin dep (0->uu=dd=ud; 1->uu=dd/=ud; 2->uu/=dd/=ud)
{spin_dep}
Cutoff (a.u.) ; Optimizable (0=NO; 1=YES)
3.d0 1
Parameter values ; Optimizable (0=NO; 1=YES)
END SET {iset}""".format(iset=iat+1, nat=a.nzs[iat], latsi=a.lats[iat], order_jastrow=a.order_jastrow, spin_dep=a.spin_dep)
sj += """
END F TERM
END JASTROW"""
return sj
def generate_backflow(a):
# version 2.12.1
sbf = """
START BACKFLOW
Title
None
Truncation order
%d
START ETA TERM
Expansion order
%d
Spin dep (0->uu=dd=ud; 1->uu=dd/=ud; 2->uu/=dd/=ud)
%d
Cut-off radius ; Optimizable (0=NO; 1=YES)
4.50 1
4.50 1
Parameter ; Optimizable (0=NO; 1=YES)
END ETA TERM
START MU TERM
Number of sets
%d"""%(a.order_trunk, a.order_bf['eta'], a.spin_dep, a.nat)
lats = []
for iat in range(a.nat):
latsi = a.lats[iat]
nai = a.nzs[iat]
sbf += """
START SET %d
Number of atoms in set
%d
Labels of the atoms in this set
%s
Type of e-N cusp conditions (0->PP/cuspless AE; 1->AE with cusp)
%d
Expansion order
%d
Spin dep (0->u=d; 1->u/=d)
%d
Cutoff (a.u.) ; Optimizable (0=NO; 1=YES)
6.d0 1
Parameter values ; Optimizable (0=NO; 1=YES)
END SET %d"""%(iat+1, nai, latsi, a.type_eN, a.order_bf['mu'], a.spin_dep, iat+1)
sbf += """
END MU TERM
START PHI TERM
Number of sets
%s"""%a.nat
for iat in range(a.nat):
nai = a.nzs[iat]
latsi = a.lats[iat]
sbf += """
START SET %d
Number of atoms in set
%d
Labels of the atoms in this set
%s
Type of e-N cusp conditions (0=PP; 1=AE)
%d
Irrotational Phi term (0=NO; 1=YES)
0
Electron-nucleus expansion order N_eN
%d
Electron-electron expansion order N_ee
%d
Spin dep (0->uu=dd=ud; 1->uu=dd/=ud; 2->uu/=dd/=ud)
%d
Cutoff (a.u.) ; Optimizable (0=NO; 1=YES)
6.d0 1
Parameter values ; Optimizable (0=NO; 1=YES)
END SET %d"""%(iat+1, nai, latsi, a.type_eN, a.order_bf['en'], a.order_bf['ee'], a.spin_dep, iat+1)
sbf += """
END PHI TERM
START AE CUTOFFS
Nucleus ; Set ; Cutoff length ; Optimizable (0=NO; 1=YES)
"""
#for iat in range(a.nat):
# sbf += " %d %d 0.200 1\n"%(iat+1, iat+1)
#for i, _ in enumerate(a.na):
# sbf += '{i} {i} 0.2 1\n'.format(i=i+1))
sbf += """ END AE CUTOFFS
END BACKFLOW"""
return sbf
def generate_input(a, task, dtdmc=2, bf=F, mdet=F, basis_type='gaussian', cycles=5):
sbf = 'T' if bf else 'F'
smd = 'T' if mdet else 'F'
svmc = ''
sdmc = ''
method = 'emin'
use_tmove = 'F'
sbf = 'T' if bf else 'F'
assert dtdmc in [1,2,4], '#ERROR: dtdmc not in [1,2,4]'
weight_dmc = 1024.0 * dtdmc
dt_dmc = 0.009259/dtdmc # unit: 1/Ha
if (not bf) or (not mdet):
if task in ['vmc_opt']:
nstep_equ_vmc = 5000
nstep_vmc = 1000000
nconfig_w_vmc = 100000
nblock_vmc = 10
elif task in ['vmc_dmc']:
nstep_equ_vmc = 5000
nstep_vmc = 2048
nconfig_w_vmc = 2048
nblock_vmc = 1
nstep_equ_dmc = 10000
nstep_stats_dmc = 50000
nblock_dmc = 5
else:
raise Exception('Todo')
if task in ['vmc_opt']:
svmc = """
# VMC
vmc_equil_nstep : {n1} #*! Number of equilibration steps (Integer)
vmc_nstep : {n2:<7} #*! Number of steps (Integer)
vmc_nblock : {nblock:<7} #*! Number of checkpoints (Integer)
vmc_nconfig_write : {nconfig_w:<7} #*! Number of configs to write (Integer)
vmc_decorr_period : 0 #*! VMC decorrelation period (0 - auto)
""".format(n1=nstep_equ_vmc, n2=nstep_vmc, nblock=nblock_vmc, nconfig_w=nconfig_w_vmc)
if bf:
svmc += """
%block opt_plan #*! Multi-cycle optimization plan (Block)
1 method=varmin backflow=F det_coeff=F fix_cutoffs=T
"""
for ib in range(2, nblock+1):
svmc += """%d\n"""%ib
svmc += """%endblock opt_plan\n"""
else:
svmc += """opt_cycles %d\n"""%(cycles)
elif task in ['vmc_dmc']:
sdmc = """
# DMC
dmc_equil_nstep : {n1} #*! Number of steps (Integer)
dmc_equil_nblock : 1 #*! Number of checkpoints (Integer)
dmc_stats_nstep : {n2} #*! Number of steps (Integer)
dmc_stats_nblock : {nblock} #*! Number of checkpoints (Integer)
dmc_target_weight : {w} #*! Total target weight in DMC (Real)
dtdmc : {dt} #*! DMC time step (Real)
use_tmove : {tmove} #*! Casula nl pp for DMC (Boolean)
popstats : T #*! Collect population statistics (Boolean)
""".format( n1=nstep_equ_dmc, n2=nstep_stats_dmc, nblock=nblock_dmc, w=weight_dmc, dt=dt_dmc, tmove=use_tmove )
else:
raise Exception('Todo')
st = """
#-------------------#
# CASINO input file #
#-------------------#
# {molecule} molecule (ground state)
# SYSTEM
neu : {neu:<3} #*! Number of up electrons (Integer)
ned : {ned:<3} #*! Number of down electrons (Integer)
periodic : F #*! Periodic boundary conditions (Boolean)
atom_basis_type : {basis_type} #*! Basis set type (text)
# RUN
runtype : {runtype} #*! Type of calculation (Text)
newrun : T #*! New run or continue old (Boolean)
testrun : F #*! Test run flag (Boolean)
allow_nochi_atoms : T #*! Permit atoms no chi (etc) terms (Boolean)
{svmc}
{sdmc}
# OPTIMIZATION
opt_method : {method} #*! Opt method (varmin/madmin/emin/...)
opt_jastrow : T #*! Optimize Jastrow factor (Boolean)
opt_detcoeff : {mdet} #*! Optimize determinant coeffs (Boolean)
opt_backflow : {backflow} #*! Optimize backflow parameters (Boolean)
""".format(neu=a.neu, ned=a.ned, basis_type=basis_type, method=method,\
runtype=task, backflow=sbf, mdet=smd, svmc=svmc, sdmc=sdmc, molecule=a.label)
st += """
# GENERAL PARAMETERS
use_gjastrow : T #*! Use a Jastrow function (Boolean)
backflow : {backflow} #*! Use backflow corrections (Boolean)
""".format(backflow=sbf)
return st
def generate_inputs(a, label, bf=F, mdet=F, tasks=['vmc_opt','vmc_dmc']):
for task in tasks:
sj = generate_input(a, task, bf=bf, mdet=mdet)
with open(label+'.%s.input'%task,'w') as fid: fid.write(sj)
s1 = generate_jastraw(a)
with open('%s.parameters.casl'%label, 'w') as fid: fid.write(s1)
#if bf and mdet:
# raise Exception('It may be too expensive to optimize when both bf and mdet are T')
if bf:
s2 = '\n%s'%generate_backflow(a)
s2 += """START MDET
Title
multideterminant WFN generated from Orca output data
MD
1
1.00 1 0
END MDET"""
with open('%s.correlation.data'%label, 'w') as fid: fid.write(s2)
if __name__ == "__main__":
import sys
fs = sys.argv[1:]
for f in fs:
a = cats(f)
# obj, ipsp=F, ispin=F, order_trunk=3, mult=None, \
# order_jastrow = {'mu':8, 'chi':8, 'en':4, 'ee':4}, \
# order_bf = {'mu':9, 'eta':9, 'en':3, 'ee':3} )
lb = f[:-4]
generate_inputs(a, lb, tasks=['vmc_opt','vmc_dmc'])
| [
"aqml.cheminfo.chemical_symbols.index",
"numpy.sum",
"os.path.exists",
"numpy.arange",
"aqml.cheminfo.core.molecules",
"os.path.join",
"aqml.cheminfo.core.catoms"
] | [((3911, 3926), 'numpy.sum', 'np.sum', (['obj.nas'], {}), '(obj.nas)\n', (3917, 3926), True, 'import numpy as np\n'), ((4117, 4130), 'numpy.arange', 'np.arange', (['na'], {}), '(na)\n', (4126, 4130), True, 'import numpy as np\n'), ((477, 507), 'os.path.join', 'os.path.join', (['*path', '"""mol.out"""'], {}), "(*path, 'mol.out')\n", (489, 507), False, 'import os\n'), ((1040, 1070), 'os.path.join', 'os.path.join', (['*path', '"""mol.out"""'], {}), "(*path, 'mol.out')\n", (1052, 1070), False, 'import os\n'), ((1606, 1636), 'os.path.join', 'os.path.join', (['*path', '"""mol.out"""'], {}), "(*path, 'mol.out')\n", (1618, 1636), False, 'import os\n'), ((4235, 4249), 'numpy.sum', 'np.sum', (['obj.zs'], {}), '(obj.zs)\n', (4241, 4249), True, 'import numpy as np\n'), ((3629, 3660), 'aqml.cheminfo.chemical_symbols.index', 'co.chemical_symbols.index', (['_obj'], {}), '(_obj)\n', (3654, 3660), True, 'import aqml.cheminfo as co\n'), ((3775, 3795), 'os.path.exists', 'os.path.exists', (['_obj'], {}), '(_obj)\n', (3789, 3795), False, 'import os\n'), ((3852, 3870), 'aqml.cheminfo.core.molecules', 'cc.molecules', (['_obj'], {}), '(_obj)\n', (3864, 3870), True, 'import aqml.cheminfo.core as cc\n'), ((3697, 3736), 'aqml.cheminfo.core.catoms', 'cc.catoms', (['[1]', '[z1]', '[[0.0, 0.0, 0.0]]'], {}), '([1], [z1], [[0.0, 0.0, 0.0]])\n', (3706, 3736), True, 'import aqml.cheminfo.core as cc\n')] |
import shutil
import subprocess as sp
import numpy as np
import pandas as pd
import pkg_resources
import pytest
from astropy import units as u
from astropy.time import Time
from lstchain.io.io import (
dl1_params_lstcam_key,
dl2_params_lstcam_key,
get_dataset_keys,
dl1_params_src_dep_lstcam_key,
)
def find_entry_points(package_name):
"""from: https://stackoverflow.com/a/47383763/3838691"""
entrypoints = [
ep.name
for ep in pkg_resources.iter_entry_points("console_scripts")
if ep.module_name.startswith(package_name)
]
return entrypoints
ALL_SCRIPTS = find_entry_points("lstchain")
def run_program(*args):
result = sp.run(args, stdout=sp.PIPE, stderr=sp.STDOUT, encoding='utf-8')
if result.returncode != 0:
raise ValueError(
f"Running {args[0]} failed with return code {result.returncode}"
f", output: \n {result.stdout}"
)
@pytest.mark.parametrize("script", ALL_SCRIPTS)
def test_all_help(script):
"""Test for all scripts if at least the help works."""
run_program(script, "--help")
@pytest.fixture(scope="session")
def simulated_dl1ab(temp_dir_simulated_files, simulated_dl1_file):
"""Produce a new simulated dl1 file using the dl1ab script."""
output_file = temp_dir_simulated_files / "dl1ab.h5"
run_program("lstchain_dl1ab", "-f", simulated_dl1_file, "-o", output_file)
return output_file
def test_add_source_dependent_parameters(simulated_dl1_file):
run_program("lstchain_add_source_dependent_parameters", "-f", simulated_dl1_file)
dl1_params_src_dep = pd.read_hdf(
simulated_dl1_file, key=dl1_params_src_dep_lstcam_key
)
dl1_params_src_dep.columns = pd.MultiIndex.from_tuples(
[
tuple(col[1:-1].replace("'", "").replace(" ", "").split(","))
for col in dl1_params_src_dep.columns
]
)
assert "alpha" in dl1_params_src_dep["on"].columns
@pytest.fixture(scope="session")
def merged_simulated_dl1_file(simulated_dl1_file, temp_dir_simulated_files):
"""Produce a merged file from two identical dl1 hdf5 files."""
shutil.copy(simulated_dl1_file, temp_dir_simulated_files / "dl1_copy.h5")
merged_dl1_file = temp_dir_simulated_files / "script_merged_dl1.h5"
run_program(
"lstchain_merge_hdf5_files",
"-d",
temp_dir_simulated_files,
"-o",
merged_dl1_file,
"--no-image",
"True",
)
return merged_dl1_file
def test_lstchain_mc_r0_to_dl1(simulated_dl1_file):
assert simulated_dl1_file.is_file()
@pytest.mark.private_data
def test_lstchain_data_r0_to_dl1(observed_dl1_files):
assert observed_dl1_files["dl1_file1"].is_file()
assert observed_dl1_files["muons1"].is_file()
assert observed_dl1_files["datacheck1"].is_file()
assert observed_dl1_files["dl1_file2"].is_file()
assert observed_dl1_files["muons2"].is_file()
assert observed_dl1_files["datacheck2"].is_file()
@pytest.mark.private_data
def test_observed_dl1_validity(observed_dl1_files):
dl1_df = pd.read_hdf(observed_dl1_files["dl1_file1"], key=dl1_params_lstcam_key)
# The first valid timestamp in the test run corresponds
# to its third event (see night summary)
first_timestamp_nightsummary = 1582059789516351903 # ns
first_event_timestamp = dl1_df["dragon_time"].iloc[2] # third event
dl1_tables = get_dataset_keys(observed_dl1_files["dl1_file1"])
assert 'dl1/event/telescope/monitoring/calibration' in dl1_tables
assert 'dl1/event/telescope/monitoring/flatfield' in dl1_tables
assert 'dl1/event/telescope/monitoring/pedestal' in dl1_tables
assert 'dl1/event/telescope/image/LST_LSTCam' in dl1_tables
assert 'configuration/instrument/subarray/layout' in dl1_tables
assert 'configuration/instrument/telescope/camera/geometry_LSTCam' in dl1_tables
assert 'configuration/instrument/telescope/camera/readout_LSTCam' in dl1_tables
assert 'configuration/instrument/telescope/optics' in dl1_tables
assert "alt_tel" in dl1_df.columns
assert "az_tel" in dl1_df.columns
assert "trigger_type" in dl1_df.columns
assert "ucts_trigger_type" in dl1_df.columns
assert "trigger_time" in dl1_df.columns
assert "dragon_time" in dl1_df.columns
assert "tib_time" in dl1_df.columns
assert "ucts_time" in dl1_df.columns
assert np.isclose(
(
Time(first_event_timestamp, format="unix")
- Time(first_timestamp_nightsummary / 1e9, format="unix_tai")
).to_value(u.s),
0,
)
np.testing.assert_allclose(dl1_df["dragon_time"], dl1_df["trigger_time"])
def test_lstchain_mc_trainpipe(rf_models):
assert rf_models["energy"].is_file()
assert rf_models["disp"].is_file()
assert rf_models["gh_sep"].is_file()
def test_lstchain_mc_rfperformance(tmp_path, simulated_dl1_file, fake_dl1_proton_file):
gamma_file = simulated_dl1_file
proton_file = fake_dl1_proton_file
output_dir = tmp_path
file_model_energy = output_dir / "reg_energy.sav"
file_model_disp = output_dir / "reg_disp_vector.sav"
file_model_gh_sep = output_dir / "cls_gh.sav"
run_program(
"lstchain_mc_rfperformance",
"--g-train",
gamma_file,
"--g-test",
gamma_file,
"--p-train",
proton_file,
"--p-test",
proton_file,
"-o",
output_dir,
)
assert file_model_gh_sep.is_file()
assert file_model_disp.is_file()
assert file_model_energy.is_file()
def test_lstchain_merge_dl1_hdf5_files(merged_simulated_dl1_file):
assert merged_simulated_dl1_file.is_file()
@pytest.mark.private_data
def test_lstchain_merge_dl1_hdf5_observed_files(
temp_dir_observed_files, observed_dl1_files
):
merged_dl1_observed_file = temp_dir_observed_files / "dl1_LST-1.Run02008_merged.h5"
run_program(
"lstchain_merge_hdf5_files",
"-d",
temp_dir_observed_files,
"-o",
merged_dl1_observed_file,
"--no-image",
"False",
"--smart",
"False",
"--run-number",
"2008",
"--pattern",
"dl1_*.h5",
)
dl1a_df = pd.read_hdf(observed_dl1_files["dl1_file1"], key=dl1_params_lstcam_key)
dl1b_df = pd.read_hdf(observed_dl1_files["dl1_file1"], key=dl1_params_lstcam_key)
merged_dl1_df = pd.read_hdf(merged_dl1_observed_file, key=dl1_params_lstcam_key)
assert merged_dl1_observed_file.is_file()
assert len(dl1a_df) + len(dl1b_df) == len(merged_dl1_df)
assert "dl1/event/telescope/image/LST_LSTCam" in get_dataset_keys(
merged_dl1_observed_file
)
assert "dl1/event/telescope/parameters/LST_LSTCam" in get_dataset_keys(
merged_dl1_observed_file
)
@pytest.mark.private_data
def test_merge_datacheck_files(temp_dir_observed_files):
run_program(
"lstchain_check_dl1",
"--batch",
"--input-file",
temp_dir_observed_files / "datacheck_dl1_LST-1.Run02008.*.h5",
"--output-dir",
temp_dir_observed_files,
)
assert (temp_dir_observed_files / "datacheck_dl1_LST-1.Run02008.h5").is_file()
assert (temp_dir_observed_files / "datacheck_dl1_LST-1.Run02008.pdf").is_file()
def test_lstchain_merged_dl1_to_dl2(
temp_dir_simulated_files, merged_simulated_dl1_file, rf_models
):
output_file = merged_simulated_dl1_file.with_name(
merged_simulated_dl1_file.name.replace("dl1", "dl2")
)
run_program(
"lstchain_dl1_to_dl2",
"-f",
merged_simulated_dl1_file,
"-p",
rf_models["path"],
"--output-dir",
temp_dir_simulated_files,
)
assert output_file.is_file()
def test_lstchain_dl1_to_dl2(simulated_dl2_file):
assert simulated_dl2_file.is_file()
dl2_df = pd.read_hdf(simulated_dl2_file, key=dl2_params_lstcam_key)
assert "gammaness" in dl2_df.columns
assert "reco_type" in dl2_df.columns
assert "reco_energy" in dl2_df.columns
assert "reco_disp_dx" in dl2_df.columns
assert "reco_disp_dy" in dl2_df.columns
assert "reco_src_x" in dl2_df.columns
assert "reco_src_y" in dl2_df.columns
@pytest.mark.private_data
def test_lstchain_observed_dl1_to_dl2(observed_dl2_file):
assert observed_dl2_file.is_file()
dl2_df = pd.read_hdf(observed_dl2_file, key=dl2_params_lstcam_key)
assert "gammaness" in dl2_df.columns
assert "reco_type" in dl2_df.columns
assert "reco_energy" in dl2_df.columns
assert "reco_alt" in dl2_df.columns
assert "reco_az" in dl2_df.columns
assert "reco_src_x" in dl2_df.columns
assert "reco_src_y" in dl2_df.columns
assert "reco_disp_dx" in dl2_df.columns
assert "reco_disp_dy" in dl2_df.columns
def test_dl1ab(simulated_dl1ab):
assert simulated_dl1ab.is_file()
@pytest.mark.private_data
def test_observed_dl1ab(tmp_path, observed_dl1_files):
output_dl1ab = tmp_path / "dl1ab.h5"
run_program(
"lstchain_dl1ab", "-f", observed_dl1_files["dl1_file1"], "-o", output_dl1ab
)
assert output_dl1ab.is_file()
dl1ab = pd.read_hdf(output_dl1ab, key=dl1_params_lstcam_key)
dl1 = pd.read_hdf(observed_dl1_files["dl1_file1"], key=dl1_params_lstcam_key)
np.testing.assert_allclose(dl1, dl1ab, rtol=1e-3, equal_nan=True)
def test_simulated_dl1ab_validity(simulated_dl1_file, simulated_dl1ab):
assert simulated_dl1ab.is_file()
dl1_df = pd.read_hdf(simulated_dl1_file, key=dl1_params_lstcam_key)
dl1ab_df = pd.read_hdf(simulated_dl1ab, key=dl1_params_lstcam_key)
np.testing.assert_allclose(dl1_df, dl1ab_df, rtol=1e-4, equal_nan=True)
def test_mc_r0_to_dl2(tmp_path, rf_models, mc_gamma_testfile):
dl2_file = tmp_path / "dl2_gamma_test_large.h5"
run_program(
"lstchain_mc_r0_to_dl2",
"--input-file",
mc_gamma_testfile,
"--path-models",
rf_models["path"],
"--store-dl1",
"False",
"--output-dir",
tmp_path,
)
assert dl2_file.is_file()
def test_read_mc_dl2_to_QTable(simulated_dl2_file):
from lstchain.io.io import read_mc_dl2_to_QTable
import astropy.units as u
events, sim_info = read_mc_dl2_to_QTable(simulated_dl2_file)
assert "true_energy" in events.colnames
assert sim_info.energy_max == 330 * u.TeV
@pytest.mark.private_data
def test_read_data_dl2_to_QTable(temp_dir_observed_files, observed_dl1_files):
from lstchain.io.io import read_data_dl2_to_QTable
real_data_dl2_file = temp_dir_observed_files / (
observed_dl1_files["dl1_file1"].name.replace("dl1", "dl2")
)
events = read_data_dl2_to_QTable(real_data_dl2_file)
assert "gh_score" in events.colnames
@pytest.mark.private_data
def test_run_summary(run_summary_path):
from astropy.table import Table
from datetime import datetime
date = "20200218"
assert run_summary_path.is_file()
run_summary_table = Table.read(run_summary_path)
assert run_summary_table.meta["date"] == datetime.strptime(date, "%Y%m%d").date().isoformat()
assert "lstchain_version" in run_summary_table.meta
assert "run_id" in run_summary_table.columns
assert "n_subruns" in run_summary_table.columns
assert "run_type" in run_summary_table.columns
assert "ucts_timestamp" in run_summary_table.columns
assert "run_start" in run_summary_table.columns
assert "dragon_reference_time" in run_summary_table.columns
assert "dragon_reference_module_id" in run_summary_table.columns
assert "dragon_reference_module_index" in run_summary_table.columns
assert "dragon_reference_counter" in run_summary_table.columns
assert "dragon_reference_source" in run_summary_table.columns
| [
"subprocess.run",
"astropy.table.Table.read",
"pandas.read_hdf",
"astropy.time.Time",
"lstchain.io.io.read_data_dl2_to_QTable",
"numpy.testing.assert_allclose",
"pytest.fixture",
"lstchain.io.io.get_dataset_keys",
"datetime.datetime.strptime",
"pytest.mark.parametrize",
"pkg_resources.iter_entry... | [((944, 990), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""script"""', 'ALL_SCRIPTS'], {}), "('script', ALL_SCRIPTS)\n", (967, 990), False, 'import pytest\n'), ((1114, 1145), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1128, 1145), False, 'import pytest\n'), ((1962, 1993), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (1976, 1993), False, 'import pytest\n'), ((687, 751), 'subprocess.run', 'sp.run', (['args'], {'stdout': 'sp.PIPE', 'stderr': 'sp.STDOUT', 'encoding': '"""utf-8"""'}), "(args, stdout=sp.PIPE, stderr=sp.STDOUT, encoding='utf-8')\n", (693, 751), True, 'import subprocess as sp\n'), ((1613, 1679), 'pandas.read_hdf', 'pd.read_hdf', (['simulated_dl1_file'], {'key': 'dl1_params_src_dep_lstcam_key'}), '(simulated_dl1_file, key=dl1_params_src_dep_lstcam_key)\n', (1624, 1679), True, 'import pandas as pd\n'), ((2142, 2215), 'shutil.copy', 'shutil.copy', (['simulated_dl1_file', "(temp_dir_simulated_files / 'dl1_copy.h5')"], {}), "(simulated_dl1_file, temp_dir_simulated_files / 'dl1_copy.h5')\n", (2153, 2215), False, 'import shutil\n'), ((3083, 3154), 'pandas.read_hdf', 'pd.read_hdf', (["observed_dl1_files['dl1_file1']"], {'key': 'dl1_params_lstcam_key'}), "(observed_dl1_files['dl1_file1'], key=dl1_params_lstcam_key)\n", (3094, 3154), True, 'import pandas as pd\n'), ((3412, 3461), 'lstchain.io.io.get_dataset_keys', 'get_dataset_keys', (["observed_dl1_files['dl1_file1']"], {}), "(observed_dl1_files['dl1_file1'])\n", (3428, 3461), False, 'from lstchain.io.io import dl1_params_lstcam_key, dl2_params_lstcam_key, get_dataset_keys, dl1_params_src_dep_lstcam_key\n'), ((4585, 4658), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (["dl1_df['dragon_time']", "dl1_df['trigger_time']"], {}), "(dl1_df['dragon_time'], dl1_df['trigger_time'])\n", (4611, 4658), True, 'import numpy as np\n'), ((6209, 6280), 'pandas.read_hdf', 'pd.read_hdf', (["observed_dl1_files['dl1_file1']"], {'key': 'dl1_params_lstcam_key'}), "(observed_dl1_files['dl1_file1'], key=dl1_params_lstcam_key)\n", (6220, 6280), True, 'import pandas as pd\n'), ((6295, 6366), 'pandas.read_hdf', 'pd.read_hdf', (["observed_dl1_files['dl1_file1']"], {'key': 'dl1_params_lstcam_key'}), "(observed_dl1_files['dl1_file1'], key=dl1_params_lstcam_key)\n", (6306, 6366), True, 'import pandas as pd\n'), ((6387, 6451), 'pandas.read_hdf', 'pd.read_hdf', (['merged_dl1_observed_file'], {'key': 'dl1_params_lstcam_key'}), '(merged_dl1_observed_file, key=dl1_params_lstcam_key)\n', (6398, 6451), True, 'import pandas as pd\n'), ((7831, 7889), 'pandas.read_hdf', 'pd.read_hdf', (['simulated_dl2_file'], {'key': 'dl2_params_lstcam_key'}), '(simulated_dl2_file, key=dl2_params_lstcam_key)\n', (7842, 7889), True, 'import pandas as pd\n'), ((8325, 8382), 'pandas.read_hdf', 'pd.read_hdf', (['observed_dl2_file'], {'key': 'dl2_params_lstcam_key'}), '(observed_dl2_file, key=dl2_params_lstcam_key)\n', (8336, 8382), True, 'import pandas as pd\n'), ((9108, 9160), 'pandas.read_hdf', 'pd.read_hdf', (['output_dl1ab'], {'key': 'dl1_params_lstcam_key'}), '(output_dl1ab, key=dl1_params_lstcam_key)\n', (9119, 9160), True, 'import pandas as pd\n'), ((9171, 9242), 'pandas.read_hdf', 'pd.read_hdf', (["observed_dl1_files['dl1_file1']"], {'key': 'dl1_params_lstcam_key'}), "(observed_dl1_files['dl1_file1'], key=dl1_params_lstcam_key)\n", (9182, 9242), True, 'import pandas as pd\n'), ((9247, 9313), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['dl1', 'dl1ab'], {'rtol': '(0.001)', 'equal_nan': '(True)'}), '(dl1, dl1ab, rtol=0.001, equal_nan=True)\n', (9273, 9313), True, 'import numpy as np\n'), ((9437, 9495), 'pandas.read_hdf', 'pd.read_hdf', (['simulated_dl1_file'], {'key': 'dl1_params_lstcam_key'}), '(simulated_dl1_file, key=dl1_params_lstcam_key)\n', (9448, 9495), True, 'import pandas as pd\n'), ((9511, 9566), 'pandas.read_hdf', 'pd.read_hdf', (['simulated_dl1ab'], {'key': 'dl1_params_lstcam_key'}), '(simulated_dl1ab, key=dl1_params_lstcam_key)\n', (9522, 9566), True, 'import pandas as pd\n'), ((9571, 9644), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['dl1_df', 'dl1ab_df'], {'rtol': '(0.0001)', 'equal_nan': '(True)'}), '(dl1_df, dl1ab_df, rtol=0.0001, equal_nan=True)\n', (9597, 9644), True, 'import numpy as np\n'), ((10192, 10233), 'lstchain.io.io.read_mc_dl2_to_QTable', 'read_mc_dl2_to_QTable', (['simulated_dl2_file'], {}), '(simulated_dl2_file)\n', (10213, 10233), False, 'from lstchain.io.io import read_mc_dl2_to_QTable\n'), ((10626, 10669), 'lstchain.io.io.read_data_dl2_to_QTable', 'read_data_dl2_to_QTable', (['real_data_dl2_file'], {}), '(real_data_dl2_file)\n', (10649, 10669), False, 'from lstchain.io.io import read_data_dl2_to_QTable\n'), ((10936, 10964), 'astropy.table.Table.read', 'Table.read', (['run_summary_path'], {}), '(run_summary_path)\n', (10946, 10964), False, 'from astropy.table import Table\n'), ((6612, 6654), 'lstchain.io.io.get_dataset_keys', 'get_dataset_keys', (['merged_dl1_observed_file'], {}), '(merged_dl1_observed_file)\n', (6628, 6654), False, 'from lstchain.io.io import dl1_params_lstcam_key, dl2_params_lstcam_key, get_dataset_keys, dl1_params_src_dep_lstcam_key\n'), ((6727, 6769), 'lstchain.io.io.get_dataset_keys', 'get_dataset_keys', (['merged_dl1_observed_file'], {}), '(merged_dl1_observed_file)\n', (6743, 6769), False, 'from lstchain.io.io import dl1_params_lstcam_key, dl2_params_lstcam_key, get_dataset_keys, dl1_params_src_dep_lstcam_key\n'), ((471, 521), 'pkg_resources.iter_entry_points', 'pkg_resources.iter_entry_points', (['"""console_scripts"""'], {}), "('console_scripts')\n", (502, 521), False, 'import pkg_resources\n'), ((4422, 4464), 'astropy.time.Time', 'Time', (['first_event_timestamp'], {'format': '"""unix"""'}), "(first_event_timestamp, format='unix')\n", (4426, 4464), False, 'from astropy.time import Time\n'), ((4479, 4547), 'astropy.time.Time', 'Time', (['(first_timestamp_nightsummary / 1000000000.0)'], {'format': '"""unix_tai"""'}), "(first_timestamp_nightsummary / 1000000000.0, format='unix_tai')\n", (4483, 4547), False, 'from astropy.time import Time\n'), ((11011, 11044), 'datetime.datetime.strptime', 'datetime.strptime', (['date', '"""%Y%m%d"""'], {}), "(date, '%Y%m%d')\n", (11028, 11044), False, 'from datetime import datetime\n')] |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
# Dicrease color
def dic_color(img):
img //= 63
img = img * 64 + 32
return img
# Database
def get_DB():
# get training image path
train = glob("dataset/train_*")
train.sort()
# prepare database
db = np.zeros((len(train), 13), dtype=np.int32)
# prepare path database
pdb = []
# each image
for i, path in enumerate(train):
# read image
img = dic_color(cv2.imread(path))
#get histogram
for j in range(4):
db[i, j] = len(np.where(img[..., 0] == (64 * j + 32))[0])
db[i, j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0])
db[i, j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0])
# get class
if 'akahara' in path:
cls = 0
elif 'madara' in path:
cls = 1
# store class label
db[i, -1] = cls
# store image path
pdb.append(path)
return db, pdb
# test
def test_DB(db, pdb):
# get test image path
test = glob("dataset/test_*")
test.sort()
success_num = 0.
# each image
for path in test:
# read image
img = dic_color(cv2.imread(path))
# get histogram
hist = np.zeros(12, dtype=np.int32)
for j in range(4):
hist[j] = len(np.where(img[..., 0] == (64 * j + 32))[0])
hist[j+4] = len(np.where(img[..., 1] == (64 * j + 32))[0])
hist[j+8] = len(np.where(img[..., 2] == (64 * j + 32))[0])
# get histogram difference
difs = np.abs(db[:, :12] - hist)
difs = np.sum(difs, axis=1)
# get argmin of difference
pred_i = np.argmin(difs)
# get prediction label
pred = db[pred_i, -1]
if pred == 0:
pl = "akahara"
elif pred == 1:
pl = "madara"
print(path, "is similar >>", pdb[pred_i], " Pred >>", pl)
db, pdb = get_DB()
test_DB(db, pdb) | [
"numpy.abs",
"numpy.sum",
"numpy.zeros",
"numpy.argmin",
"cv2.imread",
"numpy.where",
"glob.glob"
] | [((244, 267), 'glob.glob', 'glob', (['"""dataset/train_*"""'], {}), "('dataset/train_*')\n", (248, 267), False, 'from glob import glob\n'), ((1101, 1123), 'glob.glob', 'glob', (['"""dataset/test_*"""'], {}), "('dataset/test_*')\n", (1105, 1123), False, 'from glob import glob\n'), ((1305, 1333), 'numpy.zeros', 'np.zeros', (['(12)'], {'dtype': 'np.int32'}), '(12, dtype=np.int32)\n', (1313, 1333), True, 'import numpy as np\n'), ((1623, 1648), 'numpy.abs', 'np.abs', (['(db[:, :12] - hist)'], {}), '(db[:, :12] - hist)\n', (1629, 1648), True, 'import numpy as np\n'), ((1664, 1684), 'numpy.sum', 'np.sum', (['difs'], {'axis': '(1)'}), '(difs, axis=1)\n', (1670, 1684), True, 'import numpy as np\n'), ((1738, 1753), 'numpy.argmin', 'np.argmin', (['difs'], {}), '(difs)\n', (1747, 1753), True, 'import numpy as np\n'), ((503, 519), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (513, 519), False, 'import cv2\n'), ((1247, 1263), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1257, 1263), False, 'import cv2\n'), ((599, 635), 'numpy.where', 'np.where', (['(img[..., 0] == 64 * j + 32)'], {}), '(img[..., 0] == 64 * j + 32)\n', (607, 635), True, 'import numpy as np\n'), ((671, 707), 'numpy.where', 'np.where', (['(img[..., 1] == 64 * j + 32)'], {}), '(img[..., 1] == 64 * j + 32)\n', (679, 707), True, 'import numpy as np\n'), ((743, 779), 'numpy.where', 'np.where', (['(img[..., 2] == 64 * j + 32)'], {}), '(img[..., 2] == 64 * j + 32)\n', (751, 779), True, 'import numpy as np\n'), ((1387, 1423), 'numpy.where', 'np.where', (['(img[..., 0] == 64 * j + 32)'], {}), '(img[..., 0] == 64 * j + 32)\n', (1395, 1423), True, 'import numpy as np\n'), ((1458, 1494), 'numpy.where', 'np.where', (['(img[..., 1] == 64 * j + 32)'], {}), '(img[..., 1] == 64 * j + 32)\n', (1466, 1494), True, 'import numpy as np\n'), ((1529, 1565), 'numpy.where', 'np.where', (['(img[..., 2] == 64 * j + 32)'], {}), '(img[..., 2] == 64 * j + 32)\n', (1537, 1565), True, 'import numpy as np\n')] |
import numpy as np
import gym
from typing import List, Optional
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.typing import ModelConfigDict, TensorType
tf1, tf, tfv = try_import_tf()
class DDPGTFModel(TFModelV2):
"""Extension of standard TFModel to provide DDPG action- and q-outputs.
Data flow:
obs -> forward() -> model_out
model_out -> get_policy_output() -> deterministic actions
model_out, actions -> get_q_values() -> Q(s, a)
model_out, actions -> get_twin_q_values() -> Q_twin(s, a)
Note that this class by itself is not a valid model unless you
implement forward() in a subclass."""
def __init__(
self,
obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
num_outputs: int,
model_config: ModelConfigDict,
name: str,
# Extra DDPGActionModel args:
actor_hiddens: Optional[List[int]] = None,
actor_hidden_activation: str = "relu",
critic_hiddens: Optional[List[int]] = None,
critic_hidden_activation: str = "relu",
output_layer_activation: str = "softmax",
twin_q: bool = False,
add_layer_norm: bool = False,
):
"""Initialize variables of this model.
Extra model kwargs:
actor_hiddens (list): Defines size of hidden layers for the DDPG
policy head.
These will be used to postprocess the model output for the
purposes of computing deterministic actions.
Note that the core layers for forward() are not defined here, this
only defines the layers for the DDPG head. Those layers for forward()
should be defined in subclasses of DDPGActionModel.
"""
if actor_hiddens is None:
actor_hiddens = [256, 256]
if critic_hiddens is None:
critic_hiddens = [256, 256]
super(DDPGTFModel, self).__init__(
obs_space, action_space, num_outputs, model_config, name
)
actor_hidden_activation = getattr(tf.nn, actor_hidden_activation, tf.nn.relu)
critic_hidden_activation = getattr(tf.nn, critic_hidden_activation, tf.nn.relu)
output_layer_activation = getattr(tf.nn, output_layer_activation, tf.nn.softmax)
self.model_out = tf.keras.layers.Input(shape=(num_outputs,), name="model_out")
self.bounded = np.logical_and(
action_space.bounded_above, action_space.bounded_below
).any()
self.action_dim = action_space.shape[0]
if actor_hiddens:
last_layer = self.model_out
for i, n in enumerate(actor_hiddens):
last_layer = tf.keras.layers.Dense(
n,
name="actor_hidden_{}".format(i),
activation=actor_hidden_activation,
)(last_layer)
if add_layer_norm:
last_layer = tf.keras.layers.LayerNormalization(
name="LayerNorm_{}".format(i)
)(last_layer)
actor_out = tf.keras.layers.Dense(
self.action_dim, activation=output_layer_activation, name="actor_out"
)(last_layer)
else:
actor_out = self.model_out
# Use sigmoid to scale to [0,1], but also double magnitude of input to
# emulate behaviour of tanh activation used in DDPG and TD3 papers.
# After sigmoid squashing, re-scale to env action space bounds.
def lambda_(x):
action_range = (action_space.high - action_space.low)[None]
low_action = action_space.low[None]
sigmoid_out = tf.nn.sigmoid(2 * x)
squashed = action_range * sigmoid_out + low_action
return squashed
# Only squash if we have bounded actions.
if self.bounded:
actor_out = tf.keras.layers.Lambda(lambda_)(actor_out)
self.policy_model = tf.keras.Model(self.model_out, actor_out)
# Build the Q-model(s).
self.actions_input = tf.keras.layers.Input(
shape=(self.action_dim,), name="actions"
)
def build_q_net(name, observations, actions):
# For continuous actions: Feed obs and actions (concatenated)
# through the NN.
q_net = tf.keras.Sequential(
[
tf.keras.layers.Concatenate(axis=1),
]
+ [
tf.keras.layers.Dense(
units=units,
activation=critic_hidden_activation,
name="{}_hidden_{}".format(name, i),
)
for i, units in enumerate(critic_hiddens)
]
+ [
tf.keras.layers.Dense(
units=1, activation=None, name="{}_out".format(name)
)
]
)
q_net = tf.keras.Model(
[observations, actions], q_net([observations, actions])
)
return q_net
self.q_model = build_q_net("q", self.model_out, self.actions_input)
if twin_q:
self.twin_q_model = build_q_net(
"twin_q", self.model_out, self.actions_input
)
else:
self.twin_q_model = None
def get_q_values(self, model_out: TensorType, actions: TensorType) -> TensorType:
"""Return the Q estimates for the most recent forward pass.
This implements Q(s, a).
Args:
model_out (Tensor): obs embeddings from the model layers, of shape
[BATCH_SIZE, num_outputs].
actions (Tensor): Actions to return the Q-values for.
Shape: [BATCH_SIZE, action_dim].
Returns:
tensor of shape [BATCH_SIZE].
"""
if actions is not None:
return self.q_model([model_out, actions])
else:
return self.q_model(model_out)
def get_twin_q_values(
self, model_out: TensorType, actions: TensorType
) -> TensorType:
"""Same as get_q_values but using the twin Q net.
This implements the twin Q(s, a).
Args:
model_out (Tensor): obs embeddings from the model layers, of shape
[BATCH_SIZE, num_outputs].
actions (Tensor): Actions to return the Q-values for.
Shape: [BATCH_SIZE, action_dim].
Returns:
tensor of shape [BATCH_SIZE].
"""
if actions is not None:
return self.twin_q_model([model_out, actions])
else:
return self.twin_q_model(model_out)
def get_policy_output(self, model_out: TensorType) -> TensorType:
"""Return the action output for the most recent forward pass.
This outputs the support for pi(s). For continuous action spaces, this
is the action directly.
Args:
model_out (Tensor): obs embeddings from the model layers, of shape
[BATCH_SIZE, num_outputs].
Returns:
tensor of shape [BATCH_SIZE, action_out_size]
"""
return self.policy_model(model_out)
def policy_variables(self) -> List[TensorType]:
"""Return the list of variables for the policy net."""
return list(self.policy_model.variables)
def q_variables(self) -> List[TensorType]:
"""Return the list of variables for Q / twin Q nets."""
return self.q_model.variables + (
self.twin_q_model.variables if self.twin_q_model else []
)
| [
"ray.rllib.utils.framework.try_import_tf",
"numpy.logical_and"
] | [((249, 264), 'ray.rllib.utils.framework.try_import_tf', 'try_import_tf', ([], {}), '()\n', (262, 264), False, 'from ray.rllib.utils.framework import try_import_tf\n'), ((2472, 2542), 'numpy.logical_and', 'np.logical_and', (['action_space.bounded_above', 'action_space.bounded_below'], {}), '(action_space.bounded_above, action_space.bounded_below)\n', (2486, 2542), True, 'import numpy as np\n')] |
#%%
from os import listdir
import pandas as pd
import numpy as np
from numpy import linalg as LA
import re
from pathlib import Path
#%%
def calculate_area(path):
f = open(path,'r')
lines = f.readlines()
if len(lines) > 4:
wanted_lines = [3,4]
cmpt = 1
#vector1
x = np.array(re.findall("\d+\.\d+", lines[2]))
vector1 = x.astype(np.float)
#vector2
x = np.array(re.findall("\d+\.\d+", lines[3]))
vector2 = x.astype(np.float)
v = np.cross(vector1, vector2)
area = LA.norm(v)
return area
#%%
calculate_area('./R2/CONTCARs/Ag1Bi1P2Se6-Zr1Cl2/CONTCAR')
#%%
i=0
dirctories = listdir(r'./R2/CONTCARs')
areas = {}
#%%
# area calculation
for dirctory in dirctories:
path = './R2/CONTCARs/'+dirctory+'/CONTCAR'
my_file = Path(path)
if my_file.is_file():
areas[dirctory] = calculate_area(path)
i += 1
#%%
#areas
df = pd.DataFrame.from_dict(areas, orient='index', columns=['Area'])
df.index.name = 'Bilayer'
df = df.reset_index()
df['Name'] = df['Bilayer'].apply(
lambda x: x.replace('-T-', '-T_')
if x.find('-T-') != -1
else x.replace('-', '_', 1))
# %%
df[['Name', 'Area']].to_csv('./R2/areas.csv',index=False)
# %%
| [
"pandas.DataFrame.from_dict",
"numpy.cross",
"pathlib.Path",
"re.findall",
"numpy.linalg.norm",
"os.listdir"
] | [((677, 701), 'os.listdir', 'listdir', (['"""./R2/CONTCARs"""'], {}), "('./R2/CONTCARs')\n", (684, 701), False, 'from os import listdir\n'), ((943, 1006), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['areas'], {'orient': '"""index"""', 'columns': "['Area']"}), "(areas, orient='index', columns=['Area'])\n", (965, 1006), True, 'import pandas as pd\n'), ((828, 838), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (832, 838), False, 'from pathlib import Path\n'), ((516, 542), 'numpy.cross', 'np.cross', (['vector1', 'vector2'], {}), '(vector1, vector2)\n', (524, 542), True, 'import numpy as np\n'), ((558, 568), 'numpy.linalg.norm', 'LA.norm', (['v'], {}), '(v)\n', (565, 568), True, 'from numpy import linalg as LA\n'), ((321, 356), 're.findall', 're.findall', (['"""\\\\d+\\\\.\\\\d+"""', 'lines[2]'], {}), "('\\\\d+\\\\.\\\\d+', lines[2])\n", (331, 356), False, 'import re\n'), ((431, 466), 're.findall', 're.findall', (['"""\\\\d+\\\\.\\\\d+"""', 'lines[3]'], {}), "('\\\\d+\\\\.\\\\d+', lines[3])\n", (441, 466), False, 'import re\n')] |
import random
import numpy as np
from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage
class Augmenter:
def __init__(self, name, method, action, aug_min, aug_p=0.1, verbose=0):
self.name = name
self.action = action
self.method = method
self.aug_min = aug_min
self.aug_p = aug_p
self.verbose = verbose
self.augments = []
self._validate_augmenter(method, action)
@classmethod
def _validate_augmenter(cls, method, action):
if method not in Method.getall():
raise ValueError(
'Method must be one of {} while {} is passed'.format(Method.getall(), method))
if action not in Action.getall():
raise ValueError(
'Action must be one of {} while {} is passed'.format(Action.getall(), action))
def augment(self, data, n=1):
"""
:param object data: Data for augmentation
:param int n: Number of unique augmented output
:return: Augmented data
>>> augmented_data = aug.augment(data)
"""
exceptions = self._validate_augment(data)
# TODO: Handle multiple exceptions
for exception in exceptions:
if isinstance(exception, WarningException):
if self.verbose > 0:
exception.output()
# Return empty value per data type
if isinstance(data, str):
return ''
elif isinstance(data, list):
return []
elif isinstance(data, np.ndarray):
return np.array([])
return None
results = [data]
for _ in range(n*5):
if self.action == Action.INSERT:
result = self.insert(self.clean(data))
elif self.action == Action.SUBSTITUTE:
result = self.substitute(self.clean(data))
elif self.action == Action.SWAP:
result = self.swap(self.clean(data))
elif self.action == Action.DELETE:
result = self.delete(self.clean(data))
elif self.action == Action.SPLIT:
result = self.split(self.clean(data))
if not self.is_duplicate(results, result):
results.append(result)
if len(results) >= n+1:
break
# only have input data
if len(results) == 1:
if n == 1:
return results[0]
else:
return [results[0]]
# return 1 record as n == 1
if n == 1 and len(results) >= 2:
return results[1]
# return all records
return results[1:]
@classmethod
def _validate_augment(cls, data):
if data is None or len(data) == 0:
return [WarningException(name=WarningName.INPUT_VALIDATION_WARNING,
code=WarningCode.WARNING_CODE_001, msg=WarningMessage.LENGTH_IS_ZERO)]
return []
def insert(self, data):
raise NotImplementedError
def substitute(self, data):
raise NotImplementedError
def swap(self, data):
raise NotImplementedError
def delete(self, data):
raise NotImplementedError
def split(self, data):
raise NotImplementedError
def tokenizer(self, tokens):
raise NotImplementedError
def evaluate(self):
raise NotImplementedError
@classmethod
def is_duplicate(cls, dataset, data):
raise NotImplementedError
@classmethod
def prob(cls):
return random.random()
@classmethod
def sample(cls, x, num):
if isinstance(x, list):
return random.sample(x, num)
elif isinstance(x, int):
return random.randint(1, x-1)
@classmethod
def clean(cls, data):
raise NotImplementedError
def generate_aug_cnt(self, size, aug_p=None):
if aug_p is not None:
percent = aug_p
elif self.aug_p is not None:
percent = self.aug_p
else:
percent = 0.3
cnt = int(percent * size)
return cnt if cnt > self.aug_min else self.aug_min
def generate_aug_idxes(self, inputs):
aug_cnt = self.generate_aug_cnt(len(inputs))
token_idxes = [i for i, _ in enumerate(inputs)]
aug_idxes = self.sample(token_idxes, aug_cnt)
return aug_idxes
def __str__(self):
return 'Name:{}, Action:{}, Method:{}'.format(self.name, self.action, self.method)
| [
"nlpaug.util.Action.getall",
"nlpaug.util.WarningException",
"random.randint",
"random.sample",
"random.random",
"numpy.array",
"nlpaug.util.Method.getall"
] | [((3661, 3676), 'random.random', 'random.random', ([], {}), '()\n', (3674, 3676), False, 'import random\n'), ((572, 587), 'nlpaug.util.Method.getall', 'Method.getall', ([], {}), '()\n', (585, 587), False, 'from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage\n'), ((740, 755), 'nlpaug.util.Action.getall', 'Action.getall', ([], {}), '()\n', (753, 755), False, 'from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage\n'), ((3775, 3796), 'random.sample', 'random.sample', (['x', 'num'], {}), '(x, num)\n', (3788, 3796), False, 'import random\n'), ((2885, 3019), 'nlpaug.util.WarningException', 'WarningException', ([], {'name': 'WarningName.INPUT_VALIDATION_WARNING', 'code': 'WarningCode.WARNING_CODE_001', 'msg': 'WarningMessage.LENGTH_IS_ZERO'}), '(name=WarningName.INPUT_VALIDATION_WARNING, code=\n WarningCode.WARNING_CODE_001, msg=WarningMessage.LENGTH_IS_ZERO)\n', (2901, 3019), False, 'from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage\n'), ((3849, 3873), 'random.randint', 'random.randint', (['(1)', '(x - 1)'], {}), '(1, x - 1)\n', (3863, 3873), False, 'import random\n'), ((688, 703), 'nlpaug.util.Method.getall', 'Method.getall', ([], {}), '()\n', (701, 703), False, 'from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage\n'), ((856, 871), 'nlpaug.util.Action.getall', 'Action.getall', ([], {}), '()\n', (869, 871), False, 'from nlpaug.util import Action, Method, WarningException, WarningName, WarningCode, WarningMessage\n'), ((1667, 1679), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1675, 1679), True, 'import numpy as np\n')] |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Functions for performing PSF fitting photometry on 2-D arrays."""
from __future__ import division
import warnings
import numpy as np
from astropy.modeling.parameters import Parameter
from astropy.utils.exceptions import AstropyUserWarning
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling import Fittable2DModel
from imageutils import (extract_array_2d, subpixel_indices, add_array_2d,
mask_to_mirrored_num)
__all__ = ['DiscretePRF', 'create_prf', 'psf_photometry',
'GaussianPSF', 'subtract_psf']
class DiscretePRF(Fittable2DModel):
"""
A discrete PRF model.
The discrete PRF model stores images of the PRF at different subpixel
positions or offsets as a lookup table. The resolution is given by the
subsampling parameter, which states in how many subpixels a pixel is
divided.
The discrete PRF model class in initialized with a 4 dimensional
array, that contains the PRF images at different subpixel positions.
The definition of the axes is as following:
1. Axis: y subpixel position
2. Axis: x subpixel position
3. Axis: y direction of the PRF image
4. Axis: x direction of the PRF image
The total array therefore has the following shape
(subsampling, subsampling, prf_size, prf_size)
Parameters
----------
prf_array : ndarray
Array containing PRF images.
normalize : bool
Normalize PRF images to unity.
subsampling : int, optional
Factor of subsampling. Default = 1.
"""
amplitude = Parameter('amplitude')
x_0 = Parameter('x_0')
y_0 = Parameter('y_0')
linear = True
def __init__(self, prf_array, normalize=True, subsampling=1):
# Array shape and dimension check
if subsampling == 1:
if prf_array.ndim == 2:
prf_array = np.array([[prf_array]])
if prf_array.ndim != 4:
raise TypeError('Array must have 4 dimensions.')
if prf_array.shape[:2] != (subsampling, subsampling):
raise TypeError('Incompatible subsampling and array size')
if np.isnan(prf_array).any():
raise Exception("Array contains NaN values. Can't create PRF.")
# Normalize if requested
if normalize:
for i in range(prf_array.shape[0]):
for j in range(prf_array.shape[1]):
prf_array[i, j] /= prf_array[i, j].sum()
# Set PRF asttributes
self._prf_array = prf_array
self.subsampling = subsampling
constraints = {'fixed': {'x_0': True, 'y_0': True}}
x_0 = 0
y_0 = 0
amplitude = 1
super(DiscretePRF, self).__init__(n_models=1, x_0=x_0, y_0=y_0,
amplitude=amplitude, **constraints)
self.fitter = LevMarLSQFitter()
# Fix position per default
self.x_0.fixed = True
self.y_0.fixed = True
@property
def shape(self):
"""
Shape of the PRF image.
"""
return self._prf_array.shape[-2:]
def eval(self, x, y, amplitude, x_0, y_0):
"""
Discrete PRF model evaluation.
Given a certain position and amplitude the corresponding image of
the PSF is chosen and scaled to the amplitude. If x and y are
outside the boundaries of the image, zero will be returned.
Parameters
----------
x : float
x coordinate array in pixel coordinates.
y : float
y coordinate array in pixel coordinates.
amplitude : float
Model amplitude.
x_0 : float
x position of the center of the PRF.
y_0 : float
y position of the center of the PRF.
"""
# Convert x and y to index arrays
x = (x - int(x_0 + 0.5)).astype('int') + self.shape[1] // 2
y = (y - int(y_0 + 0.5)).astype('int') + self.shape[0] // 2
# Get subpixel indices
x_sub, y_sub = subpixel_indices((x_0, y_0), self.subsampling)
# Out of boundary masks
x_bound = np.logical_or(x < 0, x >= self.shape[1])
y_bound = np.logical_or(y < 0, y >= self.shape[0])
out_of_bounds = np.logical_or(x_bound, y_bound)
# Set out of boundary indices to zero
x[x_bound] = 0
y[y_bound] = 0
result = amplitude * self._prf_array[y_sub, x_sub][y, x]
# Set out of boundary values to zero
result[out_of_bounds] = 0
return result
def fit(self, data, indices):
"""
Fit PSF/PRF to data.
Fits the PSF/PRF to the data and returns the best fitting flux.
If the data contains NaN values or if the source is not completely
contained in the image data the fitting is omitted and a flux of 0
is returned.
For reasons of performance, indices for the data have to be created
outside and passed to the function.
The fit is performed on a slice of the data with the same size as
the PRF.
Parameters
----------
data : ndarray
Array containig image data.
indices : ndarray
Array with indices of the data. As
returned by np.indices(data.shape)
"""
# Extract sub array of the data of the size of the PRF grid
sub_array_data = extract_array_2d(data, self.shape,
(self.x_0.value, self.y_0.value))
# Fit only if PSF is completely contained in the image and no NaN
# values are present
if sub_array_data.shape == self.shape and not np.isnan(sub_array_data).any():
y = extract_array_2d(indices[0], self.shape,
(self.x_0.value, self.y_0.value))
x = extract_array_2d(indices[1], self.shape,
(self.x_0.value, self.y_0.value))
# TODO: It should be discussed whether this is the right place to fix
# the warning. Maybe it should be handled better in astropy.modeling.fitting
with warnings.catch_warnings():
warnings.simplefilter("ignore", AstropyUserWarning)
m = self.fitter(self, x, y, sub_array_data)
return m.amplitude.value
else:
return 0
class GaussianPSF(Fittable2DModel):
"""
Symmetrical Gaussian PSF model.
The PSF is evaluated by using the `scipy.special.erf` function
on a fixed grid of the size of 1 pixel to assure flux conservation
on subpixel scale.
Parameters
----------
sigma : float
Width of the Gaussian PSF.
amplitude : float (default 1)
Amplitude at the peak value.
x_0 : float (default 0)
Position of the peak in x direction.
y_0 : float (default 0)
Position of the peak in y direction.
Notes
-----
The PSF model is evaluated according to the following formula:
.. math::
f(x, y) =
\\frac{A}{4}
\\left[
\\textnormal{erf} \\left(\\frac{x - x_0 + 0.5}
{\\sqrt{2} \\sigma} \\right) -
\\textnormal{erf} \\left(\\frac{x - x_0 - 0.5}
{\\sqrt{2} \\sigma} \\right)
\\right]
\\left[
\\textnormal{erf} \\left(\\frac{y - y_0 + 0.5}
{\\sqrt{2} \\sigma} \\right) -
\\textnormal{erf} \\left(\\frac{y - y_0 - 0.5}
{\\sqrt{2} \\sigma} \\right)
\\right]
Where ``erf`` denotes the error function.
"""
amplitude = Parameter('amplitude')
x_0 = Parameter('x_0')
y_0 = Parameter('y_0')
sigma = Parameter('sigma')
_erf = None
def __init__(self, sigma, amplitude=1, x_0=0, y_0=0):
if self._erf is None:
from scipy.special import erf
self.__class__._erf = erf
constraints = {'fixed': {'x_0': True, 'y_0': True, 'sigma': True}}
super(GaussianPSF, self).__init__(n_models=1, sigma=sigma,
x_0=x_0, y_0=y_0,
amplitude=amplitude, **constraints)
# Default size is 8 * sigma
self.shape = (int(8 * sigma) + 1, int(8 * sigma) + 1)
self.fitter = LevMarLSQFitter()
# Fix position per default
self.x_0.fixed = True
self.y_0.fixed = True
def eval(self, x, y, amplitude, x_0, y_0, sigma):
"""
Model function Gaussian PSF model.
"""
return amplitude / 4 * ((self._erf((x - x_0 + 0.5) / (np.sqrt(2) * sigma))
- self._erf((x - x_0 - 0.5) / (np.sqrt(2) * sigma)))
* (self._erf((y - y_0 + 0.5) / (np.sqrt(2) * sigma))
- self._erf((y - y_0 - 0.5) / (np.sqrt(2) * sigma))))
def fit(self, data, indices):
"""
Fit PSF/PRF to data.
Fits the PSF/PRF to the data and returns the best fitting flux.
If the data contains NaN values or if the source is not completely
contained in the image data the fitting is omitted and a flux of 0
is returned.
For reasons of performance, indices for the data have to be created
outside and passed to the function.
The fit is performed on a slice of the data with the same size as
the PRF.
Parameters
----------
data : ndarray
Array containig image data.
indices : ndarray
Array with indices of the data. As
returned by np.indices(data.shape)
Returns
-------
flux : float
Best fit flux value. Returns flux = 0 if PSF is not completely
contained in the image or if NaN values are present.
"""
# Set position
position = (self.x_0.value, self.y_0.value)
# Extract sub array with data of interest
sub_array_data = extract_array_2d(data, self.shape, position)
# Fit only if PSF is completely contained in the image and no NaN
# values are present
if sub_array_data.shape == self.shape and not np.isnan(sub_array_data).any():
y = extract_array_2d(indices[0], self.shape, position)
x = extract_array_2d(indices[1], self.shape, position)
m = self.fitter(self, x, y, sub_array_data)
return m.amplitude.value
else:
return 0
def psf_photometry(data, positions, psf, mask=None, mode='sequential',
tune_coordinates=False):
"""
Perform PSF/PRF photometry on the data.
Given a PSF or PRF model, the model is fitted simultaneously or
sequentially to the given positions to obtain an estimate of the
flux. If required, coordinates are also tuned to match best the data.
If the data contains NaN values or the PSF/PRF is not completely
contained in the image, a flux of zero is returned.
Parameters
----------
data : ndarray
Image data array
positions : List or array
List of positions in pixel coordinates
where to fit the PSF/PRF.
psf : `photutils.psf.DiscretePRF` or `photutils.psf.GaussianPSF`
PSF/PRF model to fit to the data.
mask : ndarray, optional
Mask to be applied to the data.
mode : {'sequential', 'simultaneous'}
One of the following modes to do PSF/PRF photometry:
* 'simultaneous'
Fit PSF/PRF simultaneous to all given positions.
* 'sequential' (default)
Fit PSF/PRF one after another to the given positions .
Examples
--------
See `Spitzer PSF Photometry <http://nbviewer.ipython.org/gist/adonath/
6550989/PSFPhotometrySpitzer.ipynb>`_ for a short tutorial.
"""
# Check input array type and dimension.
if np.iscomplexobj(data):
raise TypeError('Complex type not supported')
if data.ndim != 2:
raise ValueError('{0}-d array not supported. '
'Only 2-d arrays supported.'.format(data.ndim))
# Fit coordinates if requested
if tune_coordinates:
psf.fixed['x_0'] = False
psf.fixed['y_0'] = False
# Actual photometry
result = np.array([])
indices = np.indices(data.shape)
if mode == 'simultaneous':
raise NotImplementedError('Simultaneous mode not implemented')
elif mode == 'sequential':
for i, position in enumerate(positions):
psf.x_0, psf.y_0 = position
flux = psf.fit(data, indices)
result = np.append(result, flux)
else:
raise Exception('Invalid photometry mode.')
return result
def create_prf(data, positions, size, fluxes=None, mask=None, mode='mean',
subsampling=1, fix_nan=False):
"""
Estimate point response function (PRF) from image data.
Given a list of positions and size this function estimates an image of
the PRF by extracting and combining the individual PRFs from the given
positions. Different modes of combining are available.
NaN values are either ignored by passing a mask or can be replaced by
the mirrored value with respect to the center of the PRF.
Furthermore it is possible to specify fluxes to have a correct
normalization of the individual PRFs. Otherwise the flux is estimated from
a quadratic aperture of the same size as the PRF image.
Parameters
----------
data : array
Data array
positions : List or array
List of pixel coordinate source positions to use in creating the PRF.
size : odd int
Size of the quadratic PRF image in pixels.
mask : bool array, optional
Boolean array to mask out bad values.
fluxes : array, optional
Object fluxes to normalize extracted PRFs.
mode : {'mean', 'median'}
One of the following modes to combine the extracted PRFs:
* 'mean'
Take the pixelwise mean of the extracted PRFs.
* 'median'
Take the pixelwise median of the extracted PRFs.
subsampling : int
Factor of subsampling of the PRF (default = 1).
fix_nan : bool
Fix NaN values in the data by replacing it with the
mirrored value. Assuming that the PRF is symmetrical.
Returns
-------
prf : `photutils.psf.DiscretePRF`
Discrete PRF model estimated from data.
Notes
-----
In Astronomy different definitions of Point Spread Function (PSF) and
Point Response Function (PRF) are used. Here we assume that the PRF is
an image of a point source after discretization e.g. with a CCD. This
definition is equivalent to the `Spitzer definiton of the PRF
<http://irsa.ipac.caltech.edu/data/SPITZER/docs/dataanalysistools/tools/mopex/mopexusersguide/89/>`_.
References
----------
`Spitzer PSF vs. PRF
<http://irsa.ipac.caltech.edu/data/SPITZER/docs/files/spitzer/PRF_vs_PSF.pdf>`_
`Kepler PSF calibration
<http://keplerscience.arc.nasa.gov/CalibrationPSF.shtml>`_
`The Kepler Pixel Response Function
<http://adsabs.harvard.edu/abs/2010ApJ...713L..97B>`_
"""
# Check input array type and dimension.
if np.iscomplexobj(data):
raise TypeError('Complex type not supported')
if data.ndim != 2:
raise ValueError('{0}-d array not supported. '
'Only 2-d arrays supported.'.format(data.ndim))
if size % 2 == 0:
raise TypeError("Size must be odd.")
if fluxes is not None and len(fluxes) != len(positions):
raise TypeError("Position and flux arrays must be of equal length.")
if mask is None:
mask = np.isnan(data)
if isinstance(positions, (list, tuple)):
positions = np.array(positions)
if isinstance(fluxes, (list, tuple)):
fluxes = np.array(fluxes)
if mode == 'mean':
combine = np.ma.mean
elif mode == 'median':
combine = np.ma.median
else:
raise Exception('Invalid mode to combine prfs.')
data_internal = np.ma.array(data=data, mask=mask)
prf_model = np.ndarray(shape=(subsampling, subsampling, size, size))
positions_subpixel_indices = np.array([subpixel_indices(_, subsampling)
for _ in positions])
for i in range(subsampling):
for j in range(subsampling):
extracted_sub_prfs = []
sub_prf_indices = np.all(positions_subpixel_indices == [j, i],
axis=1)
positions_sub_prfs = positions[sub_prf_indices]
for k, position in enumerate(positions_sub_prfs):
extracted_prf = extract_array_2d(data_internal, (size, size),
position)
# Check shape to exclude incomplete PRFs at the boundaries
# of the image
if extracted_prf.shape == (size, size) and np.ma.sum(extracted_prf) != 0:
# Replace NaN values by mirrored value, with respect
# to the prf's center
if fix_nan:
prf_nan = np.isnan(extracted_prf)
if prf_nan.any():
if prf_nan.sum() > 3 or prf_nan[size / 2, size / 2]:
continue
else:
extracted_prf = mask_to_mirrored_num(
extracted_prf, prf_nan)
# Normalize and add extracted PRF to data cube
if fluxes is None:
extracted_prf_norm = np.ma.copy(extracted_prf) / np.ma.sum(extracted_prf)
else:
fluxes_sub_prfs = fluxes[sub_prf_indices]
extracted_prf_norm = np.ma.copy(extracted_prf) / fluxes_sub_prfs[k]
extracted_sub_prfs.append(extracted_prf_norm)
else:
continue
prf_model[i, j] = np.ma.getdata(combine(np.ma.dstack(extracted_sub_prfs), axis=2))
return DiscretePRF(prf_model, subsampling=subsampling)
def subtract_psf(data, psf, positions, fluxes, mask=None):
"""
Removes PSF/PRF at the given positions.
To calculate residual images the PSF/PRF model is subtracted from the data
at the given positions.
Parameters
----------
data : ndarray
Image data.
psf : `photutils.psf.DiscretePRF` or `photutils.psf.GaussianPSF`
PSF/PRF model to be substracted from the data.
positions : ndarray
List of center positions where PSF/PRF is removed.
fluxes : ndarray
List of fluxes of the sources, for correct
normalization.
"""
# Set up indices
indices = np.indices(data.shape)
# Loop over position
for i, position in enumerate(positions):
y = extract_array_2d(indices[0], psf.shape, position)
x = extract_array_2d(indices[1], psf.shape, position)
psf_image = psf.eval(x, y, fluxes[i], position[0], position[1])
data = add_array_2d(data, -psf_image, position)
return data
| [
"numpy.ma.copy",
"numpy.ma.sum",
"imageutils.extract_array_2d",
"numpy.isnan",
"imageutils.subpixel_indices",
"numpy.ndarray",
"warnings.simplefilter",
"numpy.append",
"warnings.catch_warnings",
"numpy.ma.dstack",
"imageutils.mask_to_mirrored_num",
"numpy.indices",
"numpy.all",
"numpy.isco... | [((1652, 1674), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""amplitude"""'], {}), "('amplitude')\n", (1661, 1674), False, 'from astropy.modeling.parameters import Parameter\n'), ((1685, 1701), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""x_0"""'], {}), "('x_0')\n", (1694, 1701), False, 'from astropy.modeling.parameters import Parameter\n'), ((1712, 1728), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""y_0"""'], {}), "('y_0')\n", (1721, 1728), False, 'from astropy.modeling.parameters import Parameter\n'), ((7751, 7773), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""amplitude"""'], {}), "('amplitude')\n", (7760, 7773), False, 'from astropy.modeling.parameters import Parameter\n'), ((7784, 7800), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""x_0"""'], {}), "('x_0')\n", (7793, 7800), False, 'from astropy.modeling.parameters import Parameter\n'), ((7811, 7827), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""y_0"""'], {}), "('y_0')\n", (7820, 7827), False, 'from astropy.modeling.parameters import Parameter\n'), ((7840, 7858), 'astropy.modeling.parameters.Parameter', 'Parameter', (['"""sigma"""'], {}), "('sigma')\n", (7849, 7858), False, 'from astropy.modeling.parameters import Parameter\n'), ((12022, 12043), 'numpy.iscomplexobj', 'np.iscomplexobj', (['data'], {}), '(data)\n', (12037, 12043), True, 'import numpy as np\n'), ((12415, 12427), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (12423, 12427), True, 'import numpy as np\n'), ((12442, 12464), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (12452, 12464), True, 'import numpy as np\n'), ((15420, 15441), 'numpy.iscomplexobj', 'np.iscomplexobj', (['data'], {}), '(data)\n', (15435, 15441), True, 'import numpy as np\n'), ((16268, 16301), 'numpy.ma.array', 'np.ma.array', ([], {'data': 'data', 'mask': 'mask'}), '(data=data, mask=mask)\n', (16279, 16301), True, 'import numpy as np\n'), ((16318, 16374), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(subsampling, subsampling, size, size)'}), '(shape=(subsampling, subsampling, size, size))\n', (16328, 16374), True, 'import numpy as np\n'), ((19025, 19047), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (19035, 19047), True, 'import numpy as np\n'), ((2924, 2941), 'astropy.modeling.fitting.LevMarLSQFitter', 'LevMarLSQFitter', ([], {}), '()\n', (2939, 2941), False, 'from astropy.modeling.fitting import LevMarLSQFitter\n'), ((4103, 4149), 'imageutils.subpixel_indices', 'subpixel_indices', (['(x_0, y_0)', 'self.subsampling'], {}), '((x_0, y_0), self.subsampling)\n', (4119, 4149), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((4201, 4241), 'numpy.logical_or', 'np.logical_or', (['(x < 0)', '(x >= self.shape[1])'], {}), '(x < 0, x >= self.shape[1])\n', (4214, 4241), True, 'import numpy as np\n'), ((4260, 4300), 'numpy.logical_or', 'np.logical_or', (['(y < 0)', '(y >= self.shape[0])'], {}), '(y < 0, y >= self.shape[0])\n', (4273, 4300), True, 'import numpy as np\n'), ((4325, 4356), 'numpy.logical_or', 'np.logical_or', (['x_bound', 'y_bound'], {}), '(x_bound, y_bound)\n', (4338, 4356), True, 'import numpy as np\n'), ((5477, 5545), 'imageutils.extract_array_2d', 'extract_array_2d', (['data', 'self.shape', '(self.x_0.value, self.y_0.value)'], {}), '(data, self.shape, (self.x_0.value, self.y_0.value))\n', (5493, 5545), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((8447, 8464), 'astropy.modeling.fitting.LevMarLSQFitter', 'LevMarLSQFitter', ([], {}), '()\n', (8462, 8464), False, 'from astropy.modeling.fitting import LevMarLSQFitter\n'), ((10122, 10166), 'imageutils.extract_array_2d', 'extract_array_2d', (['data', 'self.shape', 'position'], {}), '(data, self.shape, position)\n', (10138, 10166), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((15891, 15905), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (15899, 15905), True, 'import numpy as np\n'), ((15972, 15991), 'numpy.array', 'np.array', (['positions'], {}), '(positions)\n', (15980, 15991), True, 'import numpy as np\n'), ((16052, 16068), 'numpy.array', 'np.array', (['fluxes'], {}), '(fluxes)\n', (16060, 16068), True, 'import numpy as np\n'), ((19131, 19180), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[0]', 'psf.shape', 'position'], {}), '(indices[0], psf.shape, position)\n', (19147, 19180), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((19193, 19242), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[1]', 'psf.shape', 'position'], {}), '(indices[1], psf.shape, position)\n', (19209, 19242), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((19330, 19370), 'imageutils.add_array_2d', 'add_array_2d', (['data', '(-psf_image)', 'position'], {}), '(data, -psf_image, position)\n', (19342, 19370), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((5794, 5868), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[0]', 'self.shape', '(self.x_0.value, self.y_0.value)'], {}), '(indices[0], self.shape, (self.x_0.value, self.y_0.value))\n', (5810, 5868), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((5918, 5992), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[1]', 'self.shape', '(self.x_0.value, self.y_0.value)'], {}), '(indices[1], self.shape, (self.x_0.value, self.y_0.value))\n', (5934, 5992), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((10373, 10423), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[0]', 'self.shape', 'position'], {}), '(indices[0], self.shape, position)\n', (10389, 10423), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((10440, 10490), 'imageutils.extract_array_2d', 'extract_array_2d', (['indices[1]', 'self.shape', 'position'], {}), '(indices[1], self.shape, position)\n', (10456, 10490), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((16418, 16450), 'imageutils.subpixel_indices', 'subpixel_indices', (['_', 'subsampling'], {}), '(_, subsampling)\n', (16434, 16450), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((16652, 16704), 'numpy.all', 'np.all', (['(positions_subpixel_indices == [j, i])'], {'axis': '(1)'}), '(positions_subpixel_indices == [j, i], axis=1)\n', (16658, 16704), True, 'import numpy as np\n'), ((1950, 1973), 'numpy.array', 'np.array', (['[[prf_array]]'], {}), '([[prf_array]])\n', (1958, 1973), True, 'import numpy as np\n'), ((2211, 2230), 'numpy.isnan', 'np.isnan', (['prf_array'], {}), '(prf_array)\n', (2219, 2230), True, 'import numpy as np\n'), ((6215, 6240), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (6238, 6240), False, 'import warnings\n'), ((6258, 6309), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'AstropyUserWarning'], {}), "('ignore', AstropyUserWarning)\n", (6279, 6309), False, 'import warnings\n'), ((12763, 12786), 'numpy.append', 'np.append', (['result', 'flux'], {}), '(result, flux)\n', (12772, 12786), True, 'import numpy as np\n'), ((16896, 16951), 'imageutils.extract_array_2d', 'extract_array_2d', (['data_internal', '(size, size)', 'position'], {}), '(data_internal, (size, size), position)\n', (16912, 16951), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n'), ((18287, 18319), 'numpy.ma.dstack', 'np.ma.dstack', (['extracted_sub_prfs'], {}), '(extracted_sub_prfs)\n', (18299, 18319), True, 'import numpy as np\n'), ((5746, 5770), 'numpy.isnan', 'np.isnan', (['sub_array_data'], {}), '(sub_array_data)\n', (5754, 5770), True, 'import numpy as np\n'), ((10325, 10349), 'numpy.isnan', 'np.isnan', (['sub_array_data'], {}), '(sub_array_data)\n', (10333, 10349), True, 'import numpy as np\n'), ((17166, 17190), 'numpy.ma.sum', 'np.ma.sum', (['extracted_prf'], {}), '(extracted_prf)\n', (17175, 17190), True, 'import numpy as np\n'), ((17378, 17401), 'numpy.isnan', 'np.isnan', (['extracted_prf'], {}), '(extracted_prf)\n', (17386, 17401), True, 'import numpy as np\n'), ((17881, 17906), 'numpy.ma.copy', 'np.ma.copy', (['extracted_prf'], {}), '(extracted_prf)\n', (17891, 17906), True, 'import numpy as np\n'), ((17909, 17933), 'numpy.ma.sum', 'np.ma.sum', (['extracted_prf'], {}), '(extracted_prf)\n', (17918, 17933), True, 'import numpy as np\n'), ((18071, 18096), 'numpy.ma.copy', 'np.ma.copy', (['extracted_prf'], {}), '(extracted_prf)\n', (18081, 18096), True, 'import numpy as np\n'), ((8745, 8755), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (8752, 8755), True, 'import numpy as np\n'), ((8825, 8835), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (8832, 8835), True, 'import numpy as np\n'), ((8907, 8917), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (8914, 8917), True, 'import numpy as np\n'), ((8987, 8997), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (8994, 8997), True, 'import numpy as np\n'), ((17648, 17692), 'imageutils.mask_to_mirrored_num', 'mask_to_mirrored_num', (['extracted_prf', 'prf_nan'], {}), '(extracted_prf, prf_nan)\n', (17668, 17692), False, 'from imageutils import extract_array_2d, subpixel_indices, add_array_2d, mask_to_mirrored_num\n')] |
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
import sklearn
import seaborn as sns
def testing_data(data_set, params, plot = 'y', save=False):
os.chdir(data_set.ip['outdir'])
"""
Function which evaluates the MSE/MAE of the test setr
Inputs:
data_seta : data container
params : new params evaluated through the lrrde procedure
plot : flag if 'y' plot results
Returns:
evaluation of MAE and MSE of the prediction on the training set
"""
if plot == 'y':
y_ref = data_set.y_test
y_test = np.dot(data_set.x_test, params.T).reshape(np.shape(y_ref)).T
y_test = y_test*data_set.ip['sigma']
y_test_s = np.sort(y_test,axis=0)
y_ref_s = np.sort(y_ref, axis=0)
mse_test = np.mean(np.power(y_test_s - y_ref_s, 2))
mae_test_s = np.mean(np.abs(y_ref_s - y_test_s.T))
print('MSE (lrr-de) = {}'.format(mse_test))
print('MAE (lrr-de) = {}'.format(mae_test_s))
print("-------")
plt.figure(dpi=100)
plt.title("Comparison prediction Test Set")
plt.plot(y_test,label="lrr-de",marker="*")
plt.plot(y_ref, label="ref",marker="*")
plt.legend(loc='upper left')
if save:
plt.savefig("TestSet.pdf")
| [
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.pyplot.plot",
"numpy.power",
"matplotlib.pyplot.legend",
"numpy.shape",
"numpy.sort",
"matplotlib.pyplot.figure",
"numpy.dot",
"os.chdir",
"matplotlib.pyplot.savefig"
] | [((193, 224), 'os.chdir', 'os.chdir', (["data_set.ip['outdir']"], {}), "(data_set.ip['outdir'])\n", (201, 224), False, 'import os\n'), ((776, 799), 'numpy.sort', 'np.sort', (['y_test'], {'axis': '(0)'}), '(y_test, axis=0)\n', (783, 799), True, 'import numpy as np\n'), ((822, 844), 'numpy.sort', 'np.sort', (['y_ref'], {'axis': '(0)'}), '(y_ref, axis=0)\n', (829, 844), True, 'import numpy as np\n'), ((1127, 1146), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(100)'}), '(dpi=100)\n', (1137, 1146), True, 'import matplotlib.pyplot as plt\n'), ((1159, 1202), 'matplotlib.pyplot.title', 'plt.title', (['"""Comparison prediction Test Set"""'], {}), "('Comparison prediction Test Set')\n", (1168, 1202), True, 'import matplotlib.pyplot as plt\n'), ((1211, 1255), 'matplotlib.pyplot.plot', 'plt.plot', (['y_test'], {'label': '"""lrr-de"""', 'marker': '"""*"""'}), "(y_test, label='lrr-de', marker='*')\n", (1219, 1255), True, 'import matplotlib.pyplot as plt\n'), ((1262, 1302), 'matplotlib.pyplot.plot', 'plt.plot', (['y_ref'], {'label': '"""ref"""', 'marker': '"""*"""'}), "(y_ref, label='ref', marker='*')\n", (1270, 1302), True, 'import matplotlib.pyplot as plt\n'), ((1310, 1338), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (1320, 1338), True, 'import matplotlib.pyplot as plt\n'), ((877, 908), 'numpy.power', 'np.power', (['(y_test_s - y_ref_s)', '(2)'], {}), '(y_test_s - y_ref_s, 2)\n', (885, 908), True, 'import numpy as np\n'), ((941, 969), 'numpy.abs', 'np.abs', (['(y_ref_s - y_test_s.T)'], {}), '(y_ref_s - y_test_s.T)\n', (947, 969), True, 'import numpy as np\n'), ((1368, 1394), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""TestSet.pdf"""'], {}), "('TestSet.pdf')\n", (1379, 1394), True, 'import matplotlib.pyplot as plt\n'), ((689, 704), 'numpy.shape', 'np.shape', (['y_ref'], {}), '(y_ref)\n', (697, 704), True, 'import numpy as np\n'), ((647, 680), 'numpy.dot', 'np.dot', (['data_set.x_test', 'params.T'], {}), '(data_set.x_test, params.T)\n', (653, 680), True, 'import numpy as np\n')] |
# coding=utf-8
# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run BERT on SQuAD 1.1 and SQuAD 2.0."""
from __future__ import absolute_import, division, print_function
import collections
import json
import math
import os
import random
import shutil
import time
import pickle
import horovod.tensorflow as hvd
import numpy as np
import six
import tensorflow as tf
from tensorflow.python.client import device_lib
import modeling
import optimization
import tokenization
from utils.create_squad_data import *
from utils.utils import LogEvalRunHook, LogTrainRunHook
from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", None,
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("vocab_file", None,
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", None,
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string("train_file", None,
"SQuAD json for training. E.g., train-v1.1.json")
flags.DEFINE_string(
"predict_file", None,
"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 384,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"doc_stride", 128,
"When splitting up a long document into chunks, how much stride to "
"take between chunks.")
flags.DEFINE_integer(
"max_query_length", 64,
"The maximum number of tokens for the question. Questions longer than "
"this will be truncated to this length.")
flags.DEFINE_bool("do_train", False, "Whether to run training.")
flags.DEFINE_bool("do_predict", False, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 8, "Total batch size for training.")
flags.DEFINE_integer("predict_batch_size", 8,
"Total batch size for predictions.")
flags.DEFINE_float("learning_rate", 5e-6, "The initial learning rate for Adam.")
flags.DEFINE_bool("use_trt", False, "Whether to use TF-TRT")
flags.DEFINE_bool("horovod", False, "Whether to use Horovod for multi-gpu runs")
flags.DEFINE_float("num_train_epochs", 3.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer("num_accumulation_steps", 1,
"Number of accumulation steps before gradient update"
"Global batch size = num_accumulation_steps * train_batch_size")
flags.DEFINE_integer(
"n_best_size", 20,
"The total number of n-best predictions to generate in the "
"nbest_predictions.json output file.")
flags.DEFINE_integer(
"max_answer_length", 30,
"The maximum length of an answer that can be generated. This is needed "
"because the start and end predictions are not conditioned on one another.")
flags.DEFINE_bool(
"verbose_logging", False,
"If true, all of the warnings related to data processing will be printed. "
"A number of warnings are expected for a normal SQuAD evaluation.")
flags.DEFINE_bool(
"version_2_with_negative", False,
"If true, the SQuAD examples contain some that do not have an answer.")
flags.DEFINE_float(
"null_score_diff_threshold", 0.0,
"If null_score - best_non_null is greater than the threshold predict null.")
flags.DEFINE_bool("use_fp16", False, "Whether to use fp32 or fp16 arithmetic on GPU.")
flags.DEFINE_bool("use_xla", False, "Whether to enable XLA JIT compilation.")
flags.DEFINE_integer("num_eval_iterations", None,
"How many eval iterations to run - performs inference on subset")
# TRTIS Specific flags
flags.DEFINE_bool("export_trtis", False, "Whether to export saved model or run inference with TRTIS")
flags.DEFINE_string("trtis_model_name", "bert", "exports to appropriate directory for TRTIS")
flags.DEFINE_integer("trtis_model_version", 1, "exports to appropriate directory for TRTIS")
flags.DEFINE_string("trtis_server_url", "localhost:8001", "exports to appropriate directory for TRTIS")
flags.DEFINE_bool("trtis_model_overwrite", False, "If True, will overwrite an existing directory with the specified 'model_name' and 'version_name'")
flags.DEFINE_integer("trtis_max_batch_size", 8, "Specifies the 'max_batch_size' in the TRTIS model config. See the TRTIS documentation for more info.")
flags.DEFINE_float("trtis_dyn_batching_delay", 0, "Determines the dynamic_batching queue delay in milliseconds(ms) for the TRTIS model config. Use '0' or '-1' to specify static batching. See the TRTIS documentation for more info.")
flags.DEFINE_integer("trtis_engine_count", 1, "Specifies the 'instance_group' count value in the TRTIS model config. See the TRTIS documentation for more info.")
flags.DEFINE_bool("do_calib", False, "Whether to do calibration.")
flags.DEFINE_bool("if_quant", False, "Whether to quantize.")
flags.DEFINE_integer("calib_batch", 4, "Number of batches for calibration.")
flags.DEFINE_string("calib_method", "percentile", "calibration method [percentile, mse, max, entropy]")
flags.DEFINE_float("percentile", 99.99, "percentile for percentile calibrator")
flags.DEFINE_string("calibrator_file", "calibrators.pkl", "pickle file for calibrators")
flags.DEFINE_integer("ft_mode", 1, "int8 mode in FasterTransformer.")
flags.DEFINE_bool("distillation", False, "Whether or not to use the techer-student model for finetuning (Knowledge distillation)")
flags.DEFINE_string("teacher", None, "teacher checkpoint file for distillation")
flags.DEFINE_float("distillation_loss_scale", 10000., "scale applied to distillation component of loss")
if FLAGS.ft_mode == 1:
KERNEL_AXIS = 1
DISABLE_LIST = ['aftergemm', 'softmax_input', 'residual_input', 'local_input']
elif FLAGS.ft_mode == 2:
KERNEL_AXIS = None
DISABLE_LIST = ['local_input']
else:
raise ValueError("wrong argument value for 'ft_mode'")
input_desc = QuantDescriptor('input', disable_key_words=DISABLE_LIST)
kernel_desc = QuantDescriptor('kernel', axis=KERNEL_AXIS, disable_key_words=DISABLE_LIST)
QuantDense.set_default_quant_desc_input(input_desc)
QuantDense.set_default_quant_desc_kernel(kernel_desc)
class CalibrationHook(tf.train.SessionRunHook):
def __init__(self, layer_num):
self.layer_num = layer_num
self.calibrator_lists = {}
def begin(self):
self.saver = tf.train.Saver()
tf.compat.v1.logging.info("initializing calibrators")
graph = tf.compat.v1.get_default_graph()
self.calibrator_lists['input'] = get_calibrators('input', collector_type='histogram')
self.calibrator_lists['kernel'] = get_calibrators('kernel', collector_type='max', axis=KERNEL_AXIS)
for k in ['input', 'kernel']:
tf.compat.v1.logging.info("There are {} calibrators in collection '{}'".format(len(self.calibrator_lists[k]), k))
self.calib_step = [
calibrator.calib_step_op(graph) for _, calib_list in self.calibrator_lists.items() for calibrator in calib_list]
self.placeholders = {}
self.load_min_op = {}
self.load_max_op = {}
self.calibrator_reverse_map = {}
for _, calib_list in self.calibrator_lists.items():
for i, calibrator in enumerate(calib_list):
if calibrator.tensor_name_prefix in self.placeholders:
raise ValueError("repeated name prefix")
self.placeholders[calibrator.tensor_name_prefix] = tf.placeholder(tf.float32)
self.load_min_op[calibrator.tensor_name_prefix] = tf.compat.v1.assign(graph.get_tensor_by_name(calibrator.quant_min_name),
self.placeholders[calibrator.tensor_name_prefix])
self.load_max_op[calibrator._tensor_name_prefix] = tf.compat.v1.assign(graph.get_tensor_by_name(calibrator.quant_max_name),
self.placeholders[calibrator.tensor_name_prefix])
self.calibrator_reverse_map[calibrator.tensor_name_prefix] = calibrator
def before_run(self, run_context):
tf.compat.v1.logging.info("registering calibration step")
return tf.estimator.SessionRunArgs(
fetches=self.calib_step)
def end(self, session):
tf.compat.v1.logging.info("computing calibration ranges")
if FLAGS.calib_method == 'max':
tf.compat.v1.logging.info("max calibration.")
for calibrator in self.calibrator_lists['input']:
calibrator.compute_range('max')
elif FLAGS.calib_method == 'percentile':
tf.compat.v1.logging.info("percentile calibration with value {}.".format(FLAGS.percentile))
for calibrator in self.calibrator_lists['input']:
calibrator.compute_range('percentile', percentile=FLAGS.percentile)
elif FLAGS.calib_method == 'mse':
tf.compat.v1.logging.info("mse calibration.")
for calibrator in self.calibrator_lists['input']:
calibrator.compute_range('mse')
elif FLAGS.calib_method == 'entropy':
tf.compat.v1.logging.info("entropy calibration.")
for calibrator in self.calibrator_lists['input']:
calibrator.compute_range('entropy')
else:
raise ValueError("Unsupported calibration method.")
for calibrator in self.calibrator_lists['kernel']:
calibrator.compute_range('max')
if FLAGS.ft_mode == 2:
tf.compat.v1.logging.info("fusing QKV")
for i in range(self.layer_num):
prefix = f"bert/encoder/layer_{i}/attention/self"
tf.compat.v1.logging.info(f"FUSE_QKV: {prefix:50}")
fuse_list = [self.calibrator_reverse_map[prefix + f"/{name}/kernel_quantizer"] for name in ['query', 'key', 'value']]
self.fuse3(*fuse_list)
fuse_list = [self.calibrator_reverse_map[prefix + f"/{name}/aftergemm_quantizer"] for name in ['query', 'key', 'value']]
self.fuse3(*fuse_list)
fuse_list = [self.calibrator_reverse_map[prefix + f"/matmul_{name}_input_quantizer"] for name in ['q', 'k', 'v']]
self.fuse3(*fuse_list)
tf.compat.v1.logging.info("loading calibration ranges")
session.run(self.load_min_op, {self.placeholders[calibrator.tensor_name_prefix]:calibrator.calib_min for _, calib_list in self.calibrator_lists.items() for calibrator in calib_list})
session.run(self.load_max_op, {self.placeholders[calibrator.tensor_name_prefix]:calibrator.calib_max for _, calib_list in self.calibrator_lists.items() for calibrator in calib_list})
tf.compat.v1.logging.info("saving calibrated model")
with open(os.path.join(FLAGS.output_dir, FLAGS.calibrator_file), 'wb') as f:
pickle.dump(self.calibrator_lists, f)
self.saver.save(session, os.path.join(FLAGS.output_dir, 'model.ckpt-calibrated'))
def fuse3(self, qq, qk, qv):
if not hasattr(qq, 'calib_min') or not hasattr(qk, 'calib_min') or not hasattr(qv, 'calib_min') or \
not hasattr(qq, 'calib_max') or not hasattr(qk, 'calib_max') or not hasattr(qv, 'calib_max'):
raise RuntimeError('missing min/max buffer, unable to fuse')
qmax = qq.calib_max
kmax = qk.calib_max
vmax = qv.calib_max
qmin = qq.calib_min
kmin = qk.calib_min
vmin = qv.calib_min
amax = max(qmax, kmax, vmax)
qq._calib_max = amax
qk._calib_max = amax
qv._calib_max = amax
amin = min(qmin, kmin, vmin)
qq._calib_min = amin
qk._calib_min = amin
qv._calib_min = amin
tf.compat.v1.logging.info(
f' q={qmin:7.4f}/{qmax:7.4f} k={kmin:7.4f}/{kmax:7.4f} v={vmin:7.4f}/{vmax:7.4f} -> {amin:7.4f}/{amax:7.4f}')
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
use_one_hot_embeddings, if_quant):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings,
compute_type=tf.float32,
if_quant=if_quant)
final_hidden = model.get_sequence_output()
final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
batch_size = final_hidden_shape[0]
seq_length = final_hidden_shape[1]
hidden_size = final_hidden_shape[2]
output_weights = tf.get_variable(
"cls/squad/output_weights", [2, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
final_hidden_matrix = tf.reshape(final_hidden,
[batch_size * seq_length, hidden_size])
logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [batch_size, seq_length, 2])
logits = tf.transpose(logits, [2, 0, 1])
unstacked_logits = tf.unstack(logits, axis=0, name='unstack')
(start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
return (start_logits, end_logits)
def get_frozen_tftrt_model(bert_config, shape, use_one_hot_embeddings, init_checkpoint):
tf_config = tf.compat.v1.ConfigProto()
tf_config.gpu_options.allow_growth = True
output_node_names = ['unstack']
with tf.Session(config=tf_config) as tf_sess:
input_ids = tf.placeholder(tf.int32, shape, 'input_ids')
input_mask = tf.placeholder(tf.int32, shape, 'input_mask')
segment_ids = tf.placeholder(tf.int32, shape, 'segment_ids')
(start_logits, end_logits) = create_model(bert_config=bert_config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
tvars = tf.trainable_variables()
(assignment_map, initialized_variable_names) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf_sess.run(tf.global_variables_initializer())
print("LOADED!")
tf.compat.v1.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
else:
init_string = ", *NOTTTTTTTTTTTTTTTTTTTTT"
tf.compat.v1.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string)
frozen_graph = tf.graph_util.convert_variables_to_constants(tf_sess,
tf_sess.graph.as_graph_def(), output_node_names)
num_nodes = len(frozen_graph.node)
print('Converting graph using TensorFlow-TensorRT...')
from tensorflow.python.compiler.tensorrt import trt_convert as trt
converter = trt.TrtGraphConverter(
input_graph_def=frozen_graph,
nodes_blacklist=output_node_names,
max_workspace_size_bytes=(4096 << 20) - 1000,
precision_mode = "FP16" if FLAGS.use_fp16 else "FP32",
minimum_segment_size=4,
is_dynamic_op=True,
maximum_cached_engines=1000
)
frozen_graph = converter.convert()
print('Total node count before and after TF-TRT conversion:',
num_nodes, '->', len(frozen_graph.node))
print('TRT node count:',
len([1 for n in frozen_graph.node if str(n.op) == 'TRTEngineOp']))
with tf.io.gfile.GFile("frozen_modelTRT.pb", "wb") as f:
f.write(frozen_graph.SerializeToString())
return frozen_graph
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps,
hvd=None, use_fp16=False, use_one_hot_embeddings=False):
"""Returns `model_fn` closure for Estimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for Estimator."""
if FLAGS.verbose_logging:
tf.compat.v1.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.compat.v1.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
if FLAGS.if_quant:
if_quant = True
else:
if_quant = False
if FLAGS.do_calib and (mode == tf.estimator.ModeKeys.TRAIN):
is_training = False
if_quant = False
if not is_training and FLAGS.use_trt:
trt_graph = get_frozen_tftrt_model(bert_config, input_ids.shape, use_one_hot_embeddings, init_checkpoint)
(start_logits, end_logits) = tf.import_graph_def(trt_graph,
input_map={'input_ids':input_ids, 'input_mask':input_mask, 'segment_ids':segment_ids},
return_elements=['unstack:0', 'unstack:1'],
name='')
predictions = {
"unique_ids": unique_ids,
"start_logits": start_logits,
"end_logits": end_logits,
}
output_spec = tf.estimator.EstimatorSpec(
mode=mode, predictions=predictions)
return output_spec
if is_training and FLAGS.distillation:
tf.compat.v1.logging.info("initializing teacher model.")
with tf.variable_scope("teacher"):
(start_logits_teacher, end_logits_teacher) = create_model(
bert_config=bert_config,
is_training=False,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings,
if_quant=False)
tvars = tf.trainable_variables()
initialized_variable_names_t = {}
if not FLAGS.teacher:
raise ValueError("no teacher checkpoint is supplied.")
if (hvd is None or hvd.rank() == 0):
(assignment_map_t, initialized_variable_names_t
) = modeling.get_assignment_map_from_checkpoint(tvars, FLAGS.teacher, "teacher/")
tf.train.init_from_checkpoint(FLAGS.teacher, assignment_map_t)
trainable_vars = tf.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES)
del trainable_vars[:]
tf.compat.v1.logging.info("!!!!!!!!!!if_quant is {}!!!!!!!!!!".format(if_quant))
(start_logits, end_logits) = create_model(
bert_config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings,
if_quant=if_quant)
tvars = tf.trainable_variables()
qvars = tf.get_collection("quantization_variables")
initialized_variable_names = {}
if init_checkpoint and (hvd is None or hvd.rank() == 0):
tf.compat.v1.logging.info("restore from checkpoint: " + init_checkpoint)
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
(assignment_map_q, initialized_variable_names_q
) = modeling.get_assignment_map_from_checkpoint(qvars, init_checkpoint, allow_shape_mismatch=True)
assignment_map.update(assignment_map_q)
initialized_variable_names.update(initialized_variable_names_q)
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
if FLAGS.verbose_logging:
tf.compat.v1.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.compat.v1.logging.info(" %d name = %s, shape = %s%s", 0 if hvd is None else hvd.rank(), var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
seq_length = modeling.get_shape_list(input_ids)[1]
def compute_loss(logits, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
log_probs = tf.nn.log_softmax(logits, axis=-1)
loss = -tf.reduce_mean(
tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
return loss
def fixprob(att, T=3):
att = tf.nn.softmax(att/T, axis=-1) + 1e-9
return att
def kl_loss(x, y):
x = fixprob(x)
y = fixprob(y)
X = tf.distributions.Categorical(probs=x)
Y = tf.distributions.Categorical(probs=y)
return tf.math.reduce_mean(tf.distributions.kl_divergence(X, Y))
start_positions = features["start_positions"]
end_positions = features["end_positions"]
start_loss = compute_loss(start_logits, start_positions)
end_loss = compute_loss(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2.0
if FLAGS.distillation:
dloss = kl_loss(start_logits, start_logits_teacher) + kl_loss(end_logits, end_logits_teacher)
total_loss = total_loss + dloss * FLAGS.distillation_loss_scale
if FLAGS.do_calib:
global_step = tf.compat.v1.train.get_or_create_global_step()
new_global_step = global_step + 1
new_global_step = tf.identity(new_global_step, name='step_update')
train_op = tf.group(tf.no_op(), [global_step.assign(new_global_step)])
else:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, hvd, False, use_fp16, FLAGS.num_accumulation_steps)
output_spec = tf.estimator.EstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op)
elif mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
"unique_ids": unique_ids,
"start_logits": start_logits,
"end_logits": end_logits,
}
output_spec = tf.estimator.EstimatorSpec(
mode=mode, predictions=predictions)
else:
raise ValueError(
"Only TRAIN and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def input_fn_builder(input_file, batch_size, seq_length, is_training, drop_remainder, hvd=None):
"""Creates an `input_fn` closure to be passed to Estimator."""
name_to_features = {
"unique_ids": tf.io.FixedLenFeature([], tf.int64),
"input_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.io.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.io.FixedLenFeature([seq_length], tf.int64),
}
if is_training:
name_to_features["start_positions"] = tf.io.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.io.FixedLenFeature([], tf.int64)
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn():
"""The actual input function."""
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = tf.data.TFRecordDataset(input_file, num_parallel_reads=4)
if hvd is not None: d = d.shard(hvd.size(), hvd.rank())
d = d.apply(tf.data.experimental.ignore_errors())
d = d.shuffle(buffer_size=100)
d = d.repeat()
else:
d = tf.data.TFRecordDataset(input_file)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_logits", "end_logits"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.compat.v1.logging.info("Writing predictions to: %s" % (output_prediction_file))
tf.compat.v1.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
score_null = 1000000 # large and positive
min_null_feature_index = 0 # the paragraph slice with min mull score
null_start_logit = 0 # the start logit at the slice with min null score
null_end_logit = 0 # the end logit at the slice with min null score
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
# if we could have irrelevant answers, get the min score of irrelevant
if FLAGS.version_2_with_negative:
feature_null_score = result.start_logits[0] + result.end_logits[0]
if feature_null_score < score_null:
score_null = feature_null_score
min_null_feature_index = feature_index
null_start_logit = result.start_logits[0]
null_end_logit = result.end_logits[0]
for start_index in start_indexes:
for end_index in end_indexes:
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
if FLAGS.version_2_with_negative:
prelim_predictions.append(
_PrelimPrediction(
feature_index=min_null_feature_index,
start_index=0,
end_index=0,
start_logit=null_start_logit,
end_logit=null_end_logit))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
if pred.start_index > 0: # this is a non-null prediction
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, do_lower_case)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
else:
final_text = ""
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
# if we didn't inlude the empty option in the n-best, inlcude it
if FLAGS.version_2_with_negative:
if "" not in seen_predictions:
nbest.append(
_NbestPrediction(
text="", start_logit=null_start_logit,
end_logit=null_end_logit))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
if not best_non_null_entry:
if entry.text:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
if not FLAGS.version_2_with_negative:
all_predictions[example.qas_id] = nbest_json[0]["text"]
else:
# predict "" iff the null score - the score of best non-null > threshold
score_diff = score_null - best_non_null_entry.start_logit - (
best_non_null_entry.end_logit)
scores_diff_json[example.qas_id] = score_diff
if score_diff > FLAGS.null_score_diff_threshold:
all_predictions[example.qas_id] = ""
else:
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.io.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.io.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
if FLAGS.version_2_with_negative:
with tf.io.gfile.GFile(output_null_log_odds_file, "w") as writer:
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span of our original text corresponding to the
# span that we predicted.
#
# However, `orig_text` may contain extra characters that we don't want in
# our prediction.
#
# For example, let's say:
# pred_text = <NAME>
# orig_text = <NAME>
#
# We don't want to return `orig_text` because it contains the extra "'s".
#
# We don't want to return `pred_text` because it's already been normalized
# (the SQuAD eval script also does punctuation stripping/lower casing but
# our tokenizer does additional normalization like stripping accent
# characters).
#
# What we really want to return is "<NAME>".
#
# Therefore, we have to apply a semi-complicated alignment heruistic between
# `pred_text` and `orig_text` to get a character-to-charcter alignment. This
# can fail in certain cases in which case we just return `orig_text`.
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
# We first tokenize `orig_text`, strip whitespace from the result
# and `pred_text`, and check if they are the same length. If they are
# NOT the same length, the heuristic has failed. If they are the same
# length, we assume the characters are one-to-one aligned.
tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if FLAGS.verbose_logging:
tf.compat.v1.logging.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if FLAGS.verbose_logging:
tf.compat.v1.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if FLAGS.verbose_logging:
tf.compat.v1.logging.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if FLAGS.verbose_logging:
tf.compat.v1.logging.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
def validate_flags_or_throw(bert_config):
"""Validate the input FLAGS or throw an exception."""
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_calib and not FLAGS.do_predict and not FLAGS.export_trtis:
raise ValueError("At least one of `do_train` or `do_predict` or `export_SavedModel` must be True.")
if FLAGS.do_train or FLAGS.do_calib:
if not FLAGS.train_file:
raise ValueError(
"If `do_train` or `do_calib` is True, then `train_file` must be specified.")
if FLAGS.do_predict:
if not FLAGS.predict_file:
raise ValueError(
"If `do_predict` is True, then `predict_file` must be specified.")
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
raise ValueError(
"The max_seq_length (%d) must be greater than max_query_length "
"(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
def export_model(estimator, export_dir, init_checkpoint):
"""Exports a checkpoint in SavedModel format in a directory structure compatible with TRTIS."""
def serving_input_fn():
label_ids = tf.placeholder(tf.int32, [None,], name='unique_ids')
input_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_ids')
input_mask = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_mask')
segment_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='segment_ids')
input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({
'unique_ids': label_ids,
'input_ids': input_ids,
'input_mask': input_mask,
'segment_ids': segment_ids,
})()
return input_fn
saved_dir = estimator.export_savedmodel(
export_dir,
serving_input_fn,
assets_extra=None,
as_text=False,
checkpoint_path=init_checkpoint,
strip_default_attrs=False)
model_name = FLAGS.trtis_model_name
model_folder = export_dir + "/trtis_models/" + model_name
version_folder = model_folder + "/" + str(FLAGS.trtis_model_version)
final_model_folder = version_folder + "/model.savedmodel"
if not os.path.exists(version_folder):
os.makedirs(version_folder)
if (not os.path.exists(final_model_folder)):
os.rename(saved_dir, final_model_folder)
print("Model saved to dir", final_model_folder)
else:
if (FLAGS.trtis_model_overwrite):
shutil.rmtree(final_model_folder)
os.rename(saved_dir, final_model_folder)
print("WARNING: Existing model was overwritten. Model dir: {}".format(final_model_folder))
else:
print("ERROR: Could not save TRTIS model. Folder already exists. Use '--trtis_model_overwrite=True' if you would like to overwrite an existing model. Model dir: {}".format(final_model_folder))
return
# Now build the config for TRTIS. Check to make sure we can overwrite it, if it exists
config_filename = os.path.join(model_folder, "config.pbtxt")
if (os.path.exists(config_filename) and not FLAGS.trtis_model_overwrite):
print("ERROR: Could not save TRTIS model config. Config file already exists. Use '--trtis_model_overwrite=True' if you would like to overwrite an existing model config. Model config: {}".format(config_filename))
return
config_template = r"""
name: "{model_name}"
platform: "tensorflow_savedmodel"
max_batch_size: {max_batch_size}
input [
{{
name: "unique_ids"
data_type: TYPE_INT32
dims: [ 1 ]
reshape: {{ shape: [ ] }}
}},
{{
name: "segment_ids"
data_type: TYPE_INT32
dims: {seq_length}
}},
{{
name: "input_ids"
data_type: TYPE_INT32
dims: {seq_length}
}},
{{
name: "input_mask"
data_type: TYPE_INT32
dims: {seq_length}
}}
]
output [
{{
name: "end_logits"
data_type: TYPE_FP32
dims: {seq_length}
}},
{{
name: "start_logits"
data_type: TYPE_FP32
dims: {seq_length}
}}
]
{dynamic_batching}
instance_group [
{{
count: {engine_count}
kind: KIND_GPU
gpus: [{gpu_list}]
}}
]"""
batching_str = ""
max_batch_size = FLAGS.trtis_max_batch_size
if (FLAGS.trtis_dyn_batching_delay > 0):
# Use only full and half full batches
pref_batch_size = [int(max_batch_size / 2.0), max_batch_size]
batching_str = r"""
dynamic_batching {{
preferred_batch_size: [{0}]
max_queue_delay_microseconds: {1}
}}""".format(", ".join([str(x) for x in pref_batch_size]), int(FLAGS.trtis_dyn_batching_delay * 1000.0))
config_values = {
"model_name": model_name,
"max_batch_size": max_batch_size,
"seq_length": FLAGS.max_seq_length,
"dynamic_batching": batching_str,
"gpu_list": ", ".join([x.name.split(":")[-1] for x in device_lib.list_local_devices() if x.device_type == "GPU"]),
"engine_count": FLAGS.trtis_engine_count
}
with open(model_folder + "/config.pbtxt", "w") as file:
final_config_str = config_template.format_map(config_values)
file.write(final_config_str)
def main(_):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)
if FLAGS.horovod:
hvd.init()
if FLAGS.use_fp16:
os.environ["TF_ENABLE_AUTO_MIXED_PRECISION_GRAPH_REWRITE"] = "1"
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
validate_flags_or_throw(bert_config)
tf.io.gfile.makedirs(FLAGS.output_dir)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
master_process = True
training_hooks = []
global_batch_size = FLAGS.train_batch_size * FLAGS.num_accumulation_steps
hvd_rank = 0
config = tf.compat.v1.ConfigProto()
learning_rate = FLAGS.learning_rate
if FLAGS.horovod:
tf.compat.v1.logging.info("Multi-GPU training with TF Horovod")
tf.compat.v1.logging.info("hvd.size() = %d hvd.rank() = %d", hvd.size(), hvd.rank())
global_batch_size = FLAGS.train_batch_size * hvd.size() * FLAGS.num_accumulation_steps
learning_rate = learning_rate * hvd.size()
master_process = (hvd.rank() == 0)
hvd_rank = hvd.rank()
config.gpu_options.visible_device_list = str(hvd.local_rank())
if hvd.size() > 1:
training_hooks.append(hvd.BroadcastGlobalVariablesHook(0))
if FLAGS.use_xla:
config.graph_options.optimizer_options.global_jit_level = tf.compat.v1.OptimizerOptions.ON_1
run_config = tf.estimator.RunConfig(
model_dir=FLAGS.output_dir if master_process else None,
session_config=config,
save_checkpoints_steps=FLAGS.save_checkpoints_steps if master_process else None,
keep_checkpoint_max=1)
if master_process:
tf.compat.v1.logging.info("***** Configuaration *****")
for key in FLAGS.__flags.keys():
tf.compat.v1.logging.info(' {}: {}'.format(key, getattr(FLAGS, key)))
tf.compat.v1.logging.info("**************************")
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_calib:
training_hooks.append(CalibrationHook(bert_config.num_hidden_layers))
training_hooks.append(LogTrainRunHook(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps))
# Prepare Training Data
if FLAGS.do_train or (FLAGS.do_calib and master_process):
train_examples = read_squad_examples(
input_file=FLAGS.train_file, is_training=True,
version_2_with_negative=FLAGS.version_2_with_negative)
num_train_steps = int(
len(train_examples) / global_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in in the `input_fn`.
rng = random.Random(12345)
rng.shuffle(train_examples)
if FLAGS.do_calib:
num_train_steps = FLAGS.calib_batch
start_index = 0
if FLAGS.do_calib:
end_index = min(len(train_examples), num_train_steps * global_batch_size)
else:
end_index = len(train_examples)
tmp_filenames = [os.path.join(FLAGS.output_dir, "train.tf_record")]
if FLAGS.horovod:
tmp_filenames = [os.path.join(FLAGS.output_dir, "train.tf_record{}".format(i)) for i in range(hvd.size())]
num_examples_per_rank = len(train_examples) // hvd.size()
remainder = len(train_examples) % hvd.size()
if hvd.rank() < remainder:
start_index = hvd.rank() * (num_examples_per_rank+1)
end_index = start_index + num_examples_per_rank + 1
else:
start_index = hvd.rank() * num_examples_per_rank + remainder
end_index = start_index + (num_examples_per_rank)
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
hvd=None if not FLAGS.horovod else hvd,
use_fp16=FLAGS.use_fp16)
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train or (FLAGS.do_calib and master_process):
# We write to a temporary file to avoid storing very large constant tensors
# in memory.
train_writer = FeatureWriter(
filename=tmp_filenames[hvd_rank],
is_training=True)
convert_examples_to_features(
examples=train_examples[start_index:end_index],
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature,
verbose_logging=FLAGS.verbose_logging)
train_writer.close()
tf.compat.v1.logging.info("***** Running training *****")
tf.compat.v1.logging.info(" Num orig examples = %d", end_index - start_index)
tf.compat.v1.logging.info(" Num split examples = %d", train_writer.num_features)
tf.compat.v1.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.compat.v1.logging.info(" Num steps = %d", num_train_steps)
tf.compat.v1.logging.info(" LR = %f", learning_rate)
del train_examples
train_input_fn = input_fn_builder(
input_file=tmp_filenames,
batch_size=FLAGS.train_batch_size,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True,
hvd=None if not FLAGS.horovod else hvd)
train_start_time = time.time()
estimator.train(input_fn=train_input_fn, hooks=training_hooks, max_steps=num_train_steps)
train_time_elapsed = time.time() - train_start_time
train_time_wo_overhead = training_hooks[-1].total_time
avg_sentences_per_second = num_train_steps * global_batch_size * 1.0 / train_time_elapsed
ss_sentences_per_second = (num_train_steps - training_hooks[-1].skipped) * global_batch_size * 1.0 / train_time_wo_overhead
if master_process:
tf.compat.v1.logging.info("-----------------------------")
tf.compat.v1.logging.info("Total Training Time = %0.2f for Sentences = %d", train_time_elapsed,
num_train_steps * global_batch_size)
tf.compat.v1.logging.info("Total Training Time W/O Overhead = %0.2f for Sentences = %d", train_time_wo_overhead,
(num_train_steps - training_hooks[-1].skipped) * global_batch_size)
tf.compat.v1.logging.info("Throughput Average (sentences/sec) with overhead = %0.2f", avg_sentences_per_second)
tf.compat.v1.logging.info("Throughput Average (sentences/sec) = %0.2f", ss_sentences_per_second)
tf.compat.v1.logging.info("-----------------------------")
if FLAGS.export_trtis and master_process:
export_model(estimator, FLAGS.output_dir, FLAGS.init_checkpoint)
if FLAGS.do_predict and master_process:
eval_examples = read_squad_examples(
input_file=FLAGS.predict_file, is_training=False,
version_2_with_negative=FLAGS.version_2_with_negative)
# Perform evaluation on subset, useful for profiling
if FLAGS.num_eval_iterations is not None:
eval_examples = eval_examples[:FLAGS.num_eval_iterations*FLAGS.predict_batch_size]
eval_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature,
verbose_logging=FLAGS.verbose_logging)
eval_writer.close()
tf.compat.v1.logging.info("***** Running predictions *****")
tf.compat.v1.logging.info(" Num orig examples = %d", len(eval_examples))
tf.compat.v1.logging.info(" Num split examples = %d", len(eval_features))
tf.compat.v1.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_input_fn = input_fn_builder(
input_file=eval_writer.filename,
batch_size=FLAGS.predict_batch_size,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False)
all_results = []
eval_hooks = [LogEvalRunHook(FLAGS.predict_batch_size)]
eval_start_time = time.time()
for result in estimator.predict(
predict_input_fn, yield_single_examples=True, hooks=eval_hooks):
if len(all_results) % 1000 == 0:
tf.compat.v1.logging.info("Processing example: %d" % (len(all_results)))
unique_id = int(result["unique_ids"])
start_logits = [float(x) for x in result["start_logits"].flat]
end_logits = [float(x) for x in result["end_logits"].flat]
all_results.append(
RawResult(
unique_id=unique_id,
start_logits=start_logits,
end_logits=end_logits))
eval_time_elapsed = time.time() - eval_start_time
eval_time_wo_overhead = eval_hooks[-1].total_time
time_list = eval_hooks[-1].time_list
time_list.sort()
num_sentences = (eval_hooks[-1].count - eval_hooks[-1].skipped) * FLAGS.predict_batch_size
avg = np.mean(time_list)
cf_50 = max(time_list[:int(len(time_list) * 0.50)])
cf_90 = max(time_list[:int(len(time_list) * 0.90)])
cf_95 = max(time_list[:int(len(time_list) * 0.95)])
cf_99 = max(time_list[:int(len(time_list) * 0.99)])
cf_100 = max(time_list[:int(len(time_list) * 1)])
ss_sentences_per_second = num_sentences * 1.0 / eval_time_wo_overhead
tf.compat.v1.logging.info("-----------------------------")
tf.compat.v1.logging.info("Total Inference Time = %0.2f for Sentences = %d", eval_time_elapsed,
eval_hooks[-1].count * FLAGS.predict_batch_size)
tf.compat.v1.logging.info("Total Inference Time W/O Overhead = %0.2f for Sentences = %d", eval_time_wo_overhead,
(eval_hooks[-1].count - eval_hooks[-1].skipped) * FLAGS.predict_batch_size)
tf.compat.v1.logging.info("Summary Inference Statistics")
tf.compat.v1.logging.info("Batch size = %d", FLAGS.predict_batch_size)
tf.compat.v1.logging.info("Sequence Length = %d", FLAGS.max_seq_length)
tf.compat.v1.logging.info("Precision = %s", "fp16" if FLAGS.use_fp16 else "fp32")
tf.compat.v1.logging.info("Latency Confidence Level 50 (ms) = %0.2f", cf_50 * 1000)
tf.compat.v1.logging.info("Latency Confidence Level 90 (ms) = %0.2f", cf_90 * 1000)
tf.compat.v1.logging.info("Latency Confidence Level 95 (ms) = %0.2f", cf_95 * 1000)
tf.compat.v1.logging.info("Latency Confidence Level 99 (ms) = %0.2f", cf_99 * 1000)
tf.compat.v1.logging.info("Latency Confidence Level 100 (ms) = %0.2f", cf_100 * 1000)
tf.compat.v1.logging.info("Latency Average (ms) = %0.2f", avg * 1000)
tf.compat.v1.logging.info("Throughput Average (sentences/sec) = %0.2f", ss_sentences_per_second)
tf.compat.v1.logging.info("-----------------------------")
output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
write_predictions(eval_examples, eval_features, all_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
FLAGS.do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file)
if __name__ == "__main__":
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.compat.v1.app.run()
| [
"modeling.BertModel",
"json.dumps",
"collections.defaultdict",
"tensorflow.get_collection_ref",
"ft_tensorflow_quantization.QuantDescriptor",
"tensorflow.nn.log_softmax",
"tokenization.FullTokenizer",
"tensorflow.compat.v1.logging.info",
"ft_tensorflow_quantization.QuantDense.set_default_quant_desc_... | [((7507, 7563), 'ft_tensorflow_quantization.QuantDescriptor', 'QuantDescriptor', (['"""input"""'], {'disable_key_words': 'DISABLE_LIST'}), "('input', disable_key_words=DISABLE_LIST)\n", (7522, 7563), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((7578, 7653), 'ft_tensorflow_quantization.QuantDescriptor', 'QuantDescriptor', (['"""kernel"""'], {'axis': 'KERNEL_AXIS', 'disable_key_words': 'DISABLE_LIST'}), "('kernel', axis=KERNEL_AXIS, disable_key_words=DISABLE_LIST)\n", (7593, 7653), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((7654, 7705), 'ft_tensorflow_quantization.QuantDense.set_default_quant_desc_input', 'QuantDense.set_default_quant_desc_input', (['input_desc'], {}), '(input_desc)\n', (7693, 7705), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((7706, 7759), 'ft_tensorflow_quantization.QuantDense.set_default_quant_desc_kernel', 'QuantDense.set_default_quant_desc_kernel', (['kernel_desc'], {}), '(kernel_desc)\n', (7746, 7759), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((25420, 25505), 'collections.namedtuple', 'collections.namedtuple', (['"""RawResult"""', "['unique_id', 'start_logits', 'end_logits']"], {}), "('RawResult', ['unique_id', 'start_logits', 'end_logits']\n )\n", (25442, 25505), False, 'import collections\n'), ((13128, 13367), 'modeling.BertModel', 'modeling.BertModel', ([], {'config': 'bert_config', 'is_training': 'is_training', 'input_ids': 'input_ids', 'input_mask': 'input_mask', 'token_type_ids': 'segment_ids', 'use_one_hot_embeddings': 'use_one_hot_embeddings', 'compute_type': 'tf.float32', 'if_quant': 'if_quant'}), '(config=bert_config, is_training=is_training, input_ids=\n input_ids, input_mask=input_mask, token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings, compute_type=tf.float32,\n if_quant=if_quant)\n', (13146, 13367), False, 'import modeling\n'), ((13474, 13528), 'modeling.get_shape_list', 'modeling.get_shape_list', (['final_hidden'], {'expected_rank': '(3)'}), '(final_hidden, expected_rank=3)\n', (13497, 13528), False, 'import modeling\n'), ((13925, 13989), 'tensorflow.reshape', 'tf.reshape', (['final_hidden', '[batch_size * seq_length, hidden_size]'], {}), '(final_hidden, [batch_size * seq_length, hidden_size])\n', (13935, 13989), True, 'import tensorflow as tf\n'), ((14036, 14100), 'tensorflow.matmul', 'tf.matmul', (['final_hidden_matrix', 'output_weights'], {'transpose_b': '(True)'}), '(final_hidden_matrix, output_weights, transpose_b=True)\n', (14045, 14100), True, 'import tensorflow as tf\n'), ((14112, 14147), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['logits', 'output_bias'], {}), '(logits, output_bias)\n', (14126, 14147), True, 'import tensorflow as tf\n'), ((14160, 14207), 'tensorflow.reshape', 'tf.reshape', (['logits', '[batch_size, seq_length, 2]'], {}), '(logits, [batch_size, seq_length, 2])\n', (14170, 14207), True, 'import tensorflow as tf\n'), ((14219, 14250), 'tensorflow.transpose', 'tf.transpose', (['logits', '[2, 0, 1]'], {}), '(logits, [2, 0, 1])\n', (14231, 14250), True, 'import tensorflow as tf\n'), ((14273, 14315), 'tensorflow.unstack', 'tf.unstack', (['logits'], {'axis': '(0)', 'name': '"""unstack"""'}), "(logits, axis=0, name='unstack')\n", (14283, 14315), True, 'import tensorflow as tf\n'), ((14532, 14558), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (14556, 14558), True, 'import tensorflow as tf\n'), ((25846, 25931), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (["('Writing predictions to: %s' % output_prediction_file)"], {}), "('Writing predictions to: %s' % output_prediction_file\n )\n", (25871, 25931), True, 'import tensorflow as tf\n'), ((25931, 26000), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (["('Writing nbest to: %s' % output_nbest_file)"], {}), "('Writing nbest to: %s' % output_nbest_file)\n", (25956, 26000), True, 'import tensorflow as tf\n'), ((26034, 26063), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (26057, 26063), False, 'import collections\n'), ((26295, 26416), 'collections.namedtuple', 'collections.namedtuple', (['"""PrelimPrediction"""', "['feature_index', 'start_index', 'end_index', 'start_logit', 'end_logit']"], {}), "('PrelimPrediction', ['feature_index', 'start_index',\n 'end_index', 'start_logit', 'end_logit'])\n", (26317, 26416), False, 'import collections\n'), ((26479, 26504), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (26502, 26504), False, 'import collections\n'), ((26524, 26549), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (26547, 26549), False, 'import collections\n'), ((26571, 26596), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (26594, 26596), False, 'import collections\n'), ((34725, 34781), 'tokenization.BasicTokenizer', 'tokenization.BasicTokenizer', ([], {'do_lower_case': 'do_lower_case'}), '(do_lower_case=do_lower_case)\n', (34752, 34781), False, 'import tokenization\n'), ((35639, 35669), 'six.iteritems', 'six.iteritems', (['tok_ns_to_s_map'], {}), '(tok_ns_to_s_map)\n', (35652, 35669), False, 'import six\n'), ((37452, 37546), 'tokenization.validate_case_matches_checkpoint', 'tokenization.validate_case_matches_checkpoint', (['FLAGS.do_lower_case', 'FLAGS.init_checkpoint'], {}), '(FLAGS.do_lower_case, FLAGS.\n init_checkpoint)\n', (37497, 37546), False, 'import tokenization\n'), ((40742, 40784), 'os.path.join', 'os.path.join', (['model_folder', '"""config.pbtxt"""'], {}), "(model_folder, 'config.pbtxt')\n", (40754, 40784), False, 'import os\n'), ((43007, 43068), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.INFO'], {}), '(tf.compat.v1.logging.INFO)\n', (43041, 43068), True, 'import tensorflow as tf\n'), ((43212, 43270), 'modeling.BertConfig.from_json_file', 'modeling.BertConfig.from_json_file', (['FLAGS.bert_config_file'], {}), '(FLAGS.bert_config_file)\n', (43246, 43270), False, 'import modeling\n'), ((43314, 43352), 'tensorflow.io.gfile.makedirs', 'tf.io.gfile.makedirs', (['FLAGS.output_dir'], {}), '(FLAGS.output_dir)\n', (43334, 43352), True, 'import tensorflow as tf\n'), ((43368, 43463), 'tokenization.FullTokenizer', 'tokenization.FullTokenizer', ([], {'vocab_file': 'FLAGS.vocab_file', 'do_lower_case': 'FLAGS.do_lower_case'}), '(vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS\n .do_lower_case)\n', (43394, 43463), False, 'import tokenization\n'), ((43616, 43642), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (43640, 43642), True, 'import tensorflow as tf\n'), ((44369, 44583), 'tensorflow.estimator.RunConfig', 'tf.estimator.RunConfig', ([], {'model_dir': '(FLAGS.output_dir if master_process else None)', 'session_config': 'config', 'save_checkpoints_steps': '(FLAGS.save_checkpoints_steps if master_process else None)', 'keep_checkpoint_max': '(1)'}), '(model_dir=FLAGS.output_dir if master_process else\n None, session_config=config, save_checkpoints_steps=FLAGS.\n save_checkpoints_steps if master_process else None, keep_checkpoint_max=1)\n', (44391, 44583), True, 'import tensorflow as tf\n'), ((46897, 46957), 'tensorflow.estimator.Estimator', 'tf.estimator.Estimator', ([], {'model_fn': 'model_fn', 'config': 'run_config'}), '(model_fn=model_fn, config=run_config)\n', (46919, 46957), True, 'import tensorflow as tf\n'), ((54674, 54696), 'tensorflow.compat.v1.app.run', 'tf.compat.v1.app.run', ([], {}), '()\n', (54694, 54696), True, 'import tensorflow as tf\n'), ((7941, 7957), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (7955, 7957), True, 'import tensorflow as tf\n'), ((7962, 8015), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""initializing calibrators"""'], {}), "('initializing calibrators')\n", (7987, 8015), True, 'import tensorflow as tf\n'), ((8028, 8060), 'tensorflow.compat.v1.get_default_graph', 'tf.compat.v1.get_default_graph', ([], {}), '()\n', (8058, 8060), True, 'import tensorflow as tf\n'), ((8098, 8150), 'ft_tensorflow_quantization.get_calibrators', 'get_calibrators', (['"""input"""'], {'collector_type': '"""histogram"""'}), "('input', collector_type='histogram')\n", (8113, 8150), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((8189, 8254), 'ft_tensorflow_quantization.get_calibrators', 'get_calibrators', (['"""kernel"""'], {'collector_type': '"""max"""', 'axis': 'KERNEL_AXIS'}), "('kernel', collector_type='max', axis=KERNEL_AXIS)\n", (8204, 8254), False, 'from ft_tensorflow_quantization import get_calibrators, QuantDense, QuantDescriptor\n'), ((9486, 9543), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""registering calibration step"""'], {}), "('registering calibration step')\n", (9511, 9543), True, 'import tensorflow as tf\n'), ((9555, 9607), 'tensorflow.estimator.SessionRunArgs', 'tf.estimator.SessionRunArgs', ([], {'fetches': 'self.calib_step'}), '(fetches=self.calib_step)\n', (9582, 9607), True, 'import tensorflow as tf\n'), ((9648, 9705), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""computing calibration ranges"""'], {}), "('computing calibration ranges')\n", (9673, 9705), True, 'import tensorflow as tf\n'), ((11423, 11478), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""loading calibration ranges"""'], {}), "('loading calibration ranges')\n", (11448, 11478), True, 'import tensorflow as tf\n'), ((11857, 11909), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""saving calibrated model"""'], {}), "('saving calibrated model')\n", (11882, 11909), True, 'import tensorflow as tf\n'), ((12793, 12947), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['f""" q={qmin:7.4f}/{qmax:7.4f} k={kmin:7.4f}/{kmax:7.4f} v={vmin:7.4f}/{vmax:7.4f} -> {amin:7.4f}/{amax:7.4f}"""'], {}), "(\n f' q={qmin:7.4f}/{qmax:7.4f} k={kmin:7.4f}/{kmax:7.4f} v={vmin:7.4f}/{vmax:7.4f} -> {amin:7.4f}/{amax:7.4f}'\n )\n", (12818, 12947), True, 'import tensorflow as tf\n'), ((14645, 14673), 'tensorflow.Session', 'tf.Session', ([], {'config': 'tf_config'}), '(config=tf_config)\n', (14655, 14673), True, 'import tensorflow as tf\n'), ((14702, 14746), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'shape', '"""input_ids"""'], {}), "(tf.int32, shape, 'input_ids')\n", (14716, 14746), True, 'import tensorflow as tf\n'), ((14764, 14809), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'shape', '"""input_mask"""'], {}), "(tf.int32, shape, 'input_mask')\n", (14778, 14809), True, 'import tensorflow as tf\n'), ((14828, 14874), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'shape', '"""segment_ids"""'], {}), "(tf.int32, shape, 'segment_ids')\n", (14842, 14874), True, 'import tensorflow as tf\n'), ((15326, 15350), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (15348, 15350), True, 'import tensorflow as tf\n'), ((15402, 15469), 'modeling.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['tvars', 'init_checkpoint'], {}), '(tvars, init_checkpoint)\n', (15445, 15469), False, 'import modeling\n'), ((15474, 15536), 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), '(init_checkpoint, assignment_map)\n', (15503, 15536), True, 'import tensorflow as tf\n'), ((15613, 15671), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""**** Trainable Variables ****"""'], {}), "('**** Trainable Variables ****')\n", (15638, 15671), True, 'import tensorflow as tf\n'), ((16291, 16562), 'tensorflow.python.compiler.tensorrt.trt_convert.TrtGraphConverter', 'trt.TrtGraphConverter', ([], {'input_graph_def': 'frozen_graph', 'nodes_blacklist': 'output_node_names', 'max_workspace_size_bytes': '((4096 << 20) - 1000)', 'precision_mode': "('FP16' if FLAGS.use_fp16 else 'FP32')", 'minimum_segment_size': '(4)', 'is_dynamic_op': '(True)', 'maximum_cached_engines': '(1000)'}), "(input_graph_def=frozen_graph, nodes_blacklist=\n output_node_names, max_workspace_size_bytes=(4096 << 20) - 1000,\n precision_mode='FP16' if FLAGS.use_fp16 else 'FP32',\n minimum_segment_size=4, is_dynamic_op=True, maximum_cached_engines=1000)\n", (16312, 16562), True, 'from tensorflow.python.compiler.tensorrt import trt_convert as trt\n'), ((20126, 20150), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (20148, 20150), True, 'import tensorflow as tf\n'), ((20163, 20206), 'tensorflow.get_collection', 'tf.get_collection', (['"""quantization_variables"""'], {}), "('quantization_variables')\n", (20180, 20206), True, 'import tensorflow as tf\n'), ((23779, 23814), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (23800, 23814), True, 'import tensorflow as tf\n'), ((23835, 23880), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), '([seq_length], tf.int64)\n', (23856, 23880), True, 'import tensorflow as tf\n'), ((23902, 23947), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), '([seq_length], tf.int64)\n', (23923, 23947), True, 'import tensorflow as tf\n'), ((23970, 24015), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[seq_length]', 'tf.int64'], {}), '([seq_length], tf.int64)\n', (23991, 24015), True, 'import tensorflow as tf\n'), ((24082, 24117), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (24103, 24117), True, 'import tensorflow as tf\n'), ((24158, 24193), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.int64'], {}), '([], tf.int64)\n', (24179, 24193), True, 'import tensorflow as tf\n'), ((24309, 24358), 'tensorflow.parse_single_example', 'tf.parse_single_example', (['record', 'name_to_features'], {}), '(record, name_to_features)\n', (24332, 24358), True, 'import tensorflow as tf\n'), ((29362, 29441), 'collections.namedtuple', 'collections.namedtuple', (['"""NbestPrediction"""', "['text', 'start_logit', 'end_logit']"], {}), "('NbestPrediction', ['text', 'start_logit', 'end_logit'])\n", (29384, 29441), False, 'import collections\n'), ((32553, 32599), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['output_prediction_file', '"""w"""'], {}), "(output_prediction_file, 'w')\n", (32570, 32599), True, 'import tensorflow as tf\n'), ((32682, 32723), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['output_nbest_file', '"""w"""'], {}), "(output_nbest_file, 'w')\n", (32699, 32723), True, 'import tensorflow as tf\n'), ((34212, 34237), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (34235, 34237), False, 'import collections\n'), ((37185, 37212), 'math.exp', 'math.exp', (['(score - max_score)'], {}), '(score - max_score)\n', (37193, 37212), False, 'import math\n'), ((38837, 38888), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {'name': '"""unique_ids"""'}), "(tf.int32, [None], name='unique_ids')\n", (38851, 38888), True, 'import tensorflow as tf\n'), ((38910, 38982), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_seq_length]'], {'name': '"""input_ids"""'}), "(tf.int32, [None, FLAGS.max_seq_length], name='input_ids')\n", (38924, 38982), True, 'import tensorflow as tf\n'), ((39004, 39077), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_seq_length]'], {'name': '"""input_mask"""'}), "(tf.int32, [None, FLAGS.max_seq_length], name='input_mask')\n", (39018, 39077), True, 'import tensorflow as tf\n'), ((39100, 39174), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_seq_length]'], {'name': '"""segment_ids"""'}), "(tf.int32, [None, FLAGS.max_seq_length], name='segment_ids')\n", (39114, 39174), True, 'import tensorflow as tf\n'), ((39909, 39939), 'os.path.exists', 'os.path.exists', (['version_folder'], {}), '(version_folder)\n', (39923, 39939), False, 'import os\n'), ((39949, 39976), 'os.makedirs', 'os.makedirs', (['version_folder'], {}), '(version_folder)\n', (39960, 39976), False, 'import os\n'), ((39994, 40028), 'os.path.exists', 'os.path.exists', (['final_model_folder'], {}), '(final_model_folder)\n', (40008, 40028), False, 'import os\n'), ((40039, 40079), 'os.rename', 'os.rename', (['saved_dir', 'final_model_folder'], {}), '(saved_dir, final_model_folder)\n', (40048, 40079), False, 'import os\n'), ((40794, 40825), 'os.path.exists', 'os.path.exists', (['config_filename'], {}), '(config_filename)\n', (40808, 40825), False, 'import os\n'), ((43094, 43104), 'horovod.tensorflow.init', 'hvd.init', ([], {}), '()\n', (43102, 43104), True, 'import horovod.tensorflow as hvd\n'), ((43708, 43771), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Multi-GPU training with TF Horovod"""'], {}), "('Multi-GPU training with TF Horovod')\n", (43733, 43771), True, 'import tensorflow as tf\n'), ((44063, 44073), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (44071, 44073), True, 'import horovod.tensorflow as hvd\n'), ((44628, 44683), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""***** Configuaration *****"""'], {}), "('***** Configuaration *****')\n", (44653, 44683), True, 'import tensorflow as tf\n'), ((44810, 44865), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""**************************"""'], {}), "('**************************')\n", (44835, 44865), True, 'import tensorflow as tf\n'), ((45061, 45135), 'utils.utils.LogTrainRunHook', 'LogTrainRunHook', (['global_batch_size', 'hvd_rank', 'FLAGS.save_checkpoints_steps'], {}), '(global_batch_size, hvd_rank, FLAGS.save_checkpoints_steps)\n', (45076, 45135), False, 'from utils.utils import LogEvalRunHook, LogTrainRunHook\n'), ((45674, 45694), 'random.Random', 'random.Random', (['(12345)'], {}), '(12345)\n', (45687, 45694), False, 'import random\n'), ((47633, 47690), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""***** Running training *****"""'], {}), "('***** Running training *****')\n", (47658, 47690), True, 'import tensorflow as tf\n'), ((47695, 47773), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" Num orig examples = %d"""', '(end_index - start_index)'], {}), "(' Num orig examples = %d', end_index - start_index)\n", (47720, 47773), True, 'import tensorflow as tf\n'), ((47778, 47864), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" Num split examples = %d"""', 'train_writer.num_features'], {}), "(' Num split examples = %d', train_writer.\n num_features)\n", (47803, 47864), True, 'import tensorflow as tf\n'), ((47864, 47934), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" Batch size = %d"""', 'FLAGS.train_batch_size'], {}), "(' Batch size = %d', FLAGS.train_batch_size)\n", (47889, 47934), True, 'import tensorflow as tf\n'), ((47939, 48001), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" Num steps = %d"""', 'num_train_steps'], {}), "(' Num steps = %d', num_train_steps)\n", (47964, 48001), True, 'import tensorflow as tf\n'), ((48006, 48059), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" LR = %f"""', 'learning_rate'], {}), "(' LR = %f', learning_rate)\n", (48031, 48059), True, 'import tensorflow as tf\n'), ((48368, 48379), 'time.time', 'time.time', ([], {}), '()\n', (48377, 48379), False, 'import time\n'), ((50715, 50775), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""***** Running predictions *****"""'], {}), "('***** Running predictions *****')\n", (50740, 50775), True, 'import tensorflow as tf\n'), ((50937, 51009), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" Batch size = %d"""', 'FLAGS.predict_batch_size'], {}), "(' Batch size = %d', FLAGS.predict_batch_size)\n", (50962, 51009), True, 'import tensorflow as tf\n'), ((51340, 51351), 'time.time', 'time.time', ([], {}), '()\n', (51349, 51351), False, 'import time\n'), ((52199, 52217), 'numpy.mean', 'np.mean', (['time_list'], {}), '(time_list)\n', (52206, 52217), True, 'import numpy as np\n'), ((52575, 52633), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""-----------------------------"""'], {}), "('-----------------------------')\n", (52600, 52633), True, 'import tensorflow as tf\n'), ((52638, 52786), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Total Inference Time = %0.2f for Sentences = %d"""', 'eval_time_elapsed', '(eval_hooks[-1].count * FLAGS.predict_batch_size)'], {}), "('Total Inference Time = %0.2f for Sentences = %d',\n eval_time_elapsed, eval_hooks[-1].count * FLAGS.predict_batch_size)\n", (52663, 52786), True, 'import tensorflow as tf\n'), ((52807, 53008), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Total Inference Time W/O Overhead = %0.2f for Sentences = %d"""', 'eval_time_wo_overhead', '((eval_hooks[-1].count - eval_hooks[-1].skipped) * FLAGS.predict_batch_size)'], {}), "(\n 'Total Inference Time W/O Overhead = %0.2f for Sentences = %d',\n eval_time_wo_overhead, (eval_hooks[-1].count - eval_hooks[-1].skipped) *\n FLAGS.predict_batch_size)\n", (52832, 53008), True, 'import tensorflow as tf\n'), ((53020, 53077), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Summary Inference Statistics"""'], {}), "('Summary Inference Statistics')\n", (53045, 53077), True, 'import tensorflow as tf\n'), ((53082, 53152), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Batch size = %d"""', 'FLAGS.predict_batch_size'], {}), "('Batch size = %d', FLAGS.predict_batch_size)\n", (53107, 53152), True, 'import tensorflow as tf\n'), ((53157, 53228), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Sequence Length = %d"""', 'FLAGS.max_seq_length'], {}), "('Sequence Length = %d', FLAGS.max_seq_length)\n", (53182, 53228), True, 'import tensorflow as tf\n'), ((53233, 53318), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Precision = %s"""', "('fp16' if FLAGS.use_fp16 else 'fp32')"], {}), "('Precision = %s', 'fp16' if FLAGS.use_fp16 else\n 'fp32')\n", (53258, 53318), True, 'import tensorflow as tf\n'), ((53319, 53406), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Confidence Level 50 (ms) = %0.2f"""', '(cf_50 * 1000)'], {}), "('Latency Confidence Level 50 (ms) = %0.2f', cf_50 *\n 1000)\n", (53344, 53406), True, 'import tensorflow as tf\n'), ((53407, 53494), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Confidence Level 90 (ms) = %0.2f"""', '(cf_90 * 1000)'], {}), "('Latency Confidence Level 90 (ms) = %0.2f', cf_90 *\n 1000)\n", (53432, 53494), True, 'import tensorflow as tf\n'), ((53495, 53582), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Confidence Level 95 (ms) = %0.2f"""', '(cf_95 * 1000)'], {}), "('Latency Confidence Level 95 (ms) = %0.2f', cf_95 *\n 1000)\n", (53520, 53582), True, 'import tensorflow as tf\n'), ((53583, 53670), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Confidence Level 99 (ms) = %0.2f"""', '(cf_99 * 1000)'], {}), "('Latency Confidence Level 99 (ms) = %0.2f', cf_99 *\n 1000)\n", (53608, 53670), True, 'import tensorflow as tf\n'), ((53671, 53761), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Confidence Level 100 (ms) = %0.2f"""', '(cf_100 * 1000)'], {}), "('Latency Confidence Level 100 (ms) = %0.2f', \n cf_100 * 1000)\n", (53696, 53761), True, 'import tensorflow as tf\n'), ((53761, 53830), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Latency Average (ms) = %0.2f"""', '(avg * 1000)'], {}), "('Latency Average (ms) = %0.2f', avg * 1000)\n", (53786, 53830), True, 'import tensorflow as tf\n'), ((53835, 53935), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Throughput Average (sentences/sec) = %0.2f"""', 'ss_sentences_per_second'], {}), "('Throughput Average (sentences/sec) = %0.2f',\n ss_sentences_per_second)\n", (53860, 53935), True, 'import tensorflow as tf\n'), ((53936, 53994), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""-----------------------------"""'], {}), "('-----------------------------')\n", (53961, 53994), True, 'import tensorflow as tf\n'), ((54025, 54075), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""predictions.json"""'], {}), "(FLAGS.output_dir, 'predictions.json')\n", (54037, 54075), False, 'import os\n'), ((54100, 54156), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""nbest_predictions.json"""'], {}), "(FLAGS.output_dir, 'nbest_predictions.json')\n", (54112, 54156), False, 'import os\n'), ((54189, 54237), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""null_odds.json"""'], {}), "(FLAGS.output_dir, 'null_odds.json')\n", (54201, 54237), False, 'import os\n'), ((9748, 9793), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""max calibration."""'], {}), "('max calibration.')\n", (9773, 9793), True, 'import tensorflow as tf\n'), ((10752, 10791), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""fusing QKV"""'], {}), "('fusing QKV')\n", (10777, 10791), True, 'import tensorflow as tf\n'), ((11997, 12034), 'pickle.dump', 'pickle.dump', (['self.calibrator_lists', 'f'], {}), '(self.calibrator_lists, f)\n', (12008, 12034), False, 'import pickle\n'), ((12064, 12119), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""model.ckpt-calibrated"""'], {}), "(FLAGS.output_dir, 'model.ckpt-calibrated')\n", (12076, 12119), False, 'import os\n'), ((13748, 13792), 'tensorflow.truncated_normal_initializer', 'tf.truncated_normal_initializer', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (13779, 13792), True, 'import tensorflow as tf\n'), ((13876, 13898), 'tensorflow.zeros_initializer', 'tf.zeros_initializer', ([], {}), '()\n', (13896, 13898), True, 'import tensorflow as tf\n'), ((15553, 15586), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (15584, 15586), True, 'import tensorflow as tf\n'), ((16891, 16936), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['"""frozen_modelTRT.pb"""', '"""wb"""'], {}), "('frozen_modelTRT.pb', 'wb')\n", (16908, 16936), True, 'import tensorflow as tf\n'), ((17442, 17487), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""*** Features ***"""'], {}), "('*** Features ***')\n", (17467, 17487), True, 'import tensorflow as tf\n'), ((18231, 18413), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['trt_graph'], {'input_map': "{'input_ids': input_ids, 'input_mask': input_mask, 'segment_ids': segment_ids}", 'return_elements': "['unstack:0', 'unstack:1']", 'name': '""""""'}), "(trt_graph, input_map={'input_ids': input_ids,\n 'input_mask': input_mask, 'segment_ids': segment_ids}, return_elements=\n ['unstack:0', 'unstack:1'], name='')\n", (18250, 18413), True, 'import tensorflow as tf\n'), ((18624, 18686), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'predictions': 'predictions'}), '(mode=mode, predictions=predictions)\n', (18650, 18686), True, 'import tensorflow as tf\n'), ((18777, 18833), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""initializing teacher model."""'], {}), "('initializing teacher model.')\n", (18802, 18833), True, 'import tensorflow as tf\n'), ((19216, 19240), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (19238, 19240), True, 'import tensorflow as tf\n'), ((19655, 19710), 'tensorflow.get_collection_ref', 'tf.get_collection_ref', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES)\n', (19676, 19710), True, 'import tensorflow as tf\n'), ((20311, 20383), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (["('restore from checkpoint: ' + init_checkpoint)"], {}), "('restore from checkpoint: ' + init_checkpoint)\n", (20336, 20383), True, 'import tensorflow as tf\n'), ((20444, 20511), 'modeling.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['tvars', 'init_checkpoint'], {}), '(tvars, init_checkpoint)\n', (20487, 20511), False, 'import modeling\n'), ((20576, 20674), 'modeling.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['qvars', 'init_checkpoint'], {'allow_shape_mismatch': '(True)'}), '(qvars, init_checkpoint,\n allow_shape_mismatch=True)\n', (20619, 20674), False, 'import modeling\n'), ((20794, 20856), 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['init_checkpoint', 'assignment_map'], {}), '(init_checkpoint, assignment_map)\n', (20823, 20856), True, 'import tensorflow as tf\n'), ((20900, 20958), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""**** Trainable Variables ****"""'], {}), "('**** Trainable Variables ****')\n", (20925, 20958), True, 'import tensorflow as tf\n'), ((23036, 23109), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'total_loss', 'train_op': 'train_op'}), '(mode=mode, loss=total_loss, train_op=train_op)\n', (23062, 23109), True, 'import tensorflow as tf\n'), ((24866, 24923), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['input_file'], {'num_parallel_reads': '(4)'}), '(input_file, num_parallel_reads=4)\n', (24889, 24923), True, 'import tensorflow as tf\n'), ((25130, 25165), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['input_file'], {}), '(input_file)\n', (25153, 25165), True, 'import tensorflow as tf\n'), ((31706, 31731), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (31729, 31731), False, 'import collections\n'), ((32843, 32892), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['output_null_log_odds_file', '"""w"""'], {}), "(output_null_log_odds_file, 'w')\n", (32860, 32892), True, 'import tensorflow as tf\n'), ((34944, 35035), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['("Unable to find text: \'%s\' in \'%s\'" % (pred_text, orig_text))'], {}), '("Unable to find text: \'%s\' in \'%s\'" % (pred_text,\n orig_text))\n', (34969, 35035), True, 'import tensorflow as tf\n'), ((35320, 35438), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Length not equal after stripping spaces: \'%s\' vs \'%s\'"""', 'orig_ns_text', 'tok_ns_text'], {}), '(\n "Length not equal after stripping spaces: \'%s\' vs \'%s\'", orig_ns_text,\n tok_ns_text)\n', (35345, 35438), True, 'import tensorflow as tf\n'), ((36013, 36069), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Couldn\'t map start position"""'], {}), '("Couldn\'t map start position")\n', (36038, 36069), True, 'import tensorflow as tf\n'), ((36382, 36436), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Couldn\'t map end position"""'], {}), '("Couldn\'t map end position")\n', (36407, 36436), True, 'import tensorflow as tf\n'), ((39194, 39362), 'tensorflow.estimator.export.build_raw_serving_input_receiver_fn', 'tf.estimator.export.build_raw_serving_input_receiver_fn', (["{'unique_ids': label_ids, 'input_ids': input_ids, 'input_mask': input_mask,\n 'segment_ids': segment_ids}"], {}), "({'unique_ids':\n label_ids, 'input_ids': input_ids, 'input_mask': input_mask,\n 'segment_ids': segment_ids})\n", (39249, 39362), True, 'import tensorflow as tf\n'), ((40200, 40233), 'shutil.rmtree', 'shutil.rmtree', (['final_model_folder'], {}), '(final_model_folder)\n', (40213, 40233), False, 'import shutil\n'), ((40246, 40286), 'os.rename', 'os.rename', (['saved_dir', 'final_model_folder'], {}), '(saved_dir, final_model_folder)\n', (40255, 40286), False, 'import os\n'), ((43839, 43849), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (43847, 43849), True, 'import horovod.tensorflow as hvd\n'), ((43851, 43861), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (43859, 43861), True, 'import horovod.tensorflow as hvd\n'), ((43994, 44004), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (44002, 44004), True, 'import horovod.tensorflow as hvd\n'), ((44029, 44039), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (44037, 44039), True, 'import horovod.tensorflow as hvd\n'), ((44125, 44141), 'horovod.tensorflow.local_rank', 'hvd.local_rank', ([], {}), '()\n', (44139, 44141), True, 'import horovod.tensorflow as hvd\n'), ((44152, 44162), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (44160, 44162), True, 'import horovod.tensorflow as hvd\n'), ((45986, 46035), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""train.tf_record"""'], {}), "(FLAGS.output_dir, 'train.tf_record')\n", (45998, 46035), False, 'import os\n'), ((48499, 48510), 'time.time', 'time.time', ([], {}), '()\n', (48508, 48510), False, 'import time\n'), ((48843, 48901), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""-----------------------------"""'], {}), "('-----------------------------')\n", (48868, 48901), True, 'import tensorflow as tf\n'), ((48910, 49046), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Total Training Time = %0.2f for Sentences = %d"""', 'train_time_elapsed', '(num_train_steps * global_batch_size)'], {}), "('Total Training Time = %0.2f for Sentences = %d',\n train_time_elapsed, num_train_steps * global_batch_size)\n", (48935, 49046), True, 'import tensorflow as tf\n'), ((49075, 49268), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Total Training Time W/O Overhead = %0.2f for Sentences = %d"""', 'train_time_wo_overhead', '((num_train_steps - training_hooks[-1].skipped) * global_batch_size)'], {}), "(\n 'Total Training Time W/O Overhead = %0.2f for Sentences = %d',\n train_time_wo_overhead, (num_train_steps - training_hooks[-1].skipped) *\n global_batch_size)\n", (49100, 49268), True, 'import tensorflow as tf\n'), ((49288, 49408), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Throughput Average (sentences/sec) with overhead = %0.2f"""', 'avg_sentences_per_second'], {}), "(\n 'Throughput Average (sentences/sec) with overhead = %0.2f',\n avg_sentences_per_second)\n", (49313, 49408), True, 'import tensorflow as tf\n'), ((49408, 49508), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Throughput Average (sentences/sec) = %0.2f"""', 'ss_sentences_per_second'], {}), "('Throughput Average (sentences/sec) = %0.2f',\n ss_sentences_per_second)\n", (49433, 49508), True, 'import tensorflow as tf\n'), ((49513, 49571), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""-----------------------------"""'], {}), "('-----------------------------')\n", (49538, 49571), True, 'import tensorflow as tf\n'), ((51276, 51316), 'utils.utils.LogEvalRunHook', 'LogEvalRunHook', (['FLAGS.predict_batch_size'], {}), '(FLAGS.predict_batch_size)\n', (51290, 51316), False, 'from utils.utils import LogEvalRunHook, LogTrainRunHook\n'), ((51946, 51957), 'time.time', 'time.time', ([], {}), '()\n', (51955, 51957), False, 'import time\n'), ((8950, 8976), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (8964, 8976), True, 'import tensorflow as tf\n'), ((10896, 10947), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['f"""FUSE_QKV: {prefix:50}"""'], {}), "(f'FUSE_QKV: {prefix:50}')\n", (10921, 10947), True, 'import tensorflow as tf\n'), ((11924, 11977), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', 'FLAGS.calibrator_file'], {}), '(FLAGS.output_dir, FLAGS.calibrator_file)\n', (11936, 11977), False, 'import os\n'), ((15880, 15972), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['""" name = %s, shape = %s%s"""', 'var.name', 'var.shape', 'init_string'], {}), "(' name = %s, shape = %s%s', var.name, var.shape,\n init_string)\n", (15905, 15972), True, 'import tensorflow as tf\n'), ((17543, 17631), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (["(' name = %s, shape = %s' % (name, features[name].shape))"], {}), "(' name = %s, shape = %s' % (name, features[name]\n .shape))\n", (17568, 17631), True, 'import tensorflow as tf\n'), ((18845, 18873), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""teacher"""'], {}), "('teacher')\n", (18862, 18873), True, 'import tensorflow as tf\n'), ((19483, 19560), 'modeling.get_assignment_map_from_checkpoint', 'modeling.get_assignment_map_from_checkpoint', (['tvars', 'FLAGS.teacher', '"""teacher/"""'], {}), "(tvars, FLAGS.teacher, 'teacher/')\n", (19526, 19560), False, 'import modeling\n'), ((19569, 19631), 'tensorflow.train.init_from_checkpoint', 'tf.train.init_from_checkpoint', (['FLAGS.teacher', 'assignment_map_t'], {}), '(FLAGS.teacher, assignment_map_t)\n', (19598, 19631), True, 'import tensorflow as tf\n'), ((21361, 21395), 'modeling.get_shape_list', 'modeling.get_shape_list', (['input_ids'], {}), '(input_ids)\n', (21384, 21395), False, 'import modeling\n'), ((21471, 21528), 'tensorflow.one_hot', 'tf.one_hot', (['positions'], {'depth': 'seq_length', 'dtype': 'tf.float32'}), '(positions, depth=seq_length, dtype=tf.float32)\n', (21481, 21528), True, 'import tensorflow as tf\n'), ((21562, 21596), 'tensorflow.nn.log_softmax', 'tf.nn.log_softmax', (['logits'], {'axis': '(-1)'}), '(logits, axis=-1)\n', (21579, 21596), True, 'import tensorflow as tf\n'), ((21899, 21936), 'tensorflow.distributions.Categorical', 'tf.distributions.Categorical', ([], {'probs': 'x'}), '(probs=x)\n', (21927, 21936), True, 'import tensorflow as tf\n'), ((21949, 21986), 'tensorflow.distributions.Categorical', 'tf.distributions.Categorical', ([], {'probs': 'y'}), '(probs=y)\n', (21977, 21986), True, 'import tensorflow as tf\n'), ((22584, 22630), 'tensorflow.compat.v1.train.get_or_create_global_step', 'tf.compat.v1.train.get_or_create_global_step', ([], {}), '()\n', (22628, 22630), True, 'import tensorflow as tf\n'), ((22699, 22747), 'tensorflow.identity', 'tf.identity', (['new_global_step'], {'name': '"""step_update"""'}), "(new_global_step, name='step_update')\n", (22710, 22747), True, 'import tensorflow as tf\n'), ((22858, 23005), 'optimization.create_optimizer', 'optimization.create_optimizer', (['total_loss', 'learning_rate', 'num_train_steps', 'num_warmup_steps', 'hvd', '(False)', 'use_fp16', 'FLAGS.num_accumulation_steps'], {}), '(total_loss, learning_rate, num_train_steps,\n num_warmup_steps, hvd, False, use_fp16, FLAGS.num_accumulation_steps)\n', (22887, 23005), False, 'import optimization\n'), ((23351, 23413), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'predictions': 'predictions'}), '(mode=mode, predictions=predictions)\n', (23377, 23413), True, 'import tensorflow as tf\n'), ((24575, 24589), 'tensorflow.to_int32', 'tf.to_int32', (['t'], {}), '(t)\n', (24586, 24589), True, 'import tensorflow as tf\n'), ((25008, 25044), 'tensorflow.data.experimental.ignore_errors', 'tf.data.experimental.ignore_errors', ([], {}), '()\n', (25042, 25044), True, 'import tensorflow as tf\n'), ((32628, 32665), 'json.dumps', 'json.dumps', (['all_predictions'], {'indent': '(4)'}), '(all_predictions, indent=4)\n', (32638, 32665), False, 'import json\n'), ((32752, 32788), 'json.dumps', 'json.dumps', (['all_nbest_json'], {'indent': '(4)'}), '(all_nbest_json, indent=4)\n', (32762, 32788), False, 'import json\n'), ((43914, 43924), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (43922, 43924), True, 'import horovod.tensorflow as hvd\n'), ((44200, 44235), 'horovod.tensorflow.BroadcastGlobalVariablesHook', 'hvd.BroadcastGlobalVariablesHook', (['(0)'], {}), '(0)\n', (44232, 44235), True, 'import horovod.tensorflow as hvd\n'), ((46226, 46236), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (46234, 46236), True, 'import horovod.tensorflow as hvd\n'), ((46277, 46287), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (46285, 46287), True, 'import horovod.tensorflow as hvd\n'), ((46297, 46307), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (46305, 46307), True, 'import horovod.tensorflow as hvd\n'), ((50138, 50186), 'os.path.join', 'os.path.join', (['FLAGS.output_dir', '"""eval.tf_record"""'], {}), "(FLAGS.output_dir, 'eval.tf_record')\n", (50150, 50186), False, 'import os\n'), ((10213, 10258), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""mse calibration."""'], {}), "('mse calibration.')\n", (10238, 10258), True, 'import tensorflow as tf\n'), ((19397, 19407), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (19405, 19407), True, 'import horovod.tensorflow as hvd\n'), ((20287, 20297), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (20295, 20297), True, 'import horovod.tensorflow as hvd\n'), ((21760, 21791), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(att / T)'], {'axis': '(-1)'}), '(att / T, axis=-1)\n', (21773, 21791), True, 'import tensorflow as tf\n'), ((22022, 22058), 'tensorflow.distributions.kl_divergence', 'tf.distributions.kl_divergence', (['X', 'Y'], {}), '(X, Y)\n', (22052, 22058), True, 'import tensorflow as tf\n'), ((22776, 22786), 'tensorflow.no_op', 'tf.no_op', ([], {}), '()\n', (22784, 22786), True, 'import tensorflow as tf\n'), ((24964, 24974), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (24972, 24974), True, 'import horovod.tensorflow as hvd\n'), ((24976, 24986), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (24984, 24986), True, 'import horovod.tensorflow as hvd\n'), ((32923, 32961), 'json.dumps', 'json.dumps', (['scores_diff_json'], {'indent': '(4)'}), '(scores_diff_json, indent=4)\n', (32933, 32961), False, 'import json\n'), ((42707, 42738), 'tensorflow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', ([], {}), '()\n', (42736, 42738), False, 'from tensorflow.python.client import device_lib\n'), ((46343, 46353), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (46351, 46353), True, 'import horovod.tensorflow as hvd\n'), ((10405, 10454), 'tensorflow.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""entropy calibration."""'], {}), "('entropy calibration.')\n", (10430, 10454), True, 'import tensorflow as tf\n'), ((21201, 21211), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (21209, 21211), True, 'import horovod.tensorflow as hvd\n'), ((21641, 21694), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(one_hot_positions * log_probs)'], {'axis': '(-1)'}), '(one_hot_positions * log_probs, axis=-1)\n', (21654, 21694), True, 'import tensorflow as tf\n'), ((46160, 46170), 'horovod.tensorflow.size', 'hvd.size', ([], {}), '()\n', (46168, 46170), True, 'import horovod.tensorflow as hvd\n'), ((46476, 46486), 'horovod.tensorflow.rank', 'hvd.rank', ([], {}), '()\n', (46484, 46486), True, 'import horovod.tensorflow as hvd\n')] |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02-attribute extraction.ipynb (unless otherwise specified).
__all__ = ['get_field_name_tags', 'field_hierarchies_to_root', 'assign_idx_fields', 'initialise_site_data_with_ids',
'get_dict_head', 'datapackage_ref_to_ds_schema', 'init_datapackage_ref',
'extract_external_foreignkey_datapackage_refs', 'add_resource_locs_to_external_datapackage_refs',
'create_dir', 'download_attribute_data_to_temp_dir', 'load_datapackage', 'load_resource_attr_dfs',
'load_dataset_ref', 'get_datapackage_ref', 'load_full_id_map', 'determine_matched_ids',
'delete_null_attributes', 'delete_null_values', 'format_attr_value_type', 'format_all_attr_value_types',
'extract_attrs_from_resource_dfs', 'flatten_list', 'drop_duplicates_attrs', 'json_nan_to_none',
'construct_dictionary_knowledge_graph']
# Cell
import numpy as np
import pandas as pd
import json
import os
import typing
import datetime
from warnings import warn
import urllib.parse
from urllib.request import urlopen, urlretrieve
from frictionless import Package
# Cell
def get_field_name_tags(
schema: dict,
ids_resource_name: str='ids'
):
field_name_tags = {
field['name']: field['hierarchy']
for field
in schema['fields']
}
return field_name_tags
def field_hierarchies_to_root(field_hierarchies: dict):
root_fields = [k for k, v in field_hierarchies.items() if v=='root']
assert len(root_fields) == 1, 'There can be only 1 field with the hierarchy: `root`'
root_field = root_fields[0]
return root_field
def assign_idx_fields(df, index, root_field_type, alt_indexes=None, int_types=['integer']):
if not isinstance(index, list):
index = [index]
if alt_indexes is not None:
index = index + alt_indexes
if df.index.name in index:
df = df.reset_index()
df = df.dropna(subset=index, how='all').copy()
if root_field_type in int_types:
df.index = df.index.astype(int)
if len(set(index) - set(df.columns)) == 0:
if root_field_type in int_types:
df[index[0]] = df[index[0]].astype(int)
df = df.set_index(index)
assert df.index.unique().size == df.shape[0], 'There were duplicated values in the primary key field'
else:
raise ValueError(f'The expected primary key field, {primary_key_field}, is not within the dataset')
return df
# Cell
get_dict_head = lambda dict_, n=5: pd.Series(dict_).head(n).to_dict()
def initialise_site_data_with_ids(df_ids, field_hierarchies):
valid_hierarchy_types = ['root', 'parent', 'child', 'equivalent', 'equivalent/parent', 'equivalent/child']
site_data = {}
id_cols = df_ids.columns
for idx, *ids in df_ids.itertuples():
site_data[idx] = {}
site_data[idx]['id_hierarchies'] = {}
site_data[idx]['id_hierarchies']['parent'] = {}
site_data[idx]['id_hierarchies']['child'] = {}
site_data[idx]['id_hierarchies']['equivalent'] = {}
for id_type, id_value in pd.Series(dict(zip(id_cols, ids))).dropna().items():
field_hierarchy = field_hierarchies[id_type]
assert field_hierarchy in valid_hierarchy_types, f'The {field_hierarchy} field did not have a valid hierarchical attribute'
if 'equivalent/' in field_hierarchy:
hierarchy_if_not_array, hierarchy_if_array = field_hierarchy.split('/')
if isinstance(id_value, list):
if len(id_value) > 1:
site_data[idx]['id_hierarchies'][hierarchy_if_array][id_type] = id_value
else:
site_data[idx]['id_hierarchies'][hierarchy_if_not_array][id_type] = id_value[0]
else:
site_data[idx]['id_hierarchies'][field_hierarchy][id_type] = id_value
return site_data
# Cell
def datapackage_ref_to_ds_schema(datapackage_ref):
dp_url = datapackage_ref['package']
resource = datapackage_ref['resource']
dp_schema = json.load(urlopen(dp_url))
ds_schema = [
resource
for resource
in dp_schema['resources']
if resource['name'] == datapackage_ref['resource']
][0]
return ds_schema
def init_datapackage_ref(fk):
datapackage_ref = {
'package': fk['reference']['package'],
'resource': fk['reference']['resource'],
'attributes': fk['reference']['attributes'],
'dictionary_pk_field': fk['fields'],
'external_fk_field': fk['reference']['fields']
}
if 'alt_indexes' in fk['reference'].keys():
datapackage_ref['alt_indexes'] = fk['reference']['alt_indexes']
return datapackage_ref
def extract_external_foreignkey_datapackage_refs(resource, primary_key_field):
fk_external_datapackage_refs = [
init_datapackage_ref(fk)
for fk
in resource.schema['foreignKeys']
if ('package' in fk['reference'].keys())
]
for i, datapackage_ref in enumerate(fk_external_datapackage_refs):
ds_schema = datapackage_ref_to_ds_schema(datapackage_ref)
fk_external_datapackage_refs[i]['attribute_fields'] = {field['name']: field for field in ds_schema['schema']['fields']}
return fk_external_datapackage_refs
# Cell
def add_resource_locs_to_external_datapackage_refs(fk_external_datapackage_refs: str) -> dict:
for i, fk_external_datapackage_ref in enumerate(fk_external_datapackage_refs):
external_datapackage_basepath = '/'.join(fk_external_datapackage_ref['package'].split('/')[:-1])
external_datapackage_json = json.load(urlopen(fk_external_datapackage_ref['package']))
fk_external_datapackage_refs[i]['resource_loc'] = [
f"{external_datapackage_basepath}/{resource['path']}"
for resource
in external_datapackage_json['resources']
if resource['name'] == fk_external_datapackage_ref['resource']
][0]
fk_external_datapackage_refs[i]['name'] = external_datapackage_json['name']
return fk_external_datapackage_refs
# Cell
def create_dir(dir_loc: str='./temp', warn=False):
if not os.path.isdir(dir_loc):
os.mkdir(dir_loc)
elif warn == True:
warn(f'The directory `{dir_loc}` already exists')
return None
def download_attribute_data_to_temp_dir(
fk_external_datapackage_refs: dict,
temp_dir_loc: str='./temp'
):
create_dir(temp_dir_loc)
for fk_external_datapackage_ref in fk_external_datapackage_refs:
datapackage_name = fk_external_datapackage_ref['name']
datapackage_files = [fk_external_datapackage_ref['resource_loc'], fk_external_datapackage_ref['package']]
datapackage_temp_dir = f'{temp_dir_loc}/{datapackage_name}'
create_dir(datapackage_temp_dir)
for file_to_download in datapackage_files:
filename = file_to_download.split('/')[-1]
filepath = f'{datapackage_temp_dir}/{filename}'
if os.path.exists(filepath):
os.remove(filepath)
file_to_download = file_to_download.replace(' ', '%20')
urlretrieve(file_to_download, filepath)
return
# Cell
def load_datapackage(datapackage_ref, temp_dir_loc='./temp', return_type='df', set_index=True):
datapackage_fp = f"{temp_dir_loc}/{datapackage_ref['resource']}/datapackage.json"
datapackage_resource = datapackage_ref['resource']
external_datapackage = Package(datapackage_fp)
resource = external_datapackage.get_resource(datapackage_resource)
if return_type == 'package':
return external_datapackage
elif return_type == 'resource':
return resource
elif return_type == 'df':
df_resource = resource.to_pandas()
if set_index == True:
assert isinstance(datapackage_ref['external_fk_field'], str) or len(datapackage_ref['external_fk_field']==1), 'Only one primary key was expected to be matched on in the external datapackage'
field_type = [field['type'] for field in resource.schema['fields'] if field['name']==datapackage_ref['external_fk_field']][0]
if 'alt_indexes' in datapackage_ref.keys():
alt_indexes = datapackage_ref['alt_indexes']
else:
alt_indexes = None
df_resource = assign_idx_fields(df_resource, datapackage_ref['external_fk_field'], field_type, alt_indexes)
return df_resource
else:
raise ValueError('`` must be one of ["df", "resource", "package"]')
return resource
def load_resource_attr_dfs(fk_external_datapackage_refs, temp_dir_loc):
resource_attr_dfs = []
for datapackage_ref in fk_external_datapackage_refs:
df_external_resource_attrs = load_datapackage(datapackage_ref, temp_dir_loc=temp_dir_loc)
attrs_to_extract = datapackage_ref['attributes']
df_external_resource_attrs = df_external_resource_attrs[attrs_to_extract]
df_external_resource_attrs.name = datapackage_ref['package']
resource_attr_dfs += [df_external_resource_attrs]
return resource_attr_dfs
# Cell
get_datapackage_ref = lambda datapackage_refs, datapackage_url: [dp_ref for dp_ref in datapackage_refs if dp_ref['package']==datapackage_url][0]
def load_dataset_ref(datapackage_url, datapackage_refs, temp_dir_loc='./temp'):
dp_ref = get_datapackage_ref(datapackage_refs, datapackage_url)
package = load_datapackage(dp_ref, temp_dir_loc=temp_dir_loc, return_type='package')
dataset_ref = {
"datapackage_json_url": dp_ref['package'],
"datapackage_name": dp_ref['name'],
"related_resources": [
{
"resource_url": dp_ref['resource_loc'],
"resource_name": dp_ref['resource'],
"dictionary_pk_field": dp_ref['dictionary_pk_field'],
"external_fk_field": dp_ref['external_fk_field'],
"extracted_attributes": dp_ref['attributes']
}
]
}
if 'description' in package.keys():
dataset_ref["datapackage_description"]: package['description']
if 'alt_indexes' in dp_ref.keys():
dataset_ref['related_resources'][0]['alt_indexes'] = dp_ref['alt_indexes']
return dataset_ref
# Cell
flatten_list = lambda list_: [item for sublist in list_ for item in sublist]
drop_duplicates_attrs = lambda attrs, subset=None: pd.DataFrame(attrs).pipe(lambda df: df.loc[df.astype(str).drop_duplicates(subset=subset).index]).to_dict(orient='records')
def load_full_id_map(single_site_data):
full_id_map = {}
for hierarchy_ids in single_site_data['id_hierarchies'].values():
full_id_map.update(hierarchy_ids)
return full_id_map
def determine_matched_ids(df_resource_attrs, dict_ids):
if isinstance(df_resource_attrs.index, pd.core.indexes.multi.MultiIndex):
primary_index = df_resource_attrs.index.get_level_values(0)
else:
primary_index = df_resource_attrs.index
matched_dict_ids = list(set(primary_index).intersection(set(dict_ids)))
matched_dict_ids = [dict_id for dict_id in dict_ids if dict_id in matched_dict_ids]
return matched_dict_ids
def delete_null_attributes(site_data):
for site_id, site_attributes in site_data.items():
if 'attributes' in site_attributes.keys():
for idx, attribute in enumerate(site_attributes['attributes']):
if isinstance(attribute['value'], float):
if np.isnan(attribute['value']) or attribute['value']=='nan':
site_data[site_id]['attributes'].remove(attribute)
return site_data
def delete_null_values(_dict, null_values=[None, np.nan, 'nan']):
for key, value in list(_dict.items()):
if isinstance(value, dict):
delete_none(value)
elif value in null_values:
del _dict[key]
elif isinstance(value, list):
for v_i in value:
if v_i in null_values:
del v_i
return _dict
def format_attr_value_type(attr_value):
if isinstance(attr_value, datetime.date):
return attr_value.strftime('%Y-%m-%d')
if isinstance(attr_value, datetime.datetime):
return attr_value.strftime('%Y-%m-%d %H:%M')
if isinstance(attr_value, pd.Timestamp):
return attr_value.strftime('%Y-%m-%d %H:%M')
return attr_value
def format_all_attr_value_types(site_data):
for site, data in site_data.items():
if 'attributes' in data.keys():
for i, attr in enumerate(data['attributes']):
site_data[site]['attributes'][i]['value'] = format_attr_value_type(attr['value'])
return site_data
def extract_attrs_from_resource_dfs(site_data, datapackage_refs, temp_dir_loc, root_id='osuked_id'):
dp_schemas = {}
resource_attr_dfs = load_resource_attr_dfs(datapackage_refs, temp_dir_loc)
for site_id in site_data.keys():
site_data[site_id]['datasets'] = {}
full_id_map = load_full_id_map(site_data[site_id])
full_id_map[root_id] = site_id
for df_resource_attrs in resource_attr_dfs:
dp_url = df_resource_attrs.name
datapackage_ref = get_datapackage_ref(datapackage_refs, dp_url)
dataset_ref = load_dataset_ref(df_resource_attrs.name, datapackage_refs, temp_dir_loc=temp_dir_loc)
if datapackage_ref['dictionary_pk_field'] in full_id_map.keys():
dict_ids = full_id_map[datapackage_ref['dictionary_pk_field']]
if not isinstance(dict_ids, list):
dict_ids = [dict_ids]
matched_dict_ids = determine_matched_ids(df_resource_attrs, dict_ids)
if len(matched_dict_ids) > 0:
# datasets
if dp_url not in site_data[site_id]['datasets'].keys():
site_data[site_id]['datasets'][dp_url] = dataset_ref
else:
site_data[site_id]['datasets'][dp_url]['related_resources'] += dataset_ref['related_resources']
# attributes
if isinstance(df_resource_attrs.index, pd.core.indexes.multi.MultiIndex):
site_attrs_from_resource = []
for id_ in matched_dict_ids:
df_relevant_resource_attrs = df_resource_attrs.xs(id_, level=0)
df_relevant_resource_attrs = df_relevant_resource_attrs.dropna(how='all', axis=1)
if df_relevant_resource_attrs.shape[0] > 0:
site_attrs_from_resource += [df_relevant_resource_attrs.to_dict()]
else:
site_attrs_from_resource = df_resource_attrs.loc[matched_dict_ids].dropna(how='all', axis=1).to_dict(orient='records')
def get_attribute_name(datapackage_ref, attribute):
if 'title' in datapackage_ref['attribute_fields'][attribute]:
return datapackage_ref['attribute_fields'][attribute]['title']
else:
return attribute
reshaped_site_attrs = flatten_list([
[
{
'source': dp_url,
'id': dict_id,
'attribute': get_attribute_name(datapackage_ref, k),
'field_schema': datapackage_ref['attribute_fields'][k],
'value': v
}
for k, v
in dict_.items()
if (not pd.isnull(v)) and (v not in [None, np.nan, 'None', 'nan'])
]
for dict_id, dict_
in zip(matched_dict_ids, site_attrs_from_resource)
])
if len(site_attrs_from_resource) >= 1:
if 'attributes' not in site_data[site_id].keys():
site_data[site_id]['attributes'] = []
site_data[site_id]['attributes'] += reshaped_site_attrs
subset = list(set(site_data[site_id]['attributes'][0].keys())-{'field_schema'}) # this assumes all attribute entries have the same keys
site_data[site_id]['attributes'] = drop_duplicates_attrs(site_data[site_id]['attributes'], subset=subset)
site_data = delete_null_attributes(site_data)
site_data = format_all_attr_value_types(site_data)
return site_data
# Cell
def json_nan_to_none(
obj: typing.Any,
*,
json_constant_map: dict={'NaN': None},
default: typing.Callable=None
) -> None:
json_string = json.dumps(obj, default=default)
cleaned_obj = json.loads(
json_string,
parse_constant=lambda constant: json_constant_map[constant],
)
return cleaned_obj
# Cell
def construct_dictionary_knowledge_graph(datapackage_fp, temp_dir_loc, resource_name='ids'):
package = Package(datapackage_fp, profile='tabular-data-package')
ids_resource = package.get_resource(resource_name)
field_hierarchies = get_field_name_tags(ids_resource.schema)
root_field = field_hierarchies_to_root(field_hierarchies)
root_field_type = [field['type'] for field in ids_resource.schema['fields'] if field['name']==root_field][0]
df_ids = assign_idx_fields(ids_resource.to_pandas(), root_field, root_field_type)
site_data = initialise_site_data_with_ids(df_ids, field_hierarchies)
fk_external_datapackage_refs = extract_external_foreignkey_datapackage_refs(ids_resource, primary_key_field=root_field)
fk_external_datapackage_refs = add_resource_locs_to_external_datapackage_refs(fk_external_datapackage_refs)
download_attribute_data_to_temp_dir(fk_external_datapackage_refs, temp_dir_loc=temp_dir_loc)
site_data = extract_attrs_from_resource_dfs(site_data, fk_external_datapackage_refs, temp_dir_loc)
site_data = json_nan_to_none(site_data)
return site_data | [
"pandas.DataFrame",
"os.mkdir",
"os.remove",
"json.loads",
"os.path.isdir",
"os.path.exists",
"urllib.request.urlopen",
"frictionless.Package",
"json.dumps",
"numpy.isnan",
"urllib.request.urlretrieve",
"pandas.isnull",
"pandas.Series",
"warnings.warn"
] | [((7494, 7517), 'frictionless.Package', 'Package', (['datapackage_fp'], {}), '(datapackage_fp)\n', (7501, 7517), False, 'from frictionless import Package\n'), ((16877, 16909), 'json.dumps', 'json.dumps', (['obj'], {'default': 'default'}), '(obj, default=default)\n', (16887, 16909), False, 'import json\n'), ((16928, 17017), 'json.loads', 'json.loads', (['json_string'], {'parse_constant': '(lambda constant: json_constant_map[constant])'}), '(json_string, parse_constant=lambda constant: json_constant_map[\n constant])\n', (16938, 17017), False, 'import json\n'), ((17175, 17230), 'frictionless.Package', 'Package', (['datapackage_fp'], {'profile': '"""tabular-data-package"""'}), "(datapackage_fp, profile='tabular-data-package')\n", (17182, 17230), False, 'from frictionless import Package\n'), ((4091, 4106), 'urllib.request.urlopen', 'urlopen', (['dp_url'], {}), '(dp_url)\n', (4098, 4106), False, 'from urllib.request import urlopen, urlretrieve\n'), ((6193, 6215), 'os.path.isdir', 'os.path.isdir', (['dir_loc'], {}), '(dir_loc)\n', (6206, 6215), False, 'import os\n'), ((6225, 6242), 'os.mkdir', 'os.mkdir', (['dir_loc'], {}), '(dir_loc)\n', (6233, 6242), False, 'import os\n'), ((5654, 5701), 'urllib.request.urlopen', 'urlopen', (["fk_external_datapackage_ref['package']"], {}), "(fk_external_datapackage_ref['package'])\n", (5661, 5701), False, 'from urllib.request import urlopen, urlretrieve\n'), ((6274, 6323), 'warnings.warn', 'warn', (['f"""The directory `{dir_loc}` already exists"""'], {}), "(f'The directory `{dir_loc}` already exists')\n", (6278, 6323), False, 'from warnings import warn\n'), ((7026, 7050), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (7040, 7050), False, 'import os\n'), ((7169, 7208), 'urllib.request.urlretrieve', 'urlretrieve', (['file_to_download', 'filepath'], {}), '(file_to_download, filepath)\n', (7180, 7208), False, 'from urllib.request import urlopen, urlretrieve\n'), ((7068, 7087), 'os.remove', 'os.remove', (['filepath'], {}), '(filepath)\n', (7077, 7087), False, 'import os\n'), ((2515, 2531), 'pandas.Series', 'pd.Series', (['dict_'], {}), '(dict_)\n', (2524, 2531), True, 'import pandas as pd\n'), ((10433, 10452), 'pandas.DataFrame', 'pd.DataFrame', (['attrs'], {}), '(attrs)\n', (10445, 10452), True, 'import pandas as pd\n'), ((11513, 11541), 'numpy.isnan', 'np.isnan', (["attribute['value']"], {}), "(attribute['value'])\n", (11521, 11541), True, 'import numpy as np\n'), ((15787, 15799), 'pandas.isnull', 'pd.isnull', (['v'], {}), '(v)\n', (15796, 15799), True, 'import pandas as pd\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 21:15:48 2018
@author: Adekanye
"""
import numpy as np
import matplotlib.pyplot as plt
import dataGenerator
class LogReg(object):
def __init__(self, eta=0.1, n_iter=10):
assert eta >= 0 and eta <= 1, "eta must be between 0.0 and 1.0"
assert type(n_iter) is int, "n_iter must be type int"
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
assert X.shape[0] == y.shape[0], "X and y dimensions not compatible"
self.coef_ = np.zeros(X.shape[1] + 1)
for _ in range(self.n_iter):
output = self.net_input(X)
error = y - output
self.coef_[0] += self.eta * error.sum()
self.coef_[1:] += self.eta * X.T.dot(error)
return self
def net_input(self, X):
return 1 / (1 + np.exp(-(X.dot(self.coef_[1:]) + self.coef_[0])))
def predict(self, X):
print(self.net_input(X))
return np.where(self.net_input(X) >= 0.5, 1, 0)
#X = np.asarray([[4, 2], [3, 5], [2, 1], [7, 10], [11, 12], [10, 14]])
#y = np.asarray([1, 1, 1, 0, 0, 0])
#plt.scatter(X[0:3, 0], X[0:3, 1], color='red', marker='o', label='1')
#plt.scatter(X[3:, 0], X[3:, 1], color='blue', marker='x', label='0')
#plt.legend(loc='upper left')
#plt.show()
gen_data = dataGenerator.generate_data(x1_min=0, x2_min=0)
data, labels = gen_data.linearlySeparable(n_rows=50)
data = data.values
labels = labels.values.ravel()
log_reg = LogReg(n_iter=50)
log_reg.fit(data[0:40, :], labels[0:40,])
gen_data.plot(data[0:40, :],labels[0:40,])
| [
"numpy.zeros",
"dataGenerator.generate_data"
] | [((1345, 1392), 'dataGenerator.generate_data', 'dataGenerator.generate_data', ([], {'x1_min': '(0)', 'x2_min': '(0)'}), '(x1_min=0, x2_min=0)\n', (1372, 1392), False, 'import dataGenerator\n'), ((561, 585), 'numpy.zeros', 'np.zeros', (['(X.shape[1] + 1)'], {}), '(X.shape[1] + 1)\n', (569, 585), True, 'import numpy as np\n')] |
import xml.etree.ElementTree as ET
import warnings
import os
import glob
from ..base import PSGbase
import pandas as pd
import numpy as np
import mne
import shutil
def read_psg_edf(folder, include = 'all', preload = False):
"""
Read compumedics polysomnography files exported to .edf. This function was
only tested for .edf exported from compumedics profusion software and
requires a .xml file with scoring informations.
Parameters
----------
folder : str
path to the folder containing the .edf file and the .xml scoring file
include : list or 'all'
The list of channel to be loaded
preload : bool
Whether or not data is loaded in memory.
Returns
-------
raw : :py:class:`mne.io.BaseRaw`
An MNE Raw instance.
hypnogram : pd.DataFrame
A dataframe with sleep staging (label, duration and onset) informations.
events : pd.DataFrame
A dataframe containing events (e.g. apneas, arousals) informations.
Each line corresponds to a different events. Dataframe keys are
"EVT_LABEL", "EVT_TIME" and "EVT_LENGTH" and represents label,
onset and duration of the onsets.
Note
----
Onset of sleep stages and events are in seconds elapsed since the
beginning of the PSG recording.
"""
if len(glob.glob(folder + '/*.edf'))==0:
raise ValueError("No edf file there: " + folder)
if len(glob.glob(folder + '/*.xml'))==0:
raise ValueError("No xml file there: " + folder)
pg = PSGedf(folder)
hypnogram = pg.hypnogram()
events = pg.events()
raw = pg.raw_data(include=include, preload = preload)
return raw, hypnogram, events
def edf_what_channels(folder):
"""Helper functions to print available channels given a folder with
polysomnography files"""
pg = PSGedf(folder)
return pg.available_channel
class PSGedf(PSGbase):
"""
Class to read edf files.
"""
def __init__(self, folder):
super().__init__(folder)
self.edf_file = glob.glob(folder + '/*.edf')[0]
self.xml_file = glob.glob(folder + '/*.xml')[0]
r = mne.io.read_raw_edf(self.edf_file, preload=False, verbose='error')
self.available_channel = r.info['ch_names']
def hypnogram(self):
"""
Reads sleep staging informations.
Returns
-------
hypnogram : pd.DataFrame
A dataframe with sleep staging (label, duration and onset)
informations.
"""
stage = import_stages_from_xml(self.xml_file)
return stage
def raw_data(self, include = 'all', preload=False):
"""
Reads PSG raw data and returns a :py:class:`mne.io.BaseRaw`.
Returns
-------
raw : :py:class:`mne.io.BaseRaw`
An MNE Raw instance.
"""
raw = mne.io.read_raw_edf(self.edf_file, preload=False, verbose='error')
if include=='all': include = raw.info['ch_names']
raw = raw.pick_channels(include)
if preload:
raw = raw.load_data()
return raw
def events(self):
"""
Reads manual scoring of events (e.g. apneas and arousals).
Returns
-------
events : pd.DataFrame
A dataframe containing events (e.g. apneas, arousals) informations.
Each line corresponds to a different events. Dataframe keys are
"EVT_LABEL", "EVT_TIME" and "EVT_LENGTH" and represents label,
onset and duration of the onsets.
"""
events = import_events_from_xml(self.xml_file)
return events
def summary(self):
raise NotImplementedError
def import_stages_from_xml(xml_file):
"""
Read compumedics .xml and extract sleep staging informations
Parameters
----------
xml_file : str
path fo the xml file to read
Returns
-------
stages : pd.DataFrame
A dataframe with sleep staging (label, duration and onset)
informations.
Notes
-------
By default compumedics labels 'Unsure" epochs as 9. This was changed to -1.
If any stages is labelled as 4 (sleep stage 4), we re-label it as sleep
stage 3 (R&K conversion to AASM).
"""
tree = ET.parse(xml_file)
root = tree.getroot()
stages = pd.DataFrame()
label = np.asarray([child.text for child in root.findall("./SleepStages/SleepStage")], dtype='int')
if np.sum(label==4)>0:
label[label==4] = 3
label[label==9] =-1
stages['label'] = label
stages['duration'] = np.ones_like(label) * \
np.asarray([child.text for child in
root.findall("./EpochLength")],dtype='int')
stages['onset'] = np.cumsum(stages['duration'].values) - \
np.asarray([child.text for child in
root.findall("./EpochLength")],dtype='int')
return stages
def import_events_from_xml(xml_file):
"""
Read compumedics .xml and extract events informations
Parameters
----------
xml_file : str
path fo the xml file to read
Returns
-------
stages : pd.DataFrame
A dataframe with events (label, duration and onset)
informations.
"""
tree = ET.parse(xml_file)
root = tree.getroot()
events = pd.DataFrame()
events['EVT_LABEL'] = \
[child.text for child in root.findall("./ScoredEvents/ScoredEvent/Name")]
events['EVT_TIME'] = \
np.asarray([child.text for child in
root.findall("./ScoredEvents/ScoredEvent/Start")],
dtype='float')
events['EVT_LENGTH'] = np.asarray([child.text for child in root.findall("./ScoredEvents/ScoredEvent/Duration")],
dtype='float')
return events
def edf_deidentify(path, save_dir=None, overwrite=False):
"""
Taken from : https://prerau.bwh.harvard.edu/edf-de-identification-tool/
All credit goes to the original authors.
:param path: path to edf file to be deidentified
:param save_dir: directory to save deidentified copy of edf (default is directory of edf file)
:param overwrite: replace the edf file given with the deidentified file (default = False) (Note: if True, ignores
save_dir)
:return: None
"""
# If no save_dir provided, use dir of edf file
if save_dir is None:
save_dir = os.path.dirname(path)
else: # check if save_dir is valid
if not os.path.isdir(save_dir):
raise Exception("Invalid save_dir path: " + save_dir)
# Check if invalid file
if not os.path.isfile(path):
raise Exception("Invalid file: " + path)
# Copy file to new name
if not overwrite:
path_new = save_dir + '/' + os.path.basename(path)[0:-4] + '_deidentified.edf'
shutil.copy(path, path_new)
path = path_new
# Open file(s) and deidentify
f = open(path, "r+", encoding="iso-8859-1") # 'r' = read
try:
f.write('%-8s' % "0")
f.write('%-80s' % "DEIDENTIFIED") # Remove patient info
f.write('%-80s' % "DEIDENTIFIED") # Remove recording info
f.write('01.01.01') # Set date as 01.01.01
except UnicodeDecodeError:
f.close()
f = open(path, "r+", encoding="iso-8859-2") # 'r' = read
try:
f.write('%-8s' % "0")
f.write('%-80s' % "DEIDENTIFIED") # Remove patient info
f.write('%-80s' % "DEIDENTIFIED") # Remove recording info
f.write('01.01.01') # Set date as 01.01.01
except UnicodeDecodeError:
f.close()
f = open(path, "r+", encoding="utf-8") # 'r' = read
try:
f.write('%-8s' % "0")
f.write('%-80s' % "DEIDENTIFIED") # Remove patient info
f.write('%-80s' % "DEIDENTIFIED") # Remove recording info
f.write('01.01.01') # Set date as 01.01.01
f.close()
finally:
raise Exception('No valid encoding format found')
return | [
"pandas.DataFrame",
"xml.etree.ElementTree.parse",
"numpy.sum",
"numpy.ones_like",
"os.path.basename",
"os.path.isdir",
"os.path.dirname",
"numpy.cumsum",
"mne.io.read_raw_edf",
"os.path.isfile",
"glob.glob",
"shutil.copy"
] | [((4270, 4288), 'xml.etree.ElementTree.parse', 'ET.parse', (['xml_file'], {}), '(xml_file)\n', (4278, 4288), True, 'import xml.etree.ElementTree as ET\n'), ((4328, 4342), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4340, 4342), True, 'import pandas as pd\n'), ((5310, 5328), 'xml.etree.ElementTree.parse', 'ET.parse', (['xml_file'], {}), '(xml_file)\n', (5318, 5328), True, 'import xml.etree.ElementTree as ET\n'), ((5368, 5382), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5380, 5382), True, 'import pandas as pd\n'), ((2147, 2213), 'mne.io.read_raw_edf', 'mne.io.read_raw_edf', (['self.edf_file'], {'preload': '(False)', 'verbose': '"""error"""'}), "(self.edf_file, preload=False, verbose='error')\n", (2166, 2213), False, 'import mne\n'), ((2867, 2933), 'mne.io.read_raw_edf', 'mne.io.read_raw_edf', (['self.edf_file'], {'preload': '(False)', 'verbose': '"""error"""'}), "(self.edf_file, preload=False, verbose='error')\n", (2886, 2933), False, 'import mne\n'), ((4455, 4473), 'numpy.sum', 'np.sum', (['(label == 4)'], {}), '(label == 4)\n', (4461, 4473), True, 'import numpy as np\n'), ((4580, 4599), 'numpy.ones_like', 'np.ones_like', (['label'], {}), '(label)\n', (4592, 4599), True, 'import numpy as np\n'), ((4769, 4805), 'numpy.cumsum', 'np.cumsum', (["stages['duration'].values"], {}), "(stages['duration'].values)\n", (4778, 4805), True, 'import numpy as np\n'), ((6480, 6501), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (6495, 6501), False, 'import os\n'), ((6688, 6708), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (6702, 6708), False, 'import os\n'), ((6905, 6932), 'shutil.copy', 'shutil.copy', (['path', 'path_new'], {}), '(path, path_new)\n', (6916, 6932), False, 'import shutil\n'), ((1333, 1361), 'glob.glob', 'glob.glob', (["(folder + '/*.edf')"], {}), "(folder + '/*.edf')\n", (1342, 1361), False, 'import glob\n'), ((1435, 1463), 'glob.glob', 'glob.glob', (["(folder + '/*.xml')"], {}), "(folder + '/*.xml')\n", (1444, 1463), False, 'import glob\n'), ((2047, 2075), 'glob.glob', 'glob.glob', (["(folder + '/*.edf')"], {}), "(folder + '/*.edf')\n", (2056, 2075), False, 'import glob\n'), ((2103, 2131), 'glob.glob', 'glob.glob', (["(folder + '/*.xml')"], {}), "(folder + '/*.xml')\n", (2112, 2131), False, 'import glob\n'), ((6557, 6580), 'os.path.isdir', 'os.path.isdir', (['save_dir'], {}), '(save_dir)\n', (6570, 6580), False, 'import os\n'), ((6846, 6868), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (6862, 6868), False, 'import os\n')] |
'''
Created on Aug 9, 2017
@author: <NAME>
'''
from math import sqrt
from ScopeFoundry import Measurement
from ScopeFoundry.helper_funcs import sibling_path, load_qt_ui_file
from ScopeFoundry import h5_io
import pyqtgraph as pg
import numpy as np
import time
import os
from random import randint,random
from PyQt5.QtWidgets import QDoubleSpinBox, QCheckBox
from blaze.expr.reductions import std
class VOTABlockTrainingMeasure(Measurement):
# this is the name of the measurement that ScopeFoundry uses
# when displaying your measurement and saving data related to it
name = "block_training"
def setup(self):
"""
Runs once during App initialization.
This is the place to load a user interface file,
define settings, and set up data structures.
"""
# Define ui file to be used as a graphical interface
# This file can be edited graphically with Qt Creator
# sibling_path function allows python to find a file in the same folder
# as this python module
self.ui_filename = sibling_path(__file__, "block_training_plot.ui")
#Load ui file and convert it to a live QWidget of the user interface
self.ui = load_qt_ui_file(self.ui_filename)
# Measurement Specific Settings
# This setting allows the option to save data to an h5 data file during a run
# All settings are automatically added to the Microscope user interface
self.settings.New('save_h5', dtype=bool, initial=False)
self.settings.New('train',dtype = bool, initial = False, ro = False)
self.settings.New('block_number', dtype = int, initial = 10)
self.settings.New('save_movie', dtype=bool, initial=False,ro=False)
self.settings.New('movie_on', dtype=bool, initial=False,ro=True)
self.settings.New('random',dtype=bool, initial=False, ro= False)
self.settings.New('audio_on',dtype=bool,initial = False,ro = False)
self.settings.New('lick_training',dtype=bool,initial=False)
self.settings.New('free_drop', dtype = bool, initial = False)
self.settings.New('threshold',dtype=float,initial = 0.3)
self.settings.New('clean_level',dtype= int, initial = 82,vmin=50,vmax=100)
'''
setting up experimental setting parameters for task
'''
exp_settings = []
exp_settings.append(self.settings.New('block', dtype = int, initial = 5))
exp_settings.append(self.settings.New('delay', dtype = int, initial = 5000, vmin = 500))
exp_settings.append(self.settings.New('go', dtype = int, initial = 2500))
exp_settings.append(self.settings.New('refract', dtype = int, initial = 2500, vmin = 500))
exp_settings.append(self.settings.New('punish', dtype = int, initial = 10000))
exp_settings.append(self.settings.New('channel1', dtype = int, initial = 6))
exp_settings.append(self.settings.New('channel2', dtype = int, initial = 6))
exp_settings.append(self.settings.New('level1', dtype = int, initial = 100, vmin = 0, vmax = 100))
exp_settings.append(self.settings.New('level2', dtype = int, initial = 100, vmin = 0, vmax = 100))
exp_settings.append(self.settings.New('Tpulse1', dtype = int, initial = 50))
exp_settings.append(self.settings.New('Tpulse2', dtype = int, initial = 50))
exp_settings.append(self.settings.New('interval1', dtype = int, initial = 400))
exp_settings.append(self.settings.New('interval2', dtype = int, initial = 1200))
exp_settings.append(self.settings.New('lower_bound1', dtype = float, initial = 7.5))
exp_settings.append(self.settings.New('lower_bound2', dtype = float, initial = 0.5))
exp_settings.append(self.settings.New('higher_bound1', dtype = float, initial = 500))
exp_settings.append(self.settings.New('higher_bound2', dtype = float, initial = 7.5))
self.exp_settings = exp_settings
'''
Setting up lqs for recording stats
'''
self.stat_settings = []
self.stat_settings.append(self.settings.New('trial', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('success', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('failure', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('early', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('idle', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('success_percent', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('failure_percent', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('early_percent', dtype = int, initial = 0, ro = True))
self.stat_settings.append(self.settings.New('idle_percent', dtype = int, initial = 0, ro = True))
'''
Setting up lqs for indicator lights
'''
self.state_ind = []
self.reward_ind = []
self.lick_ind = []
self.state_ind.append(self.settings.New('delay_ind', dtype=bool, initial=False, ro = True))
self.state_ind.append(self.settings.New('go_ind', dtype=bool, initial=False, ro = True))
self.state_ind.append(self.settings.New('refract_ind', dtype=bool, initial=False, ro = True))
self.state_ind.append(self.settings.New('punish_ind', dtype=bool, initial=False, ro = True))
self.reward_ind.append(self.settings.New('left_reward_ind', dtype=bool, initial=False, ro = True))
self.reward_ind.append(self.settings.New('right_reward_ind', dtype=bool, initial=False, ro = True))
self.lick_ind.append(self.settings.New('left_lick_ind', dtype=bool, initial=False, ro = True))
self.lick_ind.append(self.settings.New('right_lick_ind', dtype=bool, initial=False, ro = True))
self.all_ind = self.state_ind + self.reward_ind + self.lick_ind
#self.settings.New('sampling_period', dtype=float, unit='s', initial=0.005)
# Create empty numpy array to serve as a buffer for the acquired data
#self.buffer = np.zeros(10000, dtype=float)
# Define how often to update display during a run
self.display_update_period = 0.04
'''
add reference to hardware
'''
# Convenient reference to the hardware used in the measurement
self.daq_ai = self.app.hardware['daq_ai']
self.daq_do = self.app.hardware['daq_do']
self.arduino_sol = self.app.hardware['arduino_sol']
self.water=self.app.hardware['arduino_water']
self.camera=self.app.hardware['thorcam']
self.sound=self.app.hardware['sound']
self.odometer = self.app.hardware['arduino_odometer']
self.motor = self.app.hardware['arduino_motor']
def setup_figure(self):
"""
Runs once during App initialization, after setup()
This is the place to make all graphical interface initializations,
build plots, etc.
"""
# connect ui widgets to measurement/hardware settings or functions
self.ui.start_pushButton.clicked.connect(self.start)
self.ui.interrupt_pushButton.clicked.connect(self.interrupt)
self.settings.train.connect_to_widget(self.ui.train_checkBox)
self.settings.save_h5.connect_to_widget(self.ui.save_h5_checkBox)
self.settings.save_movie.connect_to_widget(self.ui.save_movie_checkBox)
self.settings.random.connect_to_widget(self.ui.random_checkBox)
for exp_setting in self.exp_settings:
exp_widget_name=exp_setting.name+'_doubleSpinBox'
#print(exp_widget_name)
exp_widget=self.ui.findChild(QDoubleSpinBox,exp_widget_name)
exp_setting.connect_to_widget(exp_widget)
for stat_setting in self.stat_settings:
stat_widget_name=stat_setting.name+'_doubleSpinBox'
#print(exp_widget_name)
stat_widget=self.ui.findChild(QDoubleSpinBox,stat_widget_name)
stat_setting.connect_to_widget(stat_widget)
for ind in self.all_ind:
ind_widget_name=ind.name+'_checkBox'
ind_widget=self.ui.findChild(QCheckBox,ind_widget_name)
ind.connect_to_widget(ind_widget)
'''
Setting light icons and colors for indicators
'''
self.ui.delay_ind_checkBox.setStyleSheet(
'QCheckBox{color:orange;}QCheckBox::indicator:checked{image: url(./icons/c_o.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_o.png);}')
self.ui.go_ind_checkBox.setStyleSheet(
'QCheckBox{color:green;}QCheckBox::indicator:checked{image: url(./icons/c_g.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_g.png);}')
self.ui.refract_ind_checkBox.setStyleSheet(
'QCheckBox{color:yellow;}QCheckBox::indicator:checked{image: url(./icons/c_y.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_y.png);}')
self.ui.punish_ind_checkBox.setStyleSheet(
'QCheckBox{color:red;}QCheckBox::indicator:checked{image: url(./icons/c_r.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_r.png);}')
self.ui.right_lick_ind_checkBox.setStyleSheet(
'QCheckBox{color:blue;}QCheckBox::indicator:checked{image: url(./icons/c_b.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_b.png);}')
self.ui.left_lick_ind_checkBox.setStyleSheet(
'QCheckBox{color:yellow;}QCheckBox::indicator:checked{image: url(./icons/c_y.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_y.png);}')
self.ui.right_reward_ind_checkBox.setStyleSheet(
'QCheckBox{color:blue;}QCheckBox::indicator:checked{image: url(./icons/c_b.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_b.png);}')
self.ui.left_reward_ind_checkBox.setStyleSheet(
'QCheckBox{color:yellow;}QCheckBox::indicator:checked{image: url(./icons/c_y.png);}QCheckBox::indicator:unchecked{image: url(./icons/uc_y.png);}')
'''
Set up pyqtgraph graph_layout in the UI
'''
self.graph_layout=pg.GraphicsLayoutWidget()
self.ui.plot_groupBox.layout().addWidget(self.graph_layout)
self.aux_graph_layout=pg.GraphicsLayoutWidget()
self.ui.aux_plot_groupBox.layout().addWidget(self.aux_graph_layout)
self.camera_layout=pg.GraphicsLayoutWidget()
self.ui.camera_groupBox.layout().addWidget(self.camera_layout)
self.position_layout=pg.GraphicsLayoutWidget()
self.ui.position_plot_groupBox.layout().addWidget(self.position_layout)
# Create PlotItem object (a set of axes)
'''
add plot
'''
self.plot1 = self.graph_layout.addPlot(row=1,col=1,title="Lick")
self.plot2 = self.graph_layout.addPlot(row=2,col=1,title="breathing")
self.plot3 = self.graph_layout.addPlot(row=3,col=1,title="odor")
# Create PlotDataItem object ( a scatter plot on the axes )
self.breathing_plot = self.plot2.plot([0])
self.lick_plot_0 = self.plot1.plot([0])
self.lick_plot_1 = self.plot1.plot([1])
self.odor_plot = []
for i in range(8):
self.odor_plot.append(self.plot3.plot([i]))
self.lick_plot_0.setPen('y')
self.lick_plot_1.setPen('b')
self.odor_plot[0].setPen('b')
self.odor_plot[4].setPen('b')
self.T=np.linspace(0,10,10000)
self.k=0
self.plot4 = self.aux_graph_layout.addPlot(title = 'Statistics')
self.stat_plot = []
for i in range(6):
self.stat_plot.append(self.plot4.plot([i]))
self.stat_plot[0].setPen('g')
self.stat_plot[1].setPen('r')
self.stat_plot[2].setPen('m')
self.stat_plot[3].setPen('w')
self.stat_plot[4].setPen('y')
self.stat_plot[5].setPen('b')
self.camera_view=pg.ViewBox()
self.camera_layout.addItem(self.camera_view)
self.camera_image=pg.ImageItem()
self.camera_view.addItem(self.camera_image)
self.position_plot = self.position_layout.addPlot(title='Position')
self.position_map = self.position_plot.plot([0])
self.pos_x = np.zeros((100,))
self.pos_y = np.zeros((100,))
self.position_map.setData(self.pos_x,self.pos_y)
def update_display(self):
"""
Displays (plots) the numpy array self.buffer.
This function runs repeatedly and automatically during the measurement run.
its update frequency is defined by self.display_update_period
"""
self.lick_plot_0.setData(self.k+self.T,self.buffer[:,1])
self.lick_plot_1.setData(self.k+self.T,self.buffer[:,2])
self.breathing_plot.setData(self.k+self.T,self.buffer[:,0])
for i in range(8):
self.odor_plot[i].setData(self.k + self.T, self.buffer[:,i+6])
for i in range(4):
self.stat_plot[i].setData(self.stat[0,0:self.ntrials+1],self.stat[5+i,0:self.ntrials+1])
self.stat_plot[4].setData(self.side_stat[0,0:self.ntrials+1],self.side_stat[7,0:self.ntrials+1])
self.stat_plot[5].setData(self.side_stat[0,0:self.ntrials+1],self.side_stat[8,0:self.ntrials+1])
'''
update position
'''
self.pos_x[0:-1] = self.pos_x[1:]
self.pos_y[0:-1] = self.pos_x[1:]
self.pos_x[-1] = self.odometer.settings.x.value()
self.pos_y[-1] = self.odometer.settings.y.value()
self.position_map.setData(self.pos_x,self.pos_y)
if self.settings.movie_on.value():
self.camera_image.setImage(self.camera.read())
if self.settings.save_movie.value():
self.camera.write()
#print(self.buffer_h5.size)
def run(self):
"""
Runs when measurement is started. Runs in a separate thread from GUI.
It should not update the graphical interface directly, and should only
focus on data acquisition.
"""
'''
disable controls
'''
self.settings.save_h5.change_readonly(True)
self.settings.save_movie.change_readonly(True)
self.settings.train.change_readonly(True)
self.ui.save_h5_checkBox.setEnabled(False)
self.ui.save_movie_checkBox.setEnabled(False)
self.ui.train_checkBox.setEnabled(False)
if self.camera.connected.value():
self.settings.movie_on.update_value(True)
self.ntrials = 1
num_of_chan=self.daq_ai.settings.num_of_chan.value()
self.buffer = np.zeros((10000,num_of_chan+12), dtype=float)
self.stat = np.zeros((9,2000), dtype = float)
self.side_stat = np.zeros((11,2000), dtype = float)
statrec = StatRec()
siderec = SideRec()
'''
initialize position
'''
position = 0
'''
Decide whether to create HDF5 file or not
'''
# first, create a data file
if self.settings['save_h5']:
# if enabled will create an HDF5 file with the plotted data
# first we create an H5 file (by default autosaved to app.settings['save_dir']
# This stores all the hardware and app meta-data in the H5 file
file_name_index=0
file_name=os.path.join(self.app.settings.save_dir.value(),self.app.settings.sample.value())+'_'+str(file_name_index)+'.h5'
while os.path.exists(file_name):
file_name_index+=1
file_name=os.path.join(self.app.settings.save_dir.value(),self.app.settings.sample.value())+'_'+str(file_name_index)+'.h5'
self.h5file = h5_io.h5_base_file(app=self.app, measurement=self,fname = file_name)
# create a measurement H5 group (folder) within self.h5file
# This stores all the measurement meta-data in this group
self.h5_group = h5_io.h5_create_measurement_group(measurement=self, h5group=self.h5file)
# create an h5 dataset to store the data
self.buffer_h5 = self.h5_group.create_dataset(name = 'buffer',
shape = self.buffer.shape,
dtype = self.buffer.dtype,
maxshape=(None,self.buffer.shape[1]))
self.stat_h5 = self.h5_group.create_dataset(name = 'stat',
shape = self.stat.shape,
dtype = self.stat.dtype)
self.side_stat_h5 = self.h5_group.create_dataset(name = 'side_stat',
shape = self.side_stat.shape,
dtype = self.side_stat.dtype)
if self.settings.save_movie.value():
file_name_index=0
file_name=os.path.join(self.app.settings.save_dir.value(),self.app.settings.sample.value())+'_'+str(file_name_index)+'.avi'
while os.path.exists(file_name):
file_name_index+=1
file_name=os.path.join(self.app.settings.save_dir.value(),self.app.settings.sample.value())+'_'+str(file_name_index)+'.avi'
self.camera.settings.file_name.update_value(file_name)
self.camera.open_file()
# We use a try/finally block, so that if anything goes wrong during a measurement,
# the finally block can clean things up, e.g. close the data file object.
'''
create odor generator and task object
'''
if self.settings.train.value():
odorgen = OdorGen(T = self.settings.delay.value(),clean_level=self.settings.clean_level)
task = TrainingTask(audio_on = self.settings.audio_on.value(), water_hw = self.water, odor_gen = odorgen,
sound_hw = self.sound,
motor_hw = self.motor,
do_hw = self.daq_do,
stat_rec = statrec,
side_rec = siderec,
random_lq = self.settings.random,
state_lqs = self.state_ind,
reward_lqs = self.reward_ind,
block = self.settings.block.value(),
delay = self.settings.delay.value(),
go = self.settings.go.value(),
refract = self.settings.refract.value(),
punish = self.settings.punish.value(),
lick_training = self.settings.lick_training.value(),
free_drop = self.settings.free_drop.value())
task.set_stimuli(side = 1,
channel = self.settings.channel1.value(),
level = self.settings.level1.value(),
Tpulse = self.settings.Tpulse1.value(),
interval = self.settings.interval1.value(),
lower_bound = self.settings.lower_bound1.value(),
higher_bound = self.settings.higher_bound1.value())
task.set_stimuli(side = 2,
channel = self.settings.channel2.value(),
level = self.settings.level2.value(),
Tpulse = self.settings.Tpulse2.value(),
interval = self.settings.interval2.value(),
lower_bound = self.settings.lower_bound2.value(),
higher_bound = self.settings.higher_bound2.value())
'''
start actual protocol
'''
try:
'''
initialize counter ticks
'''
i = 0 #counter tick for loading buffer
j = 0 #counter tick for saving hdf5 file
self.k=0 #number of seconds saved
'''
Start DAQ, Default at 1kHz
'''
self.daq_ai.start()
# Will run forever until interrupt is called.
'''
Expand HDF5 buffer when necessary
'''
while not self.interrupt_measurement_called:
i %= self.buffer.shape[0]
if self.settings['save_h5']:
if j>(self.buffer_h5.shape[0]-1):
self.buffer_h5.resize((self.buffer_h5.shape[0]+self.buffer.shape[0],self.buffer.shape[1]))
self.k +=10
'''
Update Progress Bar
'''
self.settings['progress'] = i * 100./self.buffer.shape[0]
'''
Read DAQ sensor data(0:lick_left, 1:lick_right, 2:flowmeter)
'''
# Fills the buffer with sine wave readings from func_gen Hardware
self.buffer[i,0:num_of_chan] = self.daq_ai.read_data()
lick_0 = (self.buffer[i,1]<4)
lick_1 = (self.buffer[i,2]<4)
self.buffer[i,1]=lick_0 #convert lick sensor into 0(no lick) and 1(lick)
self.buffer[i,2]=lick_1
self.lick_ind[0].update_value(lick_0)
self.lick_ind[1].update_value(lick_1)
'''
get a readout for lick
'''
if (lick_0 and lick_1):
lick = 3
elif lick_0:
lick = 1
elif lick_1:
lick = 2
else:
lick = 0
'''
step through task
'''
if self.settings.train.value():
task.step(lick)
odor, odor_disp = odorgen.step()
self.buffer[i,(num_of_chan+2):(num_of_chan + 10)] = odor_disp
self.arduino_sol.load(odor)
else:
self.arduino_sol.load([0,0,0,0,self.settings.clean_level.value(),0,0,0])
pass
'''
Read and save Position and Speed at 25Hz(default) (3:position 4:speed)
'''
# if i%20 == 0:
# self.odometer.read()
# self.buffer[j:(j+20),num_of_chan+10] = self.odometer.settings.x.value()
# self.buffer[j:(j+20),num_of_chan + 11] = self.odometer.settings.y.value()
'''
Read odor value from the odor generator, otherwise fill with clean air(default)
'''
'''
write odor value to valve
'''
self.arduino_sol.write()
'''
write odor value to display (7:clean air 8:odor1 9:odor2 10:odor3)
'''
#to be implemented
'''
Save hdf5 file
'''
if self.settings['save_h5']:
if i == self.buffer.shape[0] - 1:
# if we are saving data to disk, copy data to H5 dataset
self.buffer_h5[(j-self.buffer.shape[0]+1):(j+1),:] = self.buffer
# flush H5 every 10s
self.h5file.flush()
# wait between readings.
# We will use our sampling_period settings to define time
#time.sleep(self.settings['sampling_period'])
i += 1
j += 1
'''
update_statistics
'''
if not statrec.updated():
self.stat[:], self.ntrials = statrec.write()
for counter in range(9):
self.stat_settings[counter].update_value(self.stat[counter,self.ntrials])
if self.settings['save_h5']:
self.stat_h5[:] = self.stat[:]
#self.h5file.flush()
if not siderec.updated():
self.side_stat[:] = siderec.write()
if self.settings['save_h5']:
self.side_stat_h5[:] = self.side_stat[:]
#self.h5file.flush()
if self.interrupt_measurement_called:
# Listen for interrupt_measurement_called flag.
# This is critical to do, if you don't the measurement will
# never stop.
# The interrupt button is a polite request to the
# Measurement thread. We must periodically check for
# an interrupt request
self.daq_ai.stop()
break
finally:
if self.settings['save_h5']:
# make sure to close the data file
self.h5file.close()
if self.camera.connected.value():
self.settings.movie_on.update_value(False)
time.sleep(0.1)
if self.settings.save_movie.value():
self.camera.close_file()
self.settings.save_h5.change_readonly(False)
self.settings.save_movie.change_readonly(False)
self.settings.train.change_readonly(False)
self.ui.save_h5_checkBox.setEnabled(True)
self.ui.save_movie_checkBox.setEnabled(True)
self.ui.train_checkBox.setEnabled(True)
class StatRec(object):
'''
Record mouse performance such as correct v.s. incorrect response
'''
def __init__(self):
self.buffer = np.zeros((9,2000))
self.state_dict = {'success': 1, 'failure':2, 'early':3, 'idle':4}
self.trial = 0
self.up_to_date = True
def increment(self,state_name):
'''
Called by task object, called whenever mice make a decision
'''
state = self.state_dict[state_name]
self.up_to_date =False
self.trial += 1
i = self.trial
self.buffer[:,i] = self.buffer[:,i - 1]
self.buffer[0,i] = self.trial
self.buffer[state,i] += 1
self.buffer[5:9, i] = 100.0 * self.buffer[1:5,i] / self.trial
def write(self):
'''
output to a buffer
'''
self.up_to_date = True
return self.buffer, self.trial
def updated(self):
return self.up_to_date
class SideRec(object):
'''
Record mouse performcance on each side
'''
def __init__(self):
self.buffer = np.zeros((11,2000))
self.trial = 0
self.up_to_date = True
def increment(self,state_name,side):
'''
Called by task object, called whenever mice make a decision
0: total trials
1: side 0 trials
2: side 1 trials
3: side 0 success
4: side 1 success
5: side 0 failure
6: side 1 failure
7: side 0 success percentage
8: side 1 success percentage
9: side 0 failure percentage
10: side 1 failure percentage
'''
self.up_to_date =False
self.trial += 1
i = self.trial
self.buffer[:,i] = self.buffer[:,i - 1]
self.buffer[0,i] = self.trial
if state_name == 'success':
state = 3
self.buffer[state+side,i] += 1
elif state_name == 'failure':
state = 5
self.buffer[state+side,i] += 1
else:
pass #no side picked
self.buffer[1+side,i] += 1
if self.buffer[1,i]>0:
self.buffer[7, i] = 100.0 * self.buffer[3,i] / self.buffer[1,i]
self.buffer[9, i] = 100.0 * self.buffer[5,i] / self.buffer[1,i]
if self.buffer[2,i]>0:
self.buffer[8, i] = 100.0 * self.buffer[4,i] / self.buffer[2,i]
self.buffer[10, i] = 100.0 * self.buffer[6,i] / self.buffer[2,i]
def write(self):
'''
output to a buffer
'''
self.up_to_date = True
return self.buffer
def updated(self):
'''
check to see if the last output was up to date
'''
return self.up_to_date
class OdorGen(object):
'''
Object generate a time series of odor
'''
def __init__(self,nchan = 8, T = 3000,clean_level=None):
self.tick = 0 # millisecond time counter
self.nchan = nchan #number of channels
self.T = T # size of the output time series
self.odor_buffer = np.zeros((self.nchan,self.T))
self.odor_buffer_disp = np.zeros((self.nchan,self.T))
self.on = False
self.clean_level = clean_level
def step(self):
'''
output the next odor level in the time series
'''
default_output = np.zeros((self.nchan,))
default_output[4] = self.clean_level.value()
if self.on:
if self.tick < self.T -1:
self.tick += 1
return self.odor_buffer[:,self.tick].squeeze(),self.odor_buffer_disp[:,self.tick].squeeze()
else:
self.on = False
self.odor_buffer[:] = 0
return default_output,default_output
else:
return default_output,default_output
def new_trial(self, channel = 4, level = 30, Tpulse = 50, interval = 2000, low_bound = 1, high_bound = 100):
'''
generate new time series
called from a task
'''
self.tick = 0 #reset tick
total_count = 0
'''
generate spike trace with a certain number of pulses, within the range defined by the std
'''
while total_count<low_bound or total_count > high_bound:
'''
Exponential Process Generation
'''
base_intervals = np.random.exponential(scale = interval, size = (50,)) #pulses are exponentially distributed
base_onsets = base_intervals.cumsum().astype(int)
'''
Spike generation
'''
full_length = int(base_intervals.sum()+2000)
spike_trace = np.zeros((full_length,))
spike_trace[base_onsets] = 1
spike_trace = spike_trace[0:self.T]
total_count = spike_trace.sum()
'''
Covolution with a kernel for valve control
'''
y = np.ones((Tpulse,)) * level
output_trace_disp = np.convolve(spike_trace,y)[0:self.T]
y[0:3] = 100
y[3:5] = 90
y[5:10] = 80
output_trace = np.convolve(spike_trace,y)[0:self.T]
output_trace =output_trace.clip(0,100) #make sure output is with in range
'''
output to both solenoid valve buffer and display
'''
clean_trace = self.clean_level.value() - output_trace_disp
clean_trace = clean_trace.clip(0,100)
self.odor_buffer[4,:] = clean_trace
self.odor_buffer[channel,:] = output_trace
self.odor_buffer_disp[channel,:] = output_trace_disp
self.on = True
class TrainingTask(object):
'''
task object control the state of the task, and also generate each task
'''
def __init__(self, audio_on, water_hw, odor_gen, sound_hw, motor_hw, do_hw, stat_rec,
side_rec, random_lq, state_lqs, reward_lqs, block = 3, delay = 2000, go = 5000, refract = 2000, punish = 5000, lick_training = False, free_drop = False):
'''
tick is for measuring time
'''
self.tick = 0
'''
the correct side
'''
self.side = 1
self.trial = 0
self.block = block
self.audio_on = audio_on
self.water = water_hw
self.odor_gen = odor_gen
self.sound = sound_hw
self.motor = motor_hw
self.do_hw = do_hw
self.stat_rec = stat_rec
self.side_rec = side_rec
self.random_lq = random_lq
self.state_lqs = state_lqs
self.reward_lqs = reward_lqs
self.lick_training = lick_training
self.free_drop = free_drop
self.water_available = False
self.duration = [delay,go,refract,punish]
self.channel = [0,0]
self.level = [0,0]
self.Tpulse = [100,100]
self.interval = [500,500]
self.lower_bound = [0,0]
self.higher_bound = [200,200]
self.state_dict = {'delay':0,'go':1,'refract':2,'punish':3}
self.state = 2
def step(self,lick = 0):
self.tick += 1
if self.state == self.state_dict['delay']:
self.delay_step(lick)
elif self.state == self.state_dict['go']:
self.go_step(lick)
elif self.state == self.state_dict['refract']:
self.refract_step(lick)
elif self.state == self.state_dict['punish']:
self.punish_step(lick)
def set_state(self,state_name):
self.tick = 0
self.state = self.state_dict[state_name]
for state_lq in self.state_lqs:
state_lq.update_value(False)
self.state_lqs[self.state].update_value(True)
'''
if beginning a new trial, check to see if switching side is needed
'''
if self.state == self.state_dict['delay']:
'''
switch side for if the number of trials reach the block number
'''
self.motor.settings.lick_position.update_value(False)
if self.random_lq.value():
self.side = np.random.randint(1,3)
else:
if self.trial >= self.block:
self.side = 3 - self.side
self.trial = 0
side = self.side - 1
for reward_lq in self.reward_lqs:
reward_lq.update_value(False)
self.reward_lqs[side].update_value(True)
'''
delivery odor if not in lick training, otherwise do not deliver
'''
if not self.lick_training:
self.odor_gen.new_trial(self.channel[side],self.level[side],self.Tpulse[side],self.interval[side],self.lower_bound[side],self.higher_bound[side])
self.do_hw.settings.on.update_value(True)
else:
self.do_hw.settings.on.update_value(False)
def set_stimuli(self,side = 1, channel = 4, level = 30, Tpulse = 50, interval = 2000, lower_bound = 0, higher_bound = 200):
side = side - 1
self.channel[side] = channel
self.level[side] = level
self.Tpulse[side] = Tpulse
self.interval[side] = interval
self.lower_bound[side] = lower_bound
self.higher_bound[side] = higher_bound
def delay_step(self, lick = 0):
if self.audio_on:
if lick > 0:
self.tick = 0
self.stat_rec.increment('early')
self.side_rec.increment('early',self.side - 1)
self.sound.wrong()
self.set_state('punish')
else:
pass
my_state = self.state_dict['delay']
if self.tick > self.duration[my_state]:
self.tick = 0
self.water_available = True
if self.audio_on:
self.sound.start()
else:
self.sound.start()
self.motor.settings.lick_position.update_value(True)
if self.free_drop:
self.water.give_water(self.side - 1)
self.set_state('go')
def go_step(self,lick = 0):
if self.lick_training:
if lick > 0 and lick<3:
if self.water_available:
self.water.give_water(lick - 1)
self.water_available = False
if self.audio_on:
self.sound.correct()
self.stat_rec.increment('success')
self.side_rec.increment('success',self.side - 1)
self.set_state('refract')
else:
if lick == self.side:
if self.water_available:
self.water.give_water(self.side - 1)
self.water_available = False
if self.audio_on:
self.sound.correct()
self.stat_rec.increment('success')
self.side_rec.increment('success',self.side - 1)
if not self.random_lq.value():
self.trial += 1
self.set_state('refract')
if lick > 0 and lick != self.side:
if self.audio_on:
self.sound.wrong()
else:
#self.motor.settings.lick_position.update_value(False)
pass
self.set_state('punish')
self.stat_rec.increment('failure')
self.side_rec.increment('failure',self.side - 1)
my_state = self.state_dict['go']
if self.tick > self.duration[my_state]:
self.set_state('refract')
self.stat_rec.increment('idle')
self.side_rec.increment('idle',self.side - 1)
def refract_step(self, lick = 0):
if self.lick_training:
my_state = self.state_dict['refract']
if self.tick > self.duration[my_state]:
self.set_state('delay')
if not self.audio_on:
self.motor.settings.lick_position.update_value(False)
else:
pass
if self.audio_on:
if lick > 0 and lick != self.side:
self.sound.wrong()
self.set_state('punish')
my_state = self.state_dict['refract']
if self.tick > self.duration[my_state]:
self.set_state('delay')
if not self.audio_on:
self.sound.correct()
self.motor.settings.lick_position.update_value(False)
def punish_step(self, lick = 0):
# if lick > 0:
# self.set_state('punish')
my_state = self.state_dict['punish']
if self.tick > self.duration[my_state]:
self.sound.correct()
self.set_state('delay') | [
"pyqtgraph.ViewBox",
"ScopeFoundry.helper_funcs.sibling_path",
"numpy.random.exponential",
"numpy.zeros",
"os.path.exists",
"numpy.ones",
"time.sleep",
"ScopeFoundry.h5_io.h5_base_file",
"numpy.random.randint",
"numpy.linspace",
"ScopeFoundry.helper_funcs.load_qt_ui_file",
"numpy.convolve",
... | [((1103, 1151), 'ScopeFoundry.helper_funcs.sibling_path', 'sibling_path', (['__file__', '"""block_training_plot.ui"""'], {}), "(__file__, 'block_training_plot.ui')\n", (1115, 1151), False, 'from ScopeFoundry.helper_funcs import sibling_path, load_qt_ui_file\n'), ((1256, 1289), 'ScopeFoundry.helper_funcs.load_qt_ui_file', 'load_qt_ui_file', (['self.ui_filename'], {}), '(self.ui_filename)\n', (1271, 1289), False, 'from ScopeFoundry.helper_funcs import sibling_path, load_qt_ui_file\n'), ((10477, 10502), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (10500, 10502), True, 'import pyqtgraph as pg\n'), ((10610, 10635), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (10633, 10635), True, 'import pyqtgraph as pg\n'), ((10748, 10773), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (10771, 10773), True, 'import pyqtgraph as pg\n'), ((10883, 10908), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (10906, 10908), True, 'import pyqtgraph as pg\n'), ((11832, 11857), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(10000)'], {}), '(0, 10, 10000)\n', (11843, 11857), True, 'import numpy as np\n'), ((12328, 12340), 'pyqtgraph.ViewBox', 'pg.ViewBox', ([], {}), '()\n', (12338, 12340), True, 'import pyqtgraph as pg\n'), ((12420, 12434), 'pyqtgraph.ImageItem', 'pg.ImageItem', ([], {}), '()\n', (12432, 12434), True, 'import pyqtgraph as pg\n'), ((12650, 12666), 'numpy.zeros', 'np.zeros', (['(100,)'], {}), '((100,))\n', (12658, 12666), True, 'import numpy as np\n'), ((12688, 12704), 'numpy.zeros', 'np.zeros', (['(100,)'], {}), '((100,))\n', (12696, 12704), True, 'import numpy as np\n'), ((15100, 15148), 'numpy.zeros', 'np.zeros', (['(10000, num_of_chan + 12)'], {'dtype': 'float'}), '((10000, num_of_chan + 12), dtype=float)\n', (15108, 15148), True, 'import numpy as np\n'), ((15166, 15198), 'numpy.zeros', 'np.zeros', (['(9, 2000)'], {'dtype': 'float'}), '((9, 2000), dtype=float)\n', (15174, 15198), True, 'import numpy as np\n'), ((15225, 15258), 'numpy.zeros', 'np.zeros', (['(11, 2000)'], {'dtype': 'float'}), '((11, 2000), dtype=float)\n', (15233, 15258), True, 'import numpy as np\n'), ((26765, 26784), 'numpy.zeros', 'np.zeros', (['(9, 2000)'], {}), '((9, 2000))\n', (26773, 26784), True, 'import numpy as np\n'), ((27706, 27726), 'numpy.zeros', 'np.zeros', (['(11, 2000)'], {}), '((11, 2000))\n', (27714, 27726), True, 'import numpy as np\n'), ((29698, 29728), 'numpy.zeros', 'np.zeros', (['(self.nchan, self.T)'], {}), '((self.nchan, self.T))\n', (29706, 29728), True, 'import numpy as np\n'), ((29760, 29790), 'numpy.zeros', 'np.zeros', (['(self.nchan, self.T)'], {}), '((self.nchan, self.T))\n', (29768, 29790), True, 'import numpy as np\n'), ((29976, 29999), 'numpy.zeros', 'np.zeros', (['(self.nchan,)'], {}), '((self.nchan,))\n', (29984, 29999), True, 'import numpy as np\n'), ((15968, 15993), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (15982, 15993), False, 'import os\n'), ((16208, 16275), 'ScopeFoundry.h5_io.h5_base_file', 'h5_io.h5_base_file', ([], {'app': 'self.app', 'measurement': 'self', 'fname': 'file_name'}), '(app=self.app, measurement=self, fname=file_name)\n', (16226, 16275), False, 'from ScopeFoundry import h5_io\n'), ((16460, 16532), 'ScopeFoundry.h5_io.h5_create_measurement_group', 'h5_io.h5_create_measurement_group', ([], {'measurement': 'self', 'h5group': 'self.h5file'}), '(measurement=self, h5group=self.h5file)\n', (16493, 16532), False, 'from ScopeFoundry import h5_io\n'), ((17688, 17713), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (17702, 17713), False, 'import os\n'), ((31039, 31088), 'numpy.random.exponential', 'np.random.exponential', ([], {'scale': 'interval', 'size': '(50,)'}), '(scale=interval, size=(50,))\n', (31060, 31088), True, 'import numpy as np\n'), ((31350, 31374), 'numpy.zeros', 'np.zeros', (['(full_length,)'], {}), '((full_length,))\n', (31358, 31374), True, 'import numpy as np\n'), ((31608, 31626), 'numpy.ones', 'np.ones', (['(Tpulse,)'], {}), '((Tpulse,))\n', (31615, 31626), True, 'import numpy as np\n'), ((31663, 31690), 'numpy.convolve', 'np.convolve', (['spike_trace', 'y'], {}), '(spike_trace, y)\n', (31674, 31690), True, 'import numpy as np\n'), ((31786, 31813), 'numpy.convolve', 'np.convolve', (['spike_trace', 'y'], {}), '(spike_trace, y)\n', (31797, 31813), True, 'import numpy as np\n'), ((26098, 26113), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (26108, 26113), False, 'import time\n'), ((34747, 34770), 'numpy.random.randint', 'np.random.randint', (['(1)', '(3)'], {}), '(1, 3)\n', (34764, 34770), True, 'import numpy as np\n')] |
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
import torch
import numpy as np
import torch.multiprocessing as mp
from collections import deque
from ..component.envs import LazyFrames
from ..utils.torch_utils import tensor
def build_replay(cfg):
if cfg.is_async:
return AsyncReplay(memory_size=cfg.memory_size, batch_size=cfg.batch_size)
else:
return Replay(memory_size=cfg.memory_size, batch_size=cfg.batch_size)
class Replay:
def __init__(self, memory_size, batch_size, drop_prob=0, to_np=True):
self.memory_size = memory_size
self.batch_size = batch_size
self.data = []
self.pos = 0
self.drop_prob = drop_prob
self.to_np = to_np
def feed(self, experience):
if np.random.rand() < self.drop_prob:
return
if self.pos >= len(self.data):
self.data.append(experience)
else:
self.data[self.pos] = experience
self.pos = (self.pos + 1) % self.memory_size
def feed_batch(self, experience):
for exp in experience:
self.feed(exp)
def sample(self, batch_size=None):
if self.empty():
return None
if batch_size is None:
batch_size = self.batch_size
sampled_indices = [np.random.randint(0, len(self.data)) for _ in range(batch_size)]
sampled_data = [self.data[ind] for ind in sampled_indices]
sampled_data = zip(*sampled_data)
if self.to_np:
# sampled_data = list(map(lambda x: np.asarray(x), sampled_data))
tmp_list = []
for x in sampled_data:
if isinstance(x[0], LazyFrames):
x = [t.__array__() for t in x]
tmp_list.append(np.asarray(x))
sampled_data = tmp_list
return sampled_data
def size(self):
return len(self.data)
def empty(self):
return not len(self.data)
def shuffle(self):
np.random.shuffle(self.data)
def clear(self):
self.data = []
self.pos = 0
class SkewedReplay:
def __init__(self, memory_size, batch_size, criterion):
self.replay1 = Replay(memory_size // 2, batch_size // 2)
self.replay2 = Replay(memory_size // 2, batch_size // 2)
self.criterion = criterion
def feed(self, experience):
if self.criterion(experience):
self.replay1.feed(experience)
else:
self.replay2.feed(experience)
def feed_batch(self, experience):
for exp in experience:
self.feed(exp)
def sample(self):
data1 = self.replay1.sample()
data2 = self.replay2.sample()
if data2 is not None:
data = list(map(lambda x: np.concatenate(x, axis=0), zip(data1, data2)))
else:
data = data1
return data
class AsyncReplay(mp.Process):
FEED = 0
SAMPLE = 1
EXIT = 2
FEED_BATCH = 3
def __init__(self, memory_size, batch_size):
mp.Process.__init__(self)
self.pipe, self.worker_pipe = mp.Pipe()
self.memory_size = memory_size
self.batch_size = batch_size
self.cache_len = 2
self.start()
def run(self):
replay = Replay(self.memory_size, self.batch_size)
cache = []
pending_batch = None
first = True
cur_cache = 0
def set_up_cache():
batch_data = replay.sample()
batch_data = [tensor(x) for x in batch_data]
for i in range(self.cache_len):
cache.append([x.clone() for x in batch_data])
for x in cache[i]: x.share_memory_()
sample(0)
sample(1)
def sample(cur_cache):
batch_data = replay.sample()
batch_data = [tensor(x) for x in batch_data]
for cache_x, x in zip(cache[cur_cache], batch_data):
cache_x.copy_(x)
# while len(batch_data)>0:
# del batch_data[0]
# torch.cuda.empty_cache()
while True:
op, data = self.worker_pipe.recv()
if op == self.FEED:
replay.feed(data)
elif op == self.FEED_BATCH:
if not first:
pending_batch = data
else:
for transition in data:
replay.feed(transition)
elif op == self.SAMPLE:
if first:
set_up_cache()
first = False
self.worker_pipe.send([cur_cache, cache])
else:
self.worker_pipe.send([cur_cache, None])
cur_cache = (cur_cache + 1) % 2
sample(cur_cache)
if pending_batch is not None:
for transition in pending_batch:
replay.feed(transition)
pending_batch = None
elif op == self.EXIT:
self.worker_pipe.close()
return
else:
raise Exception('Unknown command')
def feed(self, exp):
self.pipe.send([self.FEED, exp])
def feed_batch(self, exps):
self.pipe.send([self.FEED_BATCH, exps])
def sample(self):
self.pipe.send([self.SAMPLE, None])
cache_id, data = self.pipe.recv()
if data is not None:
self.cache = data
return self.cache[cache_id]
def close(self):
self.pipe.send([self.EXIT, None])
self.pipe.close()
class Storage:
def __init__(self, size, keys=None):
if keys is None:
keys = []
keys = keys + ['s', 'a', 'r', 'm',
'v', 'q', 'pi', 'log_pi', 'ent',
'adv', 'ret', 'q_a', 'log_pi_a',
'mean']
self.keys = keys
self.size = size
self.reset()
def add(self, data):
for k, v in data.items():
if k not in self.keys:
self.keys.append(k)
setattr(self, k, [])
getattr(self, k).append(v)
def placeholder(self):
for k in self.keys:
v = getattr(self, k)
if len(v) == 0:
setattr(self, k, [None] * self.size)
def reset(self):
for key in self.keys:
setattr(self, key, [])
def cat(self, keys):
data = [getattr(self, k)[:self.size] for k in keys]
return map(lambda x: torch.cat(x, dim=0), data)
| [
"numpy.concatenate",
"numpy.random.rand",
"numpy.asarray",
"torch.cat",
"torch.multiprocessing.Process.__init__",
"torch.multiprocessing.Pipe",
"numpy.random.shuffle"
] | [((2257, 2285), 'numpy.random.shuffle', 'np.random.shuffle', (['self.data'], {}), '(self.data)\n', (2274, 2285), True, 'import numpy as np\n'), ((3290, 3315), 'torch.multiprocessing.Process.__init__', 'mp.Process.__init__', (['self'], {}), '(self)\n', (3309, 3315), True, 'import torch.multiprocessing as mp\n'), ((3354, 3363), 'torch.multiprocessing.Pipe', 'mp.Pipe', ([], {}), '()\n', (3361, 3363), True, 'import torch.multiprocessing as mp\n'), ((1039, 1055), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (1053, 1055), True, 'import numpy as np\n'), ((6786, 6805), 'torch.cat', 'torch.cat', (['x'], {'dim': '(0)'}), '(x, dim=0)\n', (6795, 6805), False, 'import torch\n'), ((2039, 2052), 'numpy.asarray', 'np.asarray', (['x'], {}), '(x)\n', (2049, 2052), True, 'import numpy as np\n'), ((3033, 3058), 'numpy.concatenate', 'np.concatenate', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (3047, 3058), True, 'import numpy as np\n')] |
import numpy as np
import cv2 as cv
class CvComparisonSliderWindow(object):
def __init__(self,
window_name='debug',
line_color=(255, 255, 255),
line_thickness=0):
self.window_name = window_name
self.click_point = [1, 1]
self.line_color = line_color
self.line_thickness = line_thickness
cv.namedWindow(self.window_name)
cv.setMouseCallback(self.window_name, self._mouse_callback)
def _mouse_callback(self, event, x, y, flags, param):
if event == cv.EVENT_MOUSEMOVE:
self.click_point = [x, y]
def imshow(self, image1, image2, fps=None):
image1_width, image1_height = image1.shape[1], image1.shape[0]
image2_width, image2_height = image2.shape[1], image2.shape[0]
if ((image1_width != image2_width)
or (image1_height != image2_height)):
image2 = cv.resize(image2, (image1_width, image1_height))
image_height = image1.shape[0]
crop_image1 = image1[:, 0:self.click_point[0]]
crop_image2 = image2[:, self.click_point[0] + 1:]
concat_image = np.concatenate([crop_image1, crop_image2], axis=1)
if self.line_thickness > 0:
cv.line(concat_image, (self.click_point[0], 1),
(self.click_point[0], image_height),
self.line_color,
thickness=self.line_thickness)
if fps is not None:
cv.putText(concat_image, "FPS:" + str(fps), (10, 50),
cv.FONT_HERSHEY_SIMPLEX, 1.3, (0, 0, 0), 2, cv.LINE_AA)
cv.putText(concat_image, "FPS:" + str(fps), (10, 50),
cv.FONT_HERSHEY_SIMPLEX, 1.3, (252, 244, 234), 1,
cv.LINE_AA)
cv.imshow(self.window_name, concat_image)
return
| [
"cv2.line",
"numpy.concatenate",
"cv2.namedWindow",
"cv2.setMouseCallback",
"cv2.imshow",
"cv2.resize"
] | [((384, 416), 'cv2.namedWindow', 'cv.namedWindow', (['self.window_name'], {}), '(self.window_name)\n', (398, 416), True, 'import cv2 as cv\n'), ((425, 484), 'cv2.setMouseCallback', 'cv.setMouseCallback', (['self.window_name', 'self._mouse_callback'], {}), '(self.window_name, self._mouse_callback)\n', (444, 484), True, 'import cv2 as cv\n'), ((1157, 1207), 'numpy.concatenate', 'np.concatenate', (['[crop_image1, crop_image2]'], {'axis': '(1)'}), '([crop_image1, crop_image2], axis=1)\n', (1171, 1207), True, 'import numpy as np\n'), ((1807, 1848), 'cv2.imshow', 'cv.imshow', (['self.window_name', 'concat_image'], {}), '(self.window_name, concat_image)\n', (1816, 1848), True, 'import cv2 as cv\n'), ((931, 979), 'cv2.resize', 'cv.resize', (['image2', '(image1_width, image1_height)'], {}), '(image2, (image1_width, image1_height))\n', (940, 979), True, 'import cv2 as cv\n'), ((1257, 1393), 'cv2.line', 'cv.line', (['concat_image', '(self.click_point[0], 1)', '(self.click_point[0], image_height)', 'self.line_color'], {'thickness': 'self.line_thickness'}), '(concat_image, (self.click_point[0], 1), (self.click_point[0],\n image_height), self.line_color, thickness=self.line_thickness)\n', (1264, 1393), True, 'import cv2 as cv\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from PIL import Image, ImageDraw
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import seaborn as sns
import tqdm
class DetectionDataset(Dataset):
def __init__(self, marks, img_folder, transforms=None):
self.marks = marks
self.img_folder = img_folder
self.transforms = transforms
def __getitem__(self, idx):
item = self.marks[idx]
img_path = f'{self.img_folder}{item["file"]}'
img = Image.open(img_path).convert('RGB')
w, h = img.size
box_coords = item['nums']
boxes = []
labels = []
masks = []
for box in box_coords:
points = np.array(box['box'])
x0, y0 = np.min(points[:, 0]), np.min(points[:, 1])
x2, y2 = np.max(points[:, 0]), np.max(points[:, 1])
boxes.append([x0, y0, x2, y2])
labels.append(1)
nx, ny = w, h
poly_verts = points
x, y = np.meshgrid(np.arange(nx), np.arange(ny))
x, y = x.flatten(), y.flatten()
points = np.vstack((x,y)).T
path = Path(poly_verts)
grid = path.contains_points(points)
grid = grid.reshape((ny,nx)).astype(int)
masks.append(grid)
boxes = torch.as_tensor(boxes)
labels = torch.as_tensor(labels)
masks = torch.as_tensor(masks)
target = {
'boxes': boxes,
'labels': labels,
'masks': masks,
}
if self.transforms is not None:
img = self.transforms(img)
return img, target
def __len__(self):
return len(self.marks)
| [
"PIL.Image.open",
"matplotlib.path.Path",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.arange",
"torch.as_tensor",
"numpy.vstack"
] | [((1481, 1503), 'torch.as_tensor', 'torch.as_tensor', (['boxes'], {}), '(boxes)\n', (1496, 1503), False, 'import torch\n'), ((1521, 1544), 'torch.as_tensor', 'torch.as_tensor', (['labels'], {}), '(labels)\n', (1536, 1544), False, 'import torch\n'), ((1561, 1583), 'torch.as_tensor', 'torch.as_tensor', (['masks'], {}), '(masks)\n', (1576, 1583), False, 'import torch\n'), ((845, 865), 'numpy.array', 'np.array', (["box['box']"], {}), "(box['box'])\n", (853, 865), True, 'import numpy as np\n'), ((1303, 1319), 'matplotlib.path.Path', 'Path', (['poly_verts'], {}), '(poly_verts)\n', (1307, 1319), False, 'from matplotlib.path import Path\n'), ((632, 652), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (642, 652), False, 'from PIL import Image, ImageDraw\n'), ((889, 909), 'numpy.min', 'np.min', (['points[:, 0]'], {}), '(points[:, 0])\n', (895, 909), True, 'import numpy as np\n'), ((911, 931), 'numpy.min', 'np.min', (['points[:, 1]'], {}), '(points[:, 1])\n', (917, 931), True, 'import numpy as np\n'), ((953, 973), 'numpy.max', 'np.max', (['points[:, 0]'], {}), '(points[:, 0])\n', (959, 973), True, 'import numpy as np\n'), ((975, 995), 'numpy.max', 'np.max', (['points[:, 1]'], {}), '(points[:, 1])\n', (981, 995), True, 'import numpy as np\n'), ((1170, 1183), 'numpy.arange', 'np.arange', (['nx'], {}), '(nx)\n', (1179, 1183), True, 'import numpy as np\n'), ((1185, 1198), 'numpy.arange', 'np.arange', (['ny'], {}), '(ny)\n', (1194, 1198), True, 'import numpy as np\n'), ((1265, 1282), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (1274, 1282), True, 'import numpy as np\n')] |
import numpy
from ._common import jitted
__all__ = [
"depthplot",
]
@jitted
def resample(thickness, velocity_p, velocity_s, density, dz):
"""Resample velocity model."""
mmax = len(thickness)
sizes = numpy.empty(mmax, dtype=numpy.int32)
for i in range(mmax):
sizes[i] = numpy.ceil(thickness[i] / dz) if thickness[i] > dz else 1
size = sizes.sum()
d = numpy.empty(size, dtype=numpy.float64)
a = numpy.empty(size, dtype=numpy.float64)
b = numpy.empty(size, dtype=numpy.float64)
rho = numpy.empty(size, dtype=numpy.float64)
j = 0
for i in range(mmax):
dzi = thickness[i] / sizes[i]
for _ in range(sizes[i]):
d[j] = dzi
a[j] = velocity_p[i]
b[j] = velocity_s[i]
rho[j] = density[i]
j += 1
return d, a, b, rho
def depthplot(x, z, zmax, ax=None, **kwargs):
"""
Vertical step plot.
Parameters
----------
x : array_like
X coordinates of data points.
z : array_like
Z coordinates of data points.
zmax : scalar
Depth of last data point.
ax : matplotlib.pyplot.Axes or None, optional, default None
Matplotlib axes. If `None`, a new figure and axe is created.
Returns
-------
:class:`matplotlib.pyplot.Axes`
Plotted data axes.
"""
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("depthplot requires matplotlib to be installed.")
n = len(x)
if len(z) != n:
raise ValueError()
if zmax <= z[-1]:
raise ValueError()
xin = numpy.empty(2 * n)
xin[:-1:2] = x
xin[1::2] = x
zin = numpy.empty(2 * n)
zin[0] = z[0]
zin[1:-2:2] = z[1:]
zin[2:-1:2] = z[1:]
zin[-1] = zmax
if ax is None:
_, ax = plt.subplots(1, 1)
ax.plot(xin, zin, **kwargs)
return ax
| [
"numpy.empty",
"matplotlib.pyplot.subplots",
"numpy.ceil"
] | [((220, 256), 'numpy.empty', 'numpy.empty', (['mmax'], {'dtype': 'numpy.int32'}), '(mmax, dtype=numpy.int32)\n', (231, 256), False, 'import numpy\n'), ((392, 430), 'numpy.empty', 'numpy.empty', (['size'], {'dtype': 'numpy.float64'}), '(size, dtype=numpy.float64)\n', (403, 430), False, 'import numpy\n'), ((439, 477), 'numpy.empty', 'numpy.empty', (['size'], {'dtype': 'numpy.float64'}), '(size, dtype=numpy.float64)\n', (450, 477), False, 'import numpy\n'), ((486, 524), 'numpy.empty', 'numpy.empty', (['size'], {'dtype': 'numpy.float64'}), '(size, dtype=numpy.float64)\n', (497, 524), False, 'import numpy\n'), ((535, 573), 'numpy.empty', 'numpy.empty', (['size'], {'dtype': 'numpy.float64'}), '(size, dtype=numpy.float64)\n', (546, 573), False, 'import numpy\n'), ((1627, 1645), 'numpy.empty', 'numpy.empty', (['(2 * n)'], {}), '(2 * n)\n', (1638, 1645), False, 'import numpy\n'), ((1694, 1712), 'numpy.empty', 'numpy.empty', (['(2 * n)'], {}), '(2 * n)\n', (1705, 1712), False, 'import numpy\n'), ((1834, 1852), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (1846, 1852), True, 'import matplotlib.pyplot as plt\n'), ((302, 331), 'numpy.ceil', 'numpy.ceil', (['(thickness[i] / dz)'], {}), '(thickness[i] / dz)\n', (312, 331), False, 'import numpy\n')] |
#!/usr/bin/python
import numpy as np
import math as m
import soundfile as sf
import matplotlib.pyplot as plot
def genwin(winsize, f):
win = np.zeros(winsize)
for i in range(0, winsize):
y = f(i/winsize)
win[i] = y
return win
def hann(winsize):
return genwin(winsize, lambda x: 0.5 - 0.5 * m.cos(2 * m.pi * x))
def hamming(winsize):
return genwin(winsize, lambda x: 0.54 - 0.46 * m.cos(2 * m.pi * x))
def dft(wav, winsize=200, stride_divide=2, wintype='hamming'):
stride = int(winsize/stride_divide)
iter_times = int(m.ceil(len(wav) / winsize)) * stride_divide
target = np.zeros((m.ceil(len(wav) / winsize) + 1) * winsize)
target[int(winsize/2):len(wav)+int(winsize/2)] = np.array(wav)
result = np.zeros([iter_times, winsize])
if wintype == 'hann':
win = hann(winsize)
elif wintype == 'hamming':
win = hamming(winsize)
for i in range(0, iter_times):
source = target[i*stride:i*stride+winsize] * win
result[i] = 20 * np.sqrt(np.abs(np.fft.fft(source)))
plot.imshow(result.T)
plot.show()
if __name__ == '__main__':
wav, rate = sf.read('s1.wav')
dft(wav, winsize=200, stride_divide=8)
| [
"soundfile.read",
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"numpy.fft.fft",
"numpy.zeros",
"numpy.array",
"math.cos"
] | [((145, 162), 'numpy.zeros', 'np.zeros', (['winsize'], {}), '(winsize)\n', (153, 162), True, 'import numpy as np\n'), ((727, 740), 'numpy.array', 'np.array', (['wav'], {}), '(wav)\n', (735, 740), True, 'import numpy as np\n'), ((754, 785), 'numpy.zeros', 'np.zeros', (['[iter_times, winsize]'], {}), '([iter_times, winsize])\n', (762, 785), True, 'import numpy as np\n'), ((1060, 1081), 'matplotlib.pyplot.imshow', 'plot.imshow', (['result.T'], {}), '(result.T)\n', (1071, 1081), True, 'import matplotlib.pyplot as plot\n'), ((1086, 1097), 'matplotlib.pyplot.show', 'plot.show', ([], {}), '()\n', (1095, 1097), True, 'import matplotlib.pyplot as plot\n'), ((1143, 1160), 'soundfile.read', 'sf.read', (['"""s1.wav"""'], {}), "('s1.wav')\n", (1150, 1160), True, 'import soundfile as sf\n'), ((323, 342), 'math.cos', 'm.cos', (['(2 * m.pi * x)'], {}), '(2 * m.pi * x)\n', (328, 342), True, 'import math as m\n'), ((418, 437), 'math.cos', 'm.cos', (['(2 * m.pi * x)'], {}), '(2 * m.pi * x)\n', (423, 437), True, 'import math as m\n'), ((1035, 1053), 'numpy.fft.fft', 'np.fft.fft', (['source'], {}), '(source)\n', (1045, 1053), True, 'import numpy as np\n')] |
import os
import numpy as np
import multiprocessing
import time
import esutil
import glob
from .wcs_table import WcsTableBuilder
from .region_mapper import RegionMapper
from .healpix_consolidator import HealpixConsolidator
from .utils import op_str_to_code
from . import decasu_globals
class MultiHealpixMapper(object):
"""
Map a combination of bands/pixels
Parameters
----------
config : `Configuration`
decasu configuration object
outputpath : `str`
Base path for output files
ncores : `int`
Number of cores to run with
"""
def __init__(self, config, outputpath, ncores=1):
self.config = config
self.outputpath = outputpath
self.ncores = ncores
if not os.path.isdir(outputpath):
raise RuntimeError("Outputpath %s does not exist." % (outputpath))
def __call__(self, infile, bands=[], pixels=[], clear_intermediate_files=True):
"""
Compute maps for a combination of bands/pixels
Parameters
----------
infile : `str`
Name of input file with wcs and map information
bands : `list`, optional
List of bands to run. If blank, run all.
pixels : `list`, optional
List of pixels to run (nside=`config.nside_run`).
If blank, run all.
clear_intermediate_files : `bool`, optional
Clear intermediate files when done?
"""
# First build the wcs's
print('Reading input table...')
wcs_builder = WcsTableBuilder(self.config, [infile], bands)
print('Generating WCSs...')
t = time.time()
mp_ctx = multiprocessing.get_context("fork")
pool = mp_ctx.Pool(processes=self.ncores)
wcs_list, pixel_list, center_list = zip(*pool.map(wcs_builder,
range(len(decasu_globals.table)),
chunksize=1))
pool.close()
pool.join()
print('Time elapsed: ', time.time() - t)
# Copy into/out of globals
decasu_globals.wcs_list = wcs_list
table = decasu_globals.table
# Split into pixels
pixel_arr = np.concatenate(pixel_list)
pixel_indices = np.zeros(len(wcs_list) + 1, dtype=np.int32)
ctr = 0
for i in range(len(wcs_list)):
pixel_indices[i] = ctr
ctr += len(pixel_list[i])
pixel_indices[-1] = ctr
h, rev = esutil.stat.histogram(pixel_arr, rev=True)
u, = np.where(h > 0)
runpix_list = []
wcsindex_list = []
for ind in u:
i1a = rev[rev[ind]: rev[ind + 1]]
wcs_inds = np.searchsorted(pixel_indices, i1a, side='left')
miss, = np.where(pixel_indices[wcs_inds] != i1a)
wcs_inds[miss] -= 1
# This could probably be more efficient
for band in wcs_builder.bands:
ok, = np.where(table[self.config.band_field][wcs_inds] == band)
if ok.size > 0:
runpix_list.append(pixel_arr[i1a[0]])
wcsindex_list.append(wcs_inds[ok])
# Generate maps
region_mapper = RegionMapper(self.config, self.outputpath, 'pixel',
self.config.nside_coverage)
values = zip(runpix_list, wcsindex_list)
print('Generating maps for %d pixels...' % (len(runpix_list)))
t = time.time()
mp_ctx = multiprocessing.get_context("fork")
pool = mp_ctx.Pool(processes=self.ncores)
pool.starmap(region_mapper, values, chunksize=1)
pool.close()
pool.join()
print('Time elapsed: ', time.time() - t)
# Consolidate
print('Consolidating maps...')
fname_list = []
mapfiles_list = []
for map_type in self.config.map_types.keys():
for operation in self.config.map_types[map_type]:
op_code = op_str_to_code(operation)
for band in wcs_builder.bands:
# Get full map filename
fname = os.path.join(self.outputpath, self.config.map_filename(band,
map_type,
op_code))
# Check if file exists
if os.path.isfile(fname):
continue
# Assemble all the individual pixel maps
fname_template = self.config.healpix_map_filename_template(band,
map_type,
op_code)
mapfiles = sorted(glob.glob(os.path.join(self.outputpath,
'%d_?????' % (self.config.nside_run),
fname_template)))
fname_list.append(fname)
mapfiles_list.append(mapfiles)
hpix_consolidator = HealpixConsolidator(self.config, clear_intermediate_files)
values = zip(fname_list, mapfiles_list)
t = time.time()
mp_ctx = multiprocessing.get_context("fork")
pool = mp_ctx.Pool(processes=self.ncores)
pool.starmap(hpix_consolidator, values, chunksize=1)
pool.close()
pool.join()
print('Time elapsed: ', time.time() - t)
# Clean up
if clear_intermediate_files:
print('Cleaning intermediate directories...')
directories = sorted(glob.glob(os.path.join(self.outputpath,
'%d_?????' % (self.config.nside_run))))
for d in directories:
if not os.listdir(d):
# Clear directory, it is empty
os.rmdir(d)
| [
"esutil.stat.histogram",
"os.path.isdir",
"numpy.searchsorted",
"time.time",
"multiprocessing.get_context",
"os.path.isfile",
"numpy.where",
"os.rmdir",
"os.path.join",
"os.listdir",
"numpy.concatenate"
] | [((1638, 1649), 'time.time', 'time.time', ([], {}), '()\n', (1647, 1649), False, 'import time\n'), ((1667, 1702), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""fork"""'], {}), "('fork')\n", (1694, 1702), False, 'import multiprocessing\n'), ((2243, 2269), 'numpy.concatenate', 'np.concatenate', (['pixel_list'], {}), '(pixel_list)\n', (2257, 2269), True, 'import numpy as np\n'), ((2517, 2559), 'esutil.stat.histogram', 'esutil.stat.histogram', (['pixel_arr'], {'rev': '(True)'}), '(pixel_arr, rev=True)\n', (2538, 2559), False, 'import esutil\n'), ((2573, 2588), 'numpy.where', 'np.where', (['(h > 0)'], {}), '(h > 0)\n', (2581, 2588), True, 'import numpy as np\n'), ((3495, 3506), 'time.time', 'time.time', ([], {}), '()\n', (3504, 3506), False, 'import time\n'), ((3524, 3559), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""fork"""'], {}), "('fork')\n", (3551, 3559), False, 'import multiprocessing\n'), ((5353, 5364), 'time.time', 'time.time', ([], {}), '()\n', (5362, 5364), False, 'import time\n'), ((5382, 5417), 'multiprocessing.get_context', 'multiprocessing.get_context', (['"""fork"""'], {}), "('fork')\n", (5409, 5417), False, 'import multiprocessing\n'), ((748, 773), 'os.path.isdir', 'os.path.isdir', (['outputpath'], {}), '(outputpath)\n', (761, 773), False, 'import os\n'), ((2732, 2780), 'numpy.searchsorted', 'np.searchsorted', (['pixel_indices', 'i1a'], {'side': '"""left"""'}), "(pixel_indices, i1a, side='left')\n", (2747, 2780), True, 'import numpy as np\n'), ((2801, 2841), 'numpy.where', 'np.where', (['(pixel_indices[wcs_inds] != i1a)'], {}), '(pixel_indices[wcs_inds] != i1a)\n', (2809, 2841), True, 'import numpy as np\n'), ((2061, 2072), 'time.time', 'time.time', ([], {}), '()\n', (2070, 2072), False, 'import time\n'), ((2992, 3049), 'numpy.where', 'np.where', (['(table[self.config.band_field][wcs_inds] == band)'], {}), '(table[self.config.band_field][wcs_inds] == band)\n', (3000, 3049), True, 'import numpy as np\n'), ((3740, 3751), 'time.time', 'time.time', ([], {}), '()\n', (3749, 3751), False, 'import time\n'), ((5602, 5613), 'time.time', 'time.time', ([], {}), '()\n', (5611, 5613), False, 'import time\n'), ((4470, 4491), 'os.path.isfile', 'os.path.isfile', (['fname'], {}), '(fname)\n', (4484, 4491), False, 'import os\n'), ((5777, 5842), 'os.path.join', 'os.path.join', (['self.outputpath', "('%d_?????' % self.config.nside_run)"], {}), "(self.outputpath, '%d_?????' % self.config.nside_run)\n", (5789, 5842), False, 'import os\n'), ((5960, 5973), 'os.listdir', 'os.listdir', (['d'], {}), '(d)\n', (5970, 5973), False, 'import os\n'), ((6046, 6057), 'os.rmdir', 'os.rmdir', (['d'], {}), '(d)\n', (6054, 6057), False, 'import os\n'), ((4899, 4984), 'os.path.join', 'os.path.join', (['self.outputpath', "('%d_?????' % self.config.nside_run)", 'fname_template'], {}), "(self.outputpath, '%d_?????' % self.config.nside_run,\n fname_template)\n", (4911, 4984), False, 'import os\n')] |
import unittest
from polyhedral_analysis.orientation_parameters import cos_theta
import numpy as np
import math
class OrientationParametersTestCase( unittest.TestCase ):
def test_cos_theta_one( self ):
a = np.array( [ 0.0, 0.0, 1.0 ] )
b = np.array( [ 1.0, 0.0, 0.0 ] )
self.assertEqual( cos_theta( a, b ), 0.0 )
def test_cos_theta_two( self ):
a = np.array( [ 0.0, 0.0, 1.0 ] )
b = np.array( [ 0.0, 0.0, 1.0 ] )
self.assertEqual( cos_theta( a, b ), 1.0 )
def test_cos_theta_three( self ):
a = np.array( [ 0.0, 0.0, 1.0 ] )
b = np.array( [ 0.0, 1.0, 1.0 ] )
self.assertTrue( cos_theta( a, b ) - math.sqrt(2)/2.0 < 1e-10 )
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"numpy.array",
"math.sqrt",
"polyhedral_analysis.orientation_parameters.cos_theta"
] | [((742, 757), 'unittest.main', 'unittest.main', ([], {}), '()\n', (755, 757), False, 'import unittest\n'), ((220, 245), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (228, 245), True, 'import numpy as np\n'), ((262, 287), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (270, 287), True, 'import numpy as np\n'), ((392, 417), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (400, 417), True, 'import numpy as np\n'), ((434, 459), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (442, 459), True, 'import numpy as np\n'), ((566, 591), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (574, 591), True, 'import numpy as np\n'), ((608, 633), 'numpy.array', 'np.array', (['[0.0, 1.0, 1.0]'], {}), '([0.0, 1.0, 1.0])\n', (616, 633), True, 'import numpy as np\n'), ((318, 333), 'polyhedral_analysis.orientation_parameters.cos_theta', 'cos_theta', (['a', 'b'], {}), '(a, b)\n', (327, 333), False, 'from polyhedral_analysis.orientation_parameters import cos_theta\n'), ((490, 505), 'polyhedral_analysis.orientation_parameters.cos_theta', 'cos_theta', (['a', 'b'], {}), '(a, b)\n', (499, 505), False, 'from polyhedral_analysis.orientation_parameters import cos_theta\n'), ((663, 678), 'polyhedral_analysis.orientation_parameters.cos_theta', 'cos_theta', (['a', 'b'], {}), '(a, b)\n', (672, 678), False, 'from polyhedral_analysis.orientation_parameters import cos_theta\n'), ((683, 695), 'math.sqrt', 'math.sqrt', (['(2)'], {}), '(2)\n', (692, 695), False, 'import math\n')] |
import os
import torch
import numpy as np
import cv2
from pycocotools.coco import COCO
from .base import BaseDataset
class CocoDataset(BaseDataset):
def get_data_info(self, ann_path):
"""
Load basic information of dataset such as image path, label and so on.
:param ann_path: coco json file path
:return: image info:
[{'license': 2,
'file_name': '000000000139.jpg',
'coco_url': 'http://images.cocodataset.org/val2017/000000000139.jpg',
'height': 426,
'width': 640,
'date_captured': '2013-11-21 01:34:01',
'flickr_url': 'http://farm9.staticflickr.com/8035/8024364858_9c41dc1666_z.jpg',
'id': 139},
...
]
"""
self.coco_api = COCO(ann_path)
self.cat_ids = sorted(self.coco_api.getCatIds())
self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)}
self.cats = self.coco_api.loadCats(self.cat_ids)
self.img_ids = sorted(self.coco_api.imgs.keys())
img_info = self.coco_api.loadImgs(self.img_ids)
return img_info
def get_per_img_info(self, idx):
img_info = self.data_info[idx]
file_name = img_info['file_name']
height = img_info['height']
width = img_info['width']
id = img_info['id']
if not isinstance(id, int):
raise TypeError('Image id must be int.')
info = {'file_name': file_name,
'height': height,
'width': width,
'id': id}
return info
def get_img_annotation(self, idx):
"""
load per image annotation
:param idx: index in dataloader
:return: annotation dict
"""
img_id = self.img_ids[idx]
ann_ids = self.coco_api.getAnnIds([img_id])
anns = self.coco_api.loadAnns(ann_ids)
gt_bboxes = []
gt_labels = []
gt_bboxes_ignore = []
if self.use_instance_mask:
gt_masks = []
if self.use_keypoint:
gt_keypoints = []
for ann in anns:
if ann.get('ignore', False):
continue
x1, y1, w, h = ann['bbox']
if ann['area'] <= 0 or w < 1 or h < 1:
continue
if ann['category_id'] not in self.cat_ids:
continue
bbox = [x1, y1, x1 + w, y1 + h]
if ann['iscrowd']:
gt_bboxes_ignore.append(bbox)
else:
gt_bboxes.append(bbox)
gt_labels.append(self.cat2label[ann['category_id']])
if self.use_instance_mask:
gt_masks.append(self.coco_api.annToMask(ann))
if self.use_keypoint:
gt_keypoints.append(ann['keypoints'])
if gt_bboxes:
gt_bboxes = np.array(gt_bboxes, dtype=np.float32)
gt_labels = np.array(gt_labels, dtype=np.int64)
else:
gt_bboxes = np.zeros((0, 4), dtype=np.float32)
gt_labels = np.array([], dtype=np.int64)
if gt_bboxes_ignore:
gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)
else:
gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)
annotation = dict(
bboxes=gt_bboxes, labels=gt_labels, bboxes_ignore=gt_bboxes_ignore)
if self.use_instance_mask:
annotation['masks'] = gt_masks
if self.use_keypoint:
if gt_keypoints:
annotation['keypoints'] = np.array(gt_keypoints, dtype=np.float32)
else:
annotation['keypoints'] = np.zeros((0, 51), dtype=np.float32)
return annotation
def get_train_data(self, idx):
"""
Load image and annotation
:param idx:
:return: meta-data (a dict containing image, annotation and other information)
"""
img_info = self.get_per_img_info(idx)
file_name = img_info['file_name']
image_path = os.path.join(self.img_path, file_name)
img = cv2.imread(image_path)
if img is None:
print('image {} read failed.'.format(image_path))
raise FileNotFoundError('Cant load image! Please check image path!')
ann = self.get_img_annotation(idx)
#apply mosaic
meta = dict(img=img,
img_info=img_info,
gt_bboxes=ann['bboxes'],
gt_labels=ann['labels'])
if self.use_instance_mask:
meta['gt_masks'] = ann['masks']
if self.use_keypoint:
meta['gt_keypoints'] = ann['keypoints']
meta = self.pipeline(meta, self.input_size)
meta['img'] = torch.from_numpy(meta['img'].transpose(2, 0, 1))
return meta
def get_val_data(self, idx):
"""
Currently no difference from get_train_data.
Not support TTA(testing time augmentation) yet.
:param idx:
:return:
"""
# TODO: support TTA
return self.get_train_data(idx)
| [
"numpy.zeros",
"cv2.imread",
"pycocotools.coco.COCO",
"numpy.array",
"os.path.join"
] | [((773, 787), 'pycocotools.coco.COCO', 'COCO', (['ann_path'], {}), '(ann_path)\n', (777, 787), False, 'from pycocotools.coco import COCO\n'), ((4029, 4067), 'os.path.join', 'os.path.join', (['self.img_path', 'file_name'], {}), '(self.img_path, file_name)\n', (4041, 4067), False, 'import os\n'), ((4082, 4104), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (4092, 4104), False, 'import cv2\n'), ((2861, 2898), 'numpy.array', 'np.array', (['gt_bboxes'], {'dtype': 'np.float32'}), '(gt_bboxes, dtype=np.float32)\n', (2869, 2898), True, 'import numpy as np\n'), ((2923, 2958), 'numpy.array', 'np.array', (['gt_labels'], {'dtype': 'np.int64'}), '(gt_labels, dtype=np.int64)\n', (2931, 2958), True, 'import numpy as np\n'), ((2997, 3031), 'numpy.zeros', 'np.zeros', (['(0, 4)'], {'dtype': 'np.float32'}), '((0, 4), dtype=np.float32)\n', (3005, 3031), True, 'import numpy as np\n'), ((3056, 3084), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.int64'}), '([], dtype=np.int64)\n', (3064, 3084), True, 'import numpy as np\n'), ((3145, 3189), 'numpy.array', 'np.array', (['gt_bboxes_ignore'], {'dtype': 'np.float32'}), '(gt_bboxes_ignore, dtype=np.float32)\n', (3153, 3189), True, 'import numpy as np\n'), ((3235, 3269), 'numpy.zeros', 'np.zeros', (['(0, 4)'], {'dtype': 'np.float32'}), '((0, 4), dtype=np.float32)\n', (3243, 3269), True, 'import numpy as np\n'), ((3556, 3596), 'numpy.array', 'np.array', (['gt_keypoints'], {'dtype': 'np.float32'}), '(gt_keypoints, dtype=np.float32)\n', (3564, 3596), True, 'import numpy as np\n'), ((3657, 3692), 'numpy.zeros', 'np.zeros', (['(0, 51)'], {'dtype': 'np.float32'}), '((0, 51), dtype=np.float32)\n', (3665, 3692), True, 'import numpy as np\n')] |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-*- coding: utf-8 -*-
import os
import gym
import numpy as np
import parl
from parl.utils import logger # 日志打印工具
from model import Model
from algorithm import DQN # from parl.algorithms import DQN # parl >= 1.3.1
from agent import Agent
from replay_memory import ReplayMemory
LEARN_FREQ = 5 # 训练频率,不需要每一个step都learn,攒一些新增经验后再learn,提高效率
MEMORY_SIZE = 20000 # replay memory的大小,越大越占用内存
MEMORY_WARMUP_SIZE = 200 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn
BATCH_SIZE = 32 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来
LEARNING_RATE = 0.001 # 学习率
GAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等
# 训练一个episode
def run_episode(env, agent, rpm):
total_reward = 0
obs = env.reset()
step = 0
while True:
step += 1
action = agent.sample(obs) # 采样动作,所有动作都有概率被尝试到
next_obs, reward, done, _ = env.step(action)
rpm.append((obs, action, reward, next_obs, done))
# train model
if (len(rpm) > MEMORY_WARMUP_SIZE) and (step % LEARN_FREQ == 0):
(batch_obs, batch_action, batch_reward, batch_next_obs,
batch_done) = rpm.sample(BATCH_SIZE)
train_loss = agent.learn(batch_obs, batch_action, batch_reward,
batch_next_obs,
batch_done) # s,a,r,s',done
total_reward += reward
obs = next_obs
if done:
break
return total_reward
# 评估 agent, 跑 5 个episode,总reward求平均
def evaluate(env, agent, render=False):
eval_reward = []
for i in range(5):
obs = env.reset()
episode_reward = 0
while True:
action = agent.predict(obs) # 预测动作,只选最优动作
obs, reward, done, _ = env.step(action)
episode_reward += reward
if render:
env.render()
if done:
break
eval_reward.append(episode_reward)
return np.mean(eval_reward)
def main():
env = gym.make(
'CartPole-v0'
) # CartPole-v0: expected reward > 180 MountainCar-v0 : expected reward > -120
action_dim = env.action_space.n # CartPole-v0: 2
obs_shape = env.observation_space.shape # CartPole-v0: (4,)
rpm = ReplayMemory(MEMORY_SIZE) # DQN的经验回放池
# 根据parl框架构建agent
model = Model(act_dim=action_dim)
algorithm = DQN(model, act_dim=action_dim, gamma=GAMMA, lr=LEARNING_RATE)
agent = Agent(
algorithm,
obs_dim=obs_shape[0],
act_dim=action_dim,
e_greed=0.1, # 有一定概率随机选取动作,探索
e_greed_decrement=1e-6) # 随着训练逐步收敛,探索的程度慢慢降低
# 加载模型
# save_path = './dqn_model.ckpt'
# agent.restore(save_path)
# 先往经验池里存一些数据,避免最开始训练的时候样本丰富度不够
while len(rpm) < MEMORY_WARMUP_SIZE:
run_episode(env, agent, rpm)
max_episode = 2000
# start train
episode = 0
while episode < max_episode: # 训练max_episode个回合,test部分不计算入episode数量
# train part
for i in range(0, 50):
total_reward = run_episode(env, agent, rpm)
episode += 1
# test part
eval_reward = evaluate(env, agent, render=True) # render=True 查看显示效果
logger.info('episode:{} e_greed:{} Test reward:{}'.format(
episode, agent.e_greed, eval_reward))
# 训练结束,保存模型
save_path = './dqn_model.ckpt'
agent.save(save_path)
if __name__ == '__main__':
main()
| [
"replay_memory.ReplayMemory",
"gym.make",
"model.Model",
"numpy.mean",
"algorithm.DQN",
"agent.Agent"
] | [((2556, 2576), 'numpy.mean', 'np.mean', (['eval_reward'], {}), '(eval_reward)\n', (2563, 2576), True, 'import numpy as np\n'), ((2601, 2624), 'gym.make', 'gym.make', (['"""CartPole-v0"""'], {}), "('CartPole-v0')\n", (2609, 2624), False, 'import gym\n'), ((2862, 2887), 'replay_memory.ReplayMemory', 'ReplayMemory', (['MEMORY_SIZE'], {}), '(MEMORY_SIZE)\n', (2874, 2887), False, 'from replay_memory import ReplayMemory\n'), ((2936, 2961), 'model.Model', 'Model', ([], {'act_dim': 'action_dim'}), '(act_dim=action_dim)\n', (2941, 2961), False, 'from model import Model\n'), ((2978, 3039), 'algorithm.DQN', 'DQN', (['model'], {'act_dim': 'action_dim', 'gamma': 'GAMMA', 'lr': 'LEARNING_RATE'}), '(model, act_dim=action_dim, gamma=GAMMA, lr=LEARNING_RATE)\n', (2981, 3039), False, 'from algorithm import DQN\n'), ((3052, 3152), 'agent.Agent', 'Agent', (['algorithm'], {'obs_dim': 'obs_shape[0]', 'act_dim': 'action_dim', 'e_greed': '(0.1)', 'e_greed_decrement': '(1e-06)'}), '(algorithm, obs_dim=obs_shape[0], act_dim=action_dim, e_greed=0.1,\n e_greed_decrement=1e-06)\n', (3057, 3152), False, 'from agent import Agent\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2020-03-27 at 13:42
@author: cook
"""
from astropy.io import fits
from astropy.table import Table
from astropy import units as uu
import numpy as np
import warnings
import sys
import os
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.optimize import curve_fit
from scipy.stats import chisquare
import matplotlib.pyplot as plt
from scipy.signal import convolve
import glob
from fits2wave import *
MASK_COLS = ['ll_mask_s', 'll_mask_e', 'w_mask']
# variables
# These values are taken from the constants file
MASK_WIDTH = 1.7 # CCF_MASK_WIDTH
# MASK_MIN_WEIGHT = 0.0 # CCF_MASK_MIN_WEIGHT
# should be smaller than ~0.25
CCF_STEP = 0.1 # CCF_DEFAULT_STEP (or user input)
CCF_WIDTH = 50 # CCF_DEFAULT_WIDTH (or user input)
CCF_RV_NULL = 1000 # CCF_OBJRV_NULL_VAL (max allowed)
IN_RV = -110 # user input [km/s]
CCF_N_ORD_MAX = 48 # CCF_N_ORD_MAX
BLAZE_NORM_PERCENTILE = 95 # CCF_BLAZE_NORM_PERCENTILE
BLAZE_THRESHOLD = 0.3 # WAVE_FP_BLAZE_THRES
IMAGE_PIXEL_SIZE = 2.28 # IMAGE_PIXEL_SIZE
NOISE_SIGDET = 8.0 # CCF_NOISE_SIGDET
NOISE_SIZE = 12 # CCF_NOISE_BOXSIZE
NOISE_THRES = 1.0e9 # CCF_NOISE_THRES
SPEED_OF_LIGHT = 299792.458 # [km/s]
# =============================================================================
# Define functions
# =============================================================================
def read_mask(MASK_FILE, MASK_COLS):
table = Table.read(MASK_FILE, format='ascii')
# get column names
oldcols = list(table.colnames)
# rename columns
for c_it, col in enumerate(MASK_COLS):
table[oldcols[c_it]].name = col
# return table
return table
def get_mask(table, mask_width, mask_units='nm'):
ll_mask_e = np.array(table['ll_mask_e']).astype(float)
ll_mask_s = np.array(table['ll_mask_s']).astype(float)
ll_mask_d = ll_mask_e - ll_mask_s
ll_mask_ctr = ll_mask_s + ll_mask_d * 0.5
# if mask_width > 0 ll_mask_d is multiplied by mask_width/c
# if mask_width > 0:
# ll_mask_d = mask_width * ll_mask_s / SPEED_OF_LIGHT
# make w_mask an array
w_mask = np.array(table['w_mask']).astype(float)
# use w_min to select on w_mask or keep all if w_mask_min >= 1
# if mask_min < 1.0:
# mask = w_mask > mask_min
# ll_mask_d = ll_mask_d[mask]
# ll_mask_ctr = ll_mask_ctr[mask]
# w_mask = w_mask[mask]
# else set all w_mask to one (and use all lines in file)
# else:
# w_mask = np.ones(len(ll_mask_d))
# ----------------------------------------------------------------------
# deal with the units of ll_mask_d and ll_mask_ctr
# must be returned in nanometers
# ----------------------------------------------------------------------
# get unit object from mask units string
unit = getattr(uu, mask_units)
# add units
ll_mask_d = ll_mask_d * unit
ll_mask_ctr = ll_mask_ctr * unit
# convert to nanometers
ll_mask_d = ll_mask_d.to(uu.nm).value
ll_mask_ctr = ll_mask_ctr.to(uu.nm).value
# ----------------------------------------------------------------------
# return the size of each pixel, the central point of each pixel
# and the weight mask
return ll_mask_d, ll_mask_ctr, w_mask
def relativistic_waveshift(dv, units='km/s'):
"""
Relativistic offset in wavelength
default is dv in km/s
:param dv: float or numpy array, the dv values
:param units: string or astropy units, the units of dv
:return:
"""
# get c in correct units
# noinspection PyUnresolvedReferences
if units == 'km/s' or units == uu.km / uu.s:
c = SPEED_OF_LIGHT
# noinspection PyUnresolvedReferences
elif units == 'm/s' or units == uu.m / uu.s:
c = SPEED_OF_LIGHT * 1000
else:
raise ValueError("Wrong units for dv ({0})".format(units))
# work out correction
corrv = np.sqrt((1 + dv / c) / (1 - dv / c))
# return correction
return corrv
def iuv_spline(x, y, **kwargs):
# check whether weights are set
w = kwargs.get('w', None)
# copy x and y
x, y = np.array(x), np.array(y)
# find all NaN values
nanmask = ~np.isfinite(y)
if np.sum(~nanmask) < 2:
y = np.zeros_like(x)
elif np.sum(nanmask) == 0:
pass
else:
# replace all NaN's with linear interpolation
badspline = InterpolatedUnivariateSpline(x[~nanmask], y[~nanmask],
k=1, ext=1)
y[nanmask] = badspline(x[nanmask])
# return spline
return InterpolatedUnivariateSpline(x, y, **kwargs)
def fit_ccf(rv, ccf, fit_type):
"""
Fit the CCF to a guassian function
:param rv: numpy array (1D), the radial velocities for the line
:param ccf: numpy array (1D), the CCF values for the line
:param fit_type: int, if "0" then we have an absorption line
if "1" then we have an emission line
:return result: numpy array (1D), the fit parameters in the
following order:
[amplitude, center, fwhm, offset from 0 (in y-direction)]
:return ccf_fit: numpy array (1D), the fit values, i.e. the gaussian values
for the fit parameters in "result"
"""
# deal with inconsistent lengths
if len(rv) != len(ccf):
print('\tERROR: RV AND CCF SHAPE DO NOT MATCH')
sys.exit()
# deal with all nans
if np.sum(np.isnan(ccf)) == len(ccf):
# log warning about all NaN ccf
print('\tWARNING: NANS in CCF')
# return NaNs
result = np.zeros(4) * np.nan
ccf_fit = np.zeros_like(ccf) * np.nan
return result, ccf_fit
# get constants
max_ccf, min_ccf = np.nanmax(ccf), np.nanmin(ccf)
argmin, argmax = np.nanargmin(ccf), np.nanargmax(ccf)
diff = max_ccf - min_ccf
rvdiff = rv[1] - rv[0]
# set up guess for gaussian fit
# if fit_type == 0 then we have absorption lines
if fit_type == 0:
if np.nanmax(ccf) != 0:
a = np.array([-diff / max_ccf, rv[argmin], 4 * rvdiff, 0])
else:
a = np.zeros(4)
# else (fit_type == 1) then we have emission lines
else:
a = np.array([diff / max_ccf, rv[argmax], 4 * rvdiff, 1])
# normalise y
y = ccf / max_ccf - 1 + fit_type
# x is just the RVs
x = rv
# uniform weights
w = np.ones(len(ccf))
# get gaussian fit
nanmask = np.isfinite(y)
y[~nanmask] = 0.0
# fit the gaussian
try:
with warnings.catch_warnings(record=True) as _:
result, fit = fitgaussian(x, y, weights=w, guess=a)
except RuntimeError:
result = np.repeat(np.nan, 4)
fit = np.repeat(np.nan, len(x))
# scale the ccf
ccf_fit = (fit + 1 - fit_type) * max_ccf
# return the best guess and the gaussian fit
return result, ccf_fit
def gauss_function(x, a, x0, sigma, dc):
"""
A standard 1D gaussian function (for fitting against)]=
:param x: numpy array (1D), the x data points
:param a: float, the amplitude
:param x0: float, the mean of the gaussian
:param sigma: float, the standard deviation (FWHM) of the gaussian
:param dc: float, the constant level below the gaussian
:return gauss: numpy array (1D), size = len(x), the output gaussian
"""
return a * np.exp(-0.5 * ((x - x0) / sigma) ** 2) + dc
def fitgaussian(x, y, weights=None, guess=None, return_fit=True,
return_uncertainties=False):
"""
Fit a single gaussian to the data "y" at positions "x", points can be
weighted by "weights" and an initial guess for the gaussian parameters
:param x: numpy array (1D), the x values for the gaussian
:param y: numpy array (1D), the y values for the gaussian
:param weights: numpy array (1D), the weights for each y value
:param guess: list of floats, the initial guess for the guassian fit
parameters in the following order:
[amplitude, center, fwhm, offset from 0 (in y-direction)]
:param return_fit: bool, if True also calculates the fit values for x
i.e. yfit = gauss_function(x, *pfit)
:param return_uncertainties: bool, if True also calculates the uncertainties
based on the covariance matrix (pcov)
uncertainties = np.sqrt(np.diag(pcov))
:return pfit: numpy array (1D), the fit parameters in the
following order:
[amplitude, center, fwhm, offset from 0 (in y-direction)]
:return yfit: numpy array (1D), the fit y values, i.e. the gaussian values
for the fit parameters, only returned if return_fit = True
"""
# if we don't have weights set them to be all equally weighted
if weights is None:
weights = np.ones(len(x))
weights = 1.0 / weights
# if we aren't provided a guess, make one
if guess is None:
guess = [np.nanmax(y), np.nanmean(y), np.nanstd(y), 0]
# calculate the fit using curve_fit to the function "gauss_function"
with warnings.catch_warnings(record=True) as _:
pfit, pcov = curve_fit(gauss_function, x, y, p0=guess, sigma=weights,
absolute_sigma=True)
if return_fit and return_uncertainties:
# calculate the fit parameters
yfit = gauss_function(x, *pfit)
# work out the normalisation constant
chis, _ = chisquare(y, f_exp=yfit)
norm = chis / (len(y) - len(guess))
# calculate the fit uncertainties based on pcov
efit = np.sqrt(np.diag(pcov)) * np.sqrt(norm)
# return pfit, yfit and efit
return pfit, yfit, efit
# if just return fit
elif return_fit:
# calculate the fit parameters
yfit = gauss_function(x, *pfit)
# return pfit and yfit
return pfit, yfit
# if return uncertainties
elif return_uncertainties:
# calculate the fit parameters
yfit = gauss_function(x, *pfit)
# work out the normalisation constant
chis, _ = chisquare(y, f_exp=yfit)
norm = chis / (len(y) - len(guess))
# calculate the fit uncertainties based on pcov
efit = np.sqrt(np.diag(pcov)) * np.sqrt(norm)
# return pfit and efit
return pfit, efit
# else just return the pfit
else:
# return pfit
return pfit
def delta_v_rms_2d(spe, wave, sigdet, threshold, size):
"""
Compute the photon noise uncertainty for all orders (for the 2D image)
:param spe: numpy array (2D), the extracted spectrum
size = (number of orders by number of columns (x-axis))
:param wave: numpy array (2D), the wave solution for each pixel
:param sigdet: float, the read noise (sigdet) for calculating the
noise array
:param threshold: float, upper limit for pixel values, above this limit
pixels are regarded as saturated
:param size: int, size (in pixels) around saturated pixels to also regard
as bad pixels
:return dvrms2: numpy array (1D), the photon noise for each pixel (squared)
:return weightedmean: float, weighted mean photon noise across all orders
"""
# flag (saturated) fluxes above threshold as "bad pixels"
with warnings.catch_warnings(record=True) as _:
flag = spe < threshold
# flag all fluxes around "bad pixels" (inside +/- size of the bad pixel)
for i_it in range(1, 2 * size, 1):
flag[:, size:-size] *= flag[:, i_it: i_it - 2 * size]
# get the wavelength normalised to the wavelength spacing
nwave = wave[:, 1:-1] / (wave[:, 2:] - wave[:, :-2])
# get the flux + noise array
sxn = (spe[:, 1:-1] + sigdet ** 2)
# get the flux difference normalised to the flux + noise
nspe = (spe[:, 2:] - spe[:, :-2]) / sxn
# get the mask value
maskv = flag[:, 2:] * flag[:, 1:-1] * flag[:, :-2]
# get the total
tot = np.nansum(sxn * ((nwave * nspe) ** 2) * maskv, axis=1)
# convert to dvrms2
with warnings.catch_warnings(record=True) as _:
dvrms2 = ((SPEED_OF_LIGHT * 1000) ** 2) / abs(tot)
# weighted mean of dvrms2 values
weightedmean = 1. / np.sqrt(np.nansum(1.0 / dvrms2))
# return dv rms and weighted mean
return dvrms2, weightedmean
def fwhm(sigma=1.0):
"""
Get the Full-width-half-maximum value from the sigma value (~2.3548)
:param sigma: float, the sigma, default value is 1.0 (normalised gaussian)
:return: 2 * sqrt(2 * log(2)) * sigma = 2.3548200450309493 * sigma
"""
return 2 * np.sqrt(2 * np.log(2)) * sigma
def ccf_calculation(wave, image, blaze, targetrv, mask_centers, mask_weights,
berv, fit_type, kernel=None):
# get rvmin and rvmax
rvmin = targetrv - CCF_WIDTH
rvmax = targetrv + CCF_WIDTH + CCF_STEP
# get the dimensions
nbo, nbpix = image.shape
# create a rv ccf range
rv_ccf = np.arange(rvmin, rvmax, CCF_STEP)
# storage of the ccf
ccf_all = []
ccf_noise_all = []
ccf_all_fit = []
ccf_all_results = []
ccf_lines = []
ccf_all_snr = []
ccf_norm_all = []
# if we have defined 'kernel', it must be a list
# with the first element being the type of convolution
# and subsequent arguments being parameters. For now,
# we have :
#
# --> boxcar convolution
# ['boxcar', width]
#
# kernel = [1, 1, ...., 1, 1]
#
# --> gaussian convolution
#
# ['gaussian', e-width]
# kernel = exp( -0.5*(x/ew)**2 )
#
# --> super gaussian
#
# ['supergaussian', e-width, beta]
#
# kernel = exp( -0.5*(x/ew)**beta )
#
# Other functions could be added below
#
if isinstance(kernel, list):
if kernel[0] == 'boxcar':
# ones with a length of kernel[1]
ker = np.ones(int(np.round(kernel[1] / CCF_STEP)))
elif kernel[0] == 'gaussian':
# width of the gaussian expressed in
# steps of CCF
ew = kernel[1] / CCF_STEP
index = np.arange(-4 * np.ceil(ew), 4 * np.ceil(ew) + 1)
ker = np.exp(-0.5 * (index / ew) ** 2)
elif kernel[0] == 'supergaussian':
# width of the gaussian expressed in
# steps of CCF. Exponents should be
# between 0.1 and 10.. Values above
# 10 are (nearly) the same as a boxcar.
if (kernel[1] < 0.1) or (kernel[1] > 10):
raise ValueError('CCF ERROR: kernel[1] is out of range.')
ew = kernel[1] / CCF_STEP
index = np.arange(-4 * np.ceil(ew), 4 * np.ceil(ew) + 1)
ker = np.exp(-0.5 * np.abs(index / ew) ** kernel[2])
else:
# kernel name is not known - generate error
raise ValueError('CCF ERROR: name of kernel not accepted!')
ker = ker / np.sum(ker)
if len(ker) > (len(rv_ccf) - 1):
# TODO : give a proper error
err_msg = """
The size of your convolution kernel is too big for your
CCF size. Please either increase the CCF_WIDTH value or
decrease the width of your convolution kernel. In boxcar,
this implies a length bigger than CCF_WIDTH/CCF_STEP, in
gaussian and supergaussian, this means that
CCF_WIDTH/CCF_STEP is >8*ew. The kernel has to run from
-4 sigma to +4 sigma.
"""
raise ValueError('CCF ERROR: {0}'.format(err_msg))
# ----------------------------------------------------------------------
# loop around the orders
for order_num in range(nbo):
# log the process
print('Order {0}'.format(order_num))
# ------------------------------------------------------------------
# get this orders values
wa_ord = np.array(wave[order_num])
sp_ord = np.array(image[order_num])
bl_ord = np.array(blaze[order_num])
# COMMENT EA, normalization moved before the masking
#
# normalize per-ord blaze to its peak value
# this gets rid of the calibration lamp SED
bl_ord /= np.nanpercentile(bl_ord, BLAZE_NORM_PERCENTILE)
# COMMENT EA, changing NaNs to 0 in the blaze
bl_ord[np.isfinite(bl_ord) == 0] = 0
# mask on the blaze
with warnings.catch_warnings(record=True) as _:
blazemask = bl_ord > BLAZE_THRESHOLD
# get order mask centers and mask weights
min_ord_wav = np.nanmin(wa_ord[blazemask])
max_ord_wav = np.nanmax(wa_ord[blazemask])
# COMMENT EA there's a problem with the sign in the min/max
# print(order_num, min_ord_wav, max_ord_wav, min_ord_wav * (1 - rvmin / SPEED_OF_LIGHT), max_ord_wav * (1 - rvmax / SPEED_OF_LIGHT), rvmin, rvmax)
# min_ord_wav = min_ord_wav * (1 - rvmin / SPEED_OF_LIGHT)
# max_ord_wav = max_ord_wav * (1 - rvmax / SPEED_OF_LIGHT)
# mask the ccf mask by the order length
mask_wave_mask = (mask_centers > min_ord_wav)
mask_wave_mask &= (mask_centers < max_ord_wav)
omask_centers = mask_centers[mask_wave_mask]
omask_weights = mask_weights[mask_wave_mask]
# ------------------------------------------------------------------
# find any places in spectrum or blaze where pixel is NaN
nanmask = np.isnan(sp_ord) | np.isnan(bl_ord)
# ------------------------------------------------------------------
# deal with no valid lines
if np.sum(mask_wave_mask) == 0:
print('\tWARNING: MASK INVALID FOR WAVELENGTH RANGE --> NAN')
# set all values to NaN
ccf_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_fit.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_results.append(np.repeat(np.nan, 4))
ccf_noise_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_lines.append(0)
ccf_all_snr.append(np.nan)
ccf_norm_all.append(np.nan)
continue
# ------------------------------------------------------------------
# deal with all nan
if np.sum(nanmask) == nbpix:
print('\tWARNING: ALL SP OR BLZ NAN --> NAN')
# set all values to NaN
ccf_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_fit.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_results.append(np.repeat(np.nan, 4))
ccf_noise_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_lines.append(0)
ccf_all_snr.append(np.nan)
ccf_norm_all.append(np.nan)
continue
# ------------------------------------------------------------------
# set the spectrum or blaze NaN pixels to zero (dealt with by divide)
sp_ord[nanmask] = 0
bl_ord[nanmask] = 0
# now every value that is zero is masked (we don't want to spline these)
good = (sp_ord != 0) & (bl_ord != 0)
# ------------------------------------------------------------------
# spline the spectrum and the blaze
spline_sp = iuv_spline(wa_ord[good], sp_ord[good], k=5, ext=1)
spline_bl = iuv_spline(wa_ord[good], bl_ord[good], k=5, ext=1)
# ------------------------------------------------------------------
# set up the ccf for this order
ccf_ord = np.zeros_like(rv_ccf)
# ------------------------------------------------------------------
# get the wavelength shift (dv) in relativistic way
wave_shifts = relativistic_waveshift(rv_ccf - berv)
# ------------------------------------------------------------------
# if order_num == 35:
# print()
# stop
wave_tmp_start = omask_centers * wave_shifts[0]
wave_tmp_end = omask_centers * wave_shifts[-1]
valid_lines_start = spline_bl(wave_tmp_start) != 0
valid_lines_end = spline_bl(wave_tmp_end) != 0
keep = valid_lines_start * valid_lines_end
omask_centers = omask_centers[keep]
omask_weights = omask_weights[keep]
# set number of valid lines used to zero
numlines = 0
# loop around the rvs and calculate the CCF at this point
part3 = spline_bl(omask_centers)
# if order_num == 42:
# print(order_num, min_ord_wav, max_ord_wav)
#
# plt.plot(wa_ord, sp_ord/np.nanmedian(sp_ord))
# plt.plot(wa_ord, bl_ord/np.nanmedian(bl_ord))
# plt.plot(omask_centers, part3/np.nanmedian(part3),'go')
# plt.show()
# we added the mask weights
omask_weights /= np.nanmean(omask_weights)
for rv_element in range(len(rv_ccf)):
wave_tmp = omask_centers * wave_shifts[rv_element]
part1 = spline_sp(wave_tmp)
part2 = spline_bl(wave_tmp)
valid_lines = spline_bl(wave_tmp) != 0
numlines = np.sum(valid_lines)
# if order_num ==42:
# print(numlines,len(valid_lines), rv_element)
# CCF is the division of the sums
with warnings.catch_warnings(record=True) as _:
ccf_element = ((part1 * part3) / part2)
ccf_ord[rv_element] = np.nansum(ccf_element[valid_lines] * omask_weights[
valid_lines]) # /np.nansum(omask_weights[valid_lines]*part3[valid_lines])
# ------------------------------------------------------------------
# deal with NaNs in ccf
if np.sum(np.isnan(ccf_ord)) > 0:
# log all NaN
print('WARNING: CCF is NAN')
# set all values to NaN
ccf_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_fit.append(np.repeat(np.nan, len(rv_ccf)))
ccf_all_results.append(np.repeat(np.nan, 4))
ccf_noise_all.append(np.repeat(np.nan, len(rv_ccf)))
ccf_lines.append(0)
ccf_all_snr.append(np.nan)
ccf_norm_all.append(np.nan)
continue
# ------------------------------------------------------------------
# Convolve by the appropriate CCF kernel, if any
if type(kernel) == list:
weight = np.convolve(np.ones(len(ccf_ord)), ker, mode='same')
ccf_ord = np.convolve(ccf_ord, ker, mode='same') / weight
# ------------------------------------------------------------------
# normalise each orders CCF to median
ccf_norm = np.nanmedian(ccf_ord)
# ccf_ord = ccf_ord / ccf_norm
# ------------------------------------------------------------------
# fit the CCF with a gaussian
fargs = [rv_ccf, ccf_ord, fit_type]
ccf_coeffs_ord, ccf_fit_ord = fit_ccf(*fargs)
# ------------------------------------------------------------------
# calculate the residuals of the ccf fit
res = ccf_ord - ccf_fit_ord
# calculate the CCF noise per order
ccf_noise = np.array(res)
# calculate the snr for this order
ccf_snr = np.abs(ccf_coeffs_ord[0] / np.nanmedian(np.abs(ccf_noise)))
# ------------------------------------------------------------------
# append ccf to storage
ccf_all.append(ccf_ord)
ccf_all_fit.append(ccf_fit_ord)
ccf_all_results.append(ccf_coeffs_ord)
ccf_noise_all.append(ccf_noise)
ccf_lines.append(numlines)
ccf_all_snr.append(ccf_snr)
ccf_norm_all.append(ccf_norm)
# store outputs in param dict
props = dict()
props['RV_CCF'] = rv_ccf
props['CCF'] = np.array(ccf_all)
props['CCF_LINES'] = np.array(ccf_lines)
props['TOT_LINE'] = np.sum(ccf_lines)
props['CCF_NOISE'] = np.array(ccf_noise_all)
props['CCF_SNR'] = np.array(ccf_all_snr)
props['CCF_FIT'] = np.array(ccf_all_fit)
props['CCF_FIT_COEFFS'] = np.array(ccf_all_results)
props['CCF_NORM'] = np.array(ccf_norm_all)
# Return properties
return props
def mean_ccf(props, targetrv, fit_type, ):
# get the average ccf
mean_ccf = np.nanmean(props['CCF'][: CCF_N_ORD_MAX], axis=0)
# get the fit for the normalized average ccf
mean_ccf_coeffs, mean_ccf_fit = fit_ccf(props['RV_CCF'],
mean_ccf, fit_type=fit_type)
# get the RV value from the normalised average ccf fit center location
ccf_rv = float(mean_ccf_coeffs[1])
# get the contrast (ccf fit amplitude)
ccf_contrast = np.abs(100 * mean_ccf_coeffs[0])
# get the FWHM value
ccf_fwhm = mean_ccf_coeffs[2] * fwhm()
# --------------------------------------------------------------------------
# CCF_NOISE uncertainty
ccf_noise_tot = np.sqrt(np.nanmean(props['CCF_NOISE'] ** 2, axis=0))
# Calculate the slope of the CCF
average_ccf_diff = (mean_ccf[2:] - mean_ccf[:-2])
rv_ccf_diff = (props['RV_CCF'][2:] - props['RV_CCF'][:-2])
ccf_slope = average_ccf_diff / rv_ccf_diff
# Calculate the CCF oversampling
ccf_oversamp = IMAGE_PIXEL_SIZE / CCF_STEP
# create a list of indices based on the oversample grid size
flist = np.arange(np.round(len(ccf_slope) / ccf_oversamp))
indexlist = np.array(flist * ccf_oversamp, dtype=int)
# we only want the unique pixels (not oversampled)
indexlist = np.unique(indexlist)
# get the rv noise from the sum of pixels for those points that are
# not oversampled
keep_ccf_slope = ccf_slope[indexlist]
keep_ccf_noise = ccf_noise_tot[1:-1][indexlist]
rv_noise = np.nansum(keep_ccf_slope ** 2 / keep_ccf_noise ** 2) ** (-0.5)
# --------------------------------------------------------------------------
# log the stats
wargs = [ccf_contrast, float(mean_ccf_coeffs[1]), rv_noise, ccf_fwhm]
print('MEAN CCF:')
print('\tCorrelation: C={0:1f}[%] RV={1:.5f}[km/s] RV_NOISE={2:.5f}[km/s] '
'FWHM={3:.4f}[km/s]'.format(*wargs))
# --------------------------------------------------------------------------
# add to output array
props['MEAN_CCF'] = mean_ccf
props['MEAN_RV'] = ccf_rv
props['MEAN_CONTRAST'] = ccf_contrast
props['MEAN_FWHM'] = ccf_fwhm
props['MEAN_CCF_RES'] = mean_ccf_coeffs
props['MEAN_CCF_FIT'] = mean_ccf_fit
props['MEAN_RV_NOISE'] = rv_noise
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
return props
def plot_individual_ccf(props, nbo):
# get the plot loop generator
generator = plotloop(range(nbo))
# loop around orders
for order_num in generator:
plt.close()
fig, frame = plt.subplots(ncols=1, nrows=1)
frame.plot(props['RV_CCF'], props['CCF'][order_num], color='b',
marker='+', ls='None', label='data')
frame.plot(props['RV_CCF'], props['CCF_FIT'][order_num], color='r', )
rvorder = props['CCF_FIT_COEFFS'][order_num][1]
frame.set(title='Order {0} RV = {1} km/s'.format(order_num, rvorder),
xlabel='RV [km/s]', ylabel='CCF')
plt.show()
plt.close()
def plot_mean_ccf(props):
plt.close()
fig, frame = plt.subplots(ncols=1, nrows=1)
frame.plot(props['RV_CCF'], props['MEAN_CCF'], color='b', marker='+',
ls='None')
frame.plot(props['RV_CCF'], props['MEAN_CCF_FIT'], color='r')
frame.set(title='Mean CCF RV = {0} km/s'.format(props['MEAN_RV']),
xlabel='RV [km/s]', ylabel='CCF')
plt.show()
plt.close()
def plotloop(looplist):
# check that looplist is a valid list
if not isinstance(looplist, list):
# noinspection PyBroadException
try:
looplist = list(looplist)
except Exception as _:
print('PLOT ERROR: looplist must be a list')
# define message to give to user
message = ('Plot loop navigation: Go to \n\t [P]revious plot '
'\n\t [N]ext plot \n\t [E]nd plotting '
'\n\t Number from [0 to {0}]: \t')
message = message.format(len(looplist) - 1)
# start the iterator at zero
it = 0
first = True
# loop around until we hit the length of the loop list
while it < len(looplist):
# deal with end of looplist
if it == len(looplist):
# break out of while
break
# if this is the first iteration do not print message
if first:
# yield the first iteration value
yield looplist[it]
# increase the iterator value
it += 1
first = False
# else we need to ask to go to previous, next or end
else:
# get user input
userinput = input(message)
# try to cast into a integer
# noinspection PyBroadException
try:
userinput = int(userinput)
except Exception as _:
userinput = str(userinput)
# if 'p' in user input we assume they want to go to previous
if 'P' in str(userinput).upper():
yield looplist[it - 1]
it -= 1
# if 'n' in user input we assume they want to go to next
elif 'N' in str(userinput).upper():
yield looplist[it + 1]
it += 1
elif isinstance(userinput, int):
it = userinput
# deal with it too low
if it < 0:
it = 0
# deal with it too large
elif it >= len(looplist):
it = len(looplist) - 1
# yield the value of it
yield looplist[it]
# else we assume the loop is over and we want to exit
else:
# break out of while
break
def write_file(props, infile, maskname, header, wheader, only_outname=False):
# ----------------------------------------------------------------------
# construct out file name
inbasename = os.path.basename(infile).split('.')[0]
maskbasename = os.path.basename(maskname).split('.')[0]
inpath = os.path.dirname(infile)
outfile = 'CCFTABLE_{0}_{1}.fits'.format(inbasename, maskbasename)
outpath = os.path.join(inpath, outfile)
if only_outname:
return outpath
# ----------------------------------------------------------------------
# produce CCF table
table1 = Table()
table1['RV'] = props['RV_CCF']
for order_num in range(len(props['CCF'])):
table1['ORDER{0:02d}'.format(order_num)] = props['CCF'][order_num]
table1['COMBINED'] = props['MEAN_CCF']
# ----------------------------------------------------------------------
# produce stats table
table2 = Table()
table2['ORDERS'] = np.arange(len(props['CCF'])).astype(int)
table2['NLINES'] = props['CCF_LINES']
# get the coefficients
coeffs = props['CCF_FIT_COEFFS']
table2['CONTRAST'] = np.abs(100 * coeffs[:, 0])
table2['RV'] = coeffs[:, 1]
table2['FWHM'] = coeffs[:, 2]
table2['DC'] = coeffs[:, 3]
table2['SNR'] = props['CCF_SNR']
table2['NORM'] = props['CCF_NORM']
# ----------------------------------------------------------------------
# add to the header
# ----------------------------------------------------------------------
# add results from the CCF
header['CCFMNRV'] = (props['MEAN_RV'],
'Mean RV calc. from the mean CCF [km/s]')
header['CCFMCONT'] = (props['MEAN_CONTRAST'],
'Mean contrast (depth of fit) from mean CCF')
header['CCFMFWHM'] = (props['MEAN_FWHM'],
'Mean FWHM from mean CCF')
header['CCFMRVNS'] = (props['MEAN_RV_NOISE'],
'Mean RV Noise from mean CCF')
header['CCFTLINE'] = (props['TOT_LINE'],
'Total no. of mask lines used in CCF')
# ----------------------------------------------------------------------
# add constants used to process
header['CCFMASK'] = (props['CCF_MASK'], 'CCF mask file used')
header['CCFSTEP'] = (props['CCF_STEP'], 'CCF step used [km/s]')
header['CCFWIDTH'] = (props['CCF_WIDTH'], 'CCF width used [km/s]')
header['CCFTRGRV'] = (props['TARGET_RV'],
'CCF central RV used in CCF [km/s]')
header['CCFSIGDT'] = (props['CCF_SIGDET'],
'Read noise used in photon noise calc. in CCF')
header['CCFBOXSZ'] = (props['CCF_BOXSIZE'],
'Size of bad px used in photon noise calc. in CCF')
header['CCFMAXFX'] = (props['CCF_MAXFLUX'],
'Flux thres for bad px in photon noise calc. in CCF')
header['CCFORDMX'] = (props['CCF_NMAX'],
'Last order used in mean for mean CCF')
# header['CCFMSKMN'] = (props['MASK_MIN'],
# 'Minimum weight of lines used in the CCF mask')
header['CCFMSKWD'] = (props['MASK_WIDTH'],
'Width of lines used in the CCF mask')
header['CCFMUNIT'] = (props['MASK_UNITS'], 'Units used in CCF Mask')
# ----------------------------------------------------------------------
# header['RV_WAVFN'] = (os.path.basename(WAVE_FILE),
# 'RV wave file used')
header['RV_WAVTM'] = (wheader['MJDMID'],
'RV wave file time [mjd]')
header['RV_WAVTD'] = (header['MJDMID'] - wheader['MJDMID'],
'RV timediff [days] btwn file and wave solution')
header['RV_WAVFP'] = ('None', 'RV measured from wave sol FP CCF [km/s]')
header['RV_SIMFP'] = ('None', 'RV measured from simultaneous FP CCF [km/s]')
header['RV_DRIFT'] = ('None',
'RV drift between wave sol and sim. FP CCF [km/s]')
header['RV_OBJ'] = (props['MEAN_RV'],
'RV calc in the object CCF (non corr.) [km/s]')
header['RV_CORR'] = ('None', 'RV corrected for FP CCF drift [km/s]')
# ----------------------------------------------------------------------
# log where we are writing the file to
print('Writing file to {0}'.format(outpath))
# construct hdus
hdu = fits.PrimaryHDU()
t1 = fits.BinTableHDU(table1, header=header)
t2 = fits.BinTableHDU(table2, header=header)
# construct hdu list
hdulist = fits.HDUList([hdu, t1, t2])
# write hdulist
hdulist.writeto(outpath, overwrite=True)
return outpath
def get_ccf(IN_FILES, MASK_FILE='Gl699_neg.mas',
BLAZE_FILE='workplace1/2019-04-20_2400404f_pp_blaze_AB.fits', KERNEL=None
):
helpstr = """
----------------------------------------------------------------------------
new_ccf_code.py
----------------------------------------------------------------------------
This code takes no arguments - you must edit the "variables section" of the
code
1. Finding the correct calibrations
a) For your observation find the date
b) Go to your /calibDB/ directory
c) find the correct file (closest in time?):
BLAZE: *blaze_{fiber}.fits
WAVE: *wave_night_{fiber}.fits
2. Finding masks
a) go to your apero-drs installation directory
b) go to data/spirou/ccf sub-directory
c) use one of these masks
3. Two options for where you put files
a) copy all data to a directory of your choice ({path})
i) copy this code there and set W1='' and W2=''
ii) or set W1={path} and W2={path}
b) set the paths for your data (W1) and your mask directory (W2)
Then update the filenames:
IN_FILES: the e2dsff_C or e2dsff_tcorr _AB file. Can include
wildcards to process multiple files at once. These files
must share the same BLAZE_FILE, WAVE_FIlE and all options.
BLAZE_FILE: the blaze file from calibDB - get the fiber correct!
WAVE_FILE: the wave file from calibDB - get the fiber correct!
MASK_FILE: the mask file
Note there are two cases (set CASE=1 or CASE=2)
For case=1 we assume your IN_FILE is a OBJ
For case=2 we assume your IN_FILe is a FP
Adding a convolution kernel. You can pass a kernel argument that
describes the convolution of the LSF. 'None' produces a Dirac comb
while 3 others are described below.
--> boxcar convolution
['boxcar', width]
kernel = [1, 1, ...., 1, 1]
--> gaussian convolution
['gaussian', e-width]
kernel = exp( -0.5*(x/ew)**2 )
--> super gaussian
['supergaussian', e-width, beta]
kernel = exp( -0.5*(x/ew)**beta )
Other functions could be added
----------------------------------------------------------------------------
"""
# =============================================================================
# Define variables
# =============================================================================
# constants
# if all files copied to same directory set these to ''
# W1 = ''
# W2 = ''
# these files are on cook@nb19
# W1 = 'workplace1'
# W2 = 'workplace2'
# whether to plot (True or False)
PLOT = False
# which case 1: science (OBJ) 2: reference (FP)
CASE = 1
# Pick you CCF convolution kernel. See explanantions below in the
# CCF function. Uncomment the kernel type you want and change the
# parameter.
# CCF is a set of Dirac functions
# KERNEL = None
# boxcar length expressed in km/s
# KERNEL = ['boxcar', 5]
# gaussian with e-width in km/s
# KERNEL = ['gaussian', 3.5]
# supergaussian e-width + exponent
# KERNEL = ['supergaussian', 3.5, 4]
# build file paths
# IN_FILES = glob.glob('Gl699/2*o_pp_e2dsff_*tcorr_AB.fits')
# BLAZE_FILE = 'workplace1/2019-04-20_2400404f_pp_blaze_AB.fits'
# MASK_FILE = 'Gl699_neg.mas'
# MASK_FILE = 'workplace2/masque_sept18_andres_trans50.mas'
for IN_FILE in IN_FILES:
# get input telluric corrected file and header
image, header = fits.getdata(IN_FILE, header=True)
blaze = fits.getdata(BLAZE_FILE)
masktable = read_mask(MASK_FILE, MASK_COLS)
wheader = header
wave = fits2wave(wheader)
# wave, wheader = fits.getdata(WAVE_FILE, header=True)
# get the dimensions
nbo, nbpix = image.shape
outname = write_file(dict(), IN_FILE, MASK_FILE, header, wheader, only_outname=True)
if os.path.isfile(outname):
print('File {0} exists, we skip'.format(outname))
continue
# --------------------------------------------------------------------------
# get fiber typoe
if 'FIBER' in header:
fiber = header['FIBER']
else:
raise ValueError('HEADER ERROR: FIBER MISSING')
# --------------------------------------------------------------------------
# get dprtype
if 'DPRTYPE' in header:
if fiber == 'AB':
dprtype = header['DPRTYPE'].split('_')[0]
else:
dprtype = header['DPRTYPE'].split('_')[1]
else:
raise ValueError('HEADER ERROR: DPRTYPE MISSING')
# make sure dprtype is correct for fiber
if dprtype not in ['OBJ', 'FP']:
raise ValueError('HEADER ERROR: DPRTPYE must be OBJ or FP')
# --------------------------------------------------------------------------
# get berv from header
if fiber == 'AB' and dprtype == 'OBJ':
berv = header['BERV']
# absorption features
fit_type = 0
else:
berv = 0.0
# emission features
fit_type = 1
# --------------------------------------------------------------------------
# get rv from header (or set to zero)
if ('OBJRV' in header) and dprtype == 'OBJ':
targetrv = header['OBJRV']
if np.isnan(targetrv) or np.abs(targetrv) > CCF_RV_NULL:
targetrv = 0.0
else:
targetrv = 0.0
if IN_RV is not None:
targetrv = float(IN_RV)
# --------------------------------------------------------------------------
# get mask centers, and weights
_, mask_centers, mask_weights = get_mask(masktable, MASK_WIDTH)
# --------------------------------------------------------------------------
# Photon noise uncertainty
# --------------------------------------------------------------------------
dkwargs = dict(spe=image, wave=wave, sigdet=NOISE_SIGDET,
size=NOISE_SIZE, threshold=NOISE_THRES)
# run DeltaVrms2D
dvrmsref, wmeanref = delta_v_rms_2d(**dkwargs)
wmsg = 'On fiber {0} estimated RV uncertainty on spectrum is {1:.3f}'
print(wmsg.format(fiber, wmeanref))
# --------------------------------------------------------------------------
# Calculate the CCF
# --------------------------------------------------------------------------
print('\nRunning CCF calculation')
props = ccf_calculation(wave, image, blaze, targetrv, mask_centers,
mask_weights, berv, fit_type, kernel=KERNEL)
# --------------------------------------------------------------------------
# Calculate the mean CCF
# --------------------------------------------------------------------------
print('\nRunning Mean CCF')
# add constants to props
props['CCF_MASK'] = os.path.basename(MASK_FILE)
props['CCF_STEP'] = CCF_STEP
props['CCF_WIDTH'] = CCF_WIDTH
props['TARGET_RV'] = targetrv
props['CCF_SIGDET'] = NOISE_SIGDET
props['CCF_BOXSIZE'] = NOISE_SIZE
props['CCF_MAXFLUX'] = NOISE_THRES
props['CCF_NMAX'] = CCF_N_ORD_MAX
# props['MASK_MIN'] = MASK_MIN_WEIGHT
props['MASK_WIDTH'] = MASK_WIDTH
props['MASK_UNITS'] = 'nm'
props = mean_ccf(props, targetrv, fit_type)
# --------------------------------------------------------------------------
# Plots
# --------------------------------------------------------------------------
if PLOT:
# plot individual CCFs
print('\n Plotting individual CCFs')
plot_individual_ccf(props, nbo)
# plot mean ccf and fit
print('\n Plotting Mean CCF')
plot_mean_ccf(props)
# --------------------------------------------------------------------------
# Save file
# --------------------------------------------------------------------------
# write the two tables to file CCFTABLE_{filename}_{mask}.fits
write_file(props, IN_FILE, MASK_FILE, header, wheader)
return IN_FILE
def wrap_ccf():
# file_strings = ['Gl699/2*o_pp_e2dsff_*tcorr_AB.fits','Gl699/2*o_pp_e2dsff_*sanit_AB.fits']
# mask_names = ['M4_all.mas','Gl699_full.mas','Gl699_neg.mas','Gl699_pos.mas','workplace2/masque_sept18_andres_trans50.mas']
file_strings = ['Gl699/2*o_pp_e2dsff_*sanit_AB.fits', 'Gl699/2*o_pp_e2dsff_*tcorr_AB.fits']
mask_names = ['Gl699_neg.mas', 'Gl699_full.mas']
for file_string in file_strings:
for mask_name in mask_names:
get_ccf(np.sort(glob.glob(file_string)), MASK_FILE=mask_name) | [
"numpy.nanpercentile",
"numpy.sum",
"numpy.abs",
"numpy.nanmedian",
"astropy.io.fits.PrimaryHDU",
"numpy.isnan",
"os.path.isfile",
"numpy.arange",
"numpy.exp",
"glob.glob",
"numpy.diag",
"numpy.convolve",
"astropy.io.fits.HDUList",
"os.path.join",
"numpy.round",
"numpy.unique",
"nump... | [((1502, 1539), 'astropy.table.Table.read', 'Table.read', (['MASK_FILE'], {'format': '"""ascii"""'}), "(MASK_FILE, format='ascii')\n", (1512, 1539), False, 'from astropy.table import Table\n'), ((3956, 3992), 'numpy.sqrt', 'np.sqrt', (['((1 + dv / c) / (1 - dv / c))'], {}), '((1 + dv / c) / (1 - dv / c))\n', (3963, 3992), True, 'import numpy as np\n'), ((4622, 4666), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['x', 'y'], {}), '(x, y, **kwargs)\n', (4650, 4666), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((6501, 6515), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (6512, 6515), True, 'import numpy as np\n'), ((12059, 12111), 'numpy.nansum', 'np.nansum', (['(sxn * (nwave * nspe) ** 2 * maskv)'], {'axis': '(1)'}), '(sxn * (nwave * nspe) ** 2 * maskv, axis=1)\n', (12068, 12111), True, 'import numpy as np\n'), ((13049, 13082), 'numpy.arange', 'np.arange', (['rvmin', 'rvmax', 'CCF_STEP'], {}), '(rvmin, rvmax, CCF_STEP)\n', (13058, 13082), True, 'import numpy as np\n'), ((23730, 23747), 'numpy.array', 'np.array', (['ccf_all'], {}), '(ccf_all)\n', (23738, 23747), True, 'import numpy as np\n'), ((23773, 23792), 'numpy.array', 'np.array', (['ccf_lines'], {}), '(ccf_lines)\n', (23781, 23792), True, 'import numpy as np\n'), ((23817, 23834), 'numpy.sum', 'np.sum', (['ccf_lines'], {}), '(ccf_lines)\n', (23823, 23834), True, 'import numpy as np\n'), ((23860, 23883), 'numpy.array', 'np.array', (['ccf_noise_all'], {}), '(ccf_noise_all)\n', (23868, 23883), True, 'import numpy as np\n'), ((23907, 23928), 'numpy.array', 'np.array', (['ccf_all_snr'], {}), '(ccf_all_snr)\n', (23915, 23928), True, 'import numpy as np\n'), ((23952, 23973), 'numpy.array', 'np.array', (['ccf_all_fit'], {}), '(ccf_all_fit)\n', (23960, 23973), True, 'import numpy as np\n'), ((24004, 24029), 'numpy.array', 'np.array', (['ccf_all_results'], {}), '(ccf_all_results)\n', (24012, 24029), True, 'import numpy as np\n'), ((24054, 24076), 'numpy.array', 'np.array', (['ccf_norm_all'], {}), '(ccf_norm_all)\n', (24062, 24076), True, 'import numpy as np\n'), ((24205, 24253), 'numpy.nanmean', 'np.nanmean', (["props['CCF'][:CCF_N_ORD_MAX]"], {'axis': '(0)'}), "(props['CCF'][:CCF_N_ORD_MAX], axis=0)\n", (24215, 24253), True, 'import numpy as np\n'), ((24614, 24646), 'numpy.abs', 'np.abs', (['(100 * mean_ccf_coeffs[0])'], {}), '(100 * mean_ccf_coeffs[0])\n', (24620, 24646), True, 'import numpy as np\n'), ((25327, 25368), 'numpy.array', 'np.array', (['(flist * ccf_oversamp)'], {'dtype': 'int'}), '(flist * ccf_oversamp, dtype=int)\n', (25335, 25368), True, 'import numpy as np\n'), ((25440, 25460), 'numpy.unique', 'np.unique', (['indexlist'], {}), '(indexlist)\n', (25449, 25460), True, 'import numpy as np\n'), ((27308, 27319), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27317, 27319), True, 'import matplotlib.pyplot as plt\n'), ((27337, 27367), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(1)', 'nrows': '(1)'}), '(ncols=1, nrows=1)\n', (27349, 27367), True, 'import matplotlib.pyplot as plt\n'), ((27659, 27669), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (27667, 27669), True, 'import matplotlib.pyplot as plt\n'), ((27674, 27685), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27683, 27685), True, 'import matplotlib.pyplot as plt\n'), ((30300, 30323), 'os.path.dirname', 'os.path.dirname', (['infile'], {}), '(infile)\n', (30315, 30323), False, 'import os\n'), ((30409, 30438), 'os.path.join', 'os.path.join', (['inpath', 'outfile'], {}), '(inpath, outfile)\n', (30421, 30438), False, 'import os\n'), ((30599, 30606), 'astropy.table.Table', 'Table', ([], {}), '()\n', (30604, 30606), False, 'from astropy.table import Table\n'), ((30923, 30930), 'astropy.table.Table', 'Table', ([], {}), '()\n', (30928, 30930), False, 'from astropy.table import Table\n'), ((31126, 31152), 'numpy.abs', 'np.abs', (['(100 * coeffs[:, 0])'], {}), '(100 * coeffs[:, 0])\n', (31132, 31152), True, 'import numpy as np\n'), ((34382, 34399), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {}), '()\n', (34397, 34399), False, 'from astropy.io import fits\n'), ((34409, 34448), 'astropy.io.fits.BinTableHDU', 'fits.BinTableHDU', (['table1'], {'header': 'header'}), '(table1, header=header)\n', (34425, 34448), False, 'from astropy.io import fits\n'), ((34458, 34497), 'astropy.io.fits.BinTableHDU', 'fits.BinTableHDU', (['table2'], {'header': 'header'}), '(table2, header=header)\n', (34474, 34497), False, 'from astropy.io import fits\n'), ((34537, 34564), 'astropy.io.fits.HDUList', 'fits.HDUList', (['[hdu, t1, t2]'], {}), '([hdu, t1, t2])\n', (34549, 34564), False, 'from astropy.io import fits\n'), ((4164, 4175), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (4172, 4175), True, 'import numpy as np\n'), ((4177, 4188), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (4185, 4188), True, 'import numpy as np\n'), ((4230, 4244), 'numpy.isfinite', 'np.isfinite', (['y'], {}), '(y)\n', (4241, 4244), True, 'import numpy as np\n'), ((4253, 4269), 'numpy.sum', 'np.sum', (['(~nanmask)'], {}), '(~nanmask)\n', (4259, 4269), True, 'import numpy as np\n'), ((4287, 4303), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (4300, 4303), True, 'import numpy as np\n'), ((5454, 5464), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5462, 5464), False, 'import sys\n'), ((5794, 5808), 'numpy.nanmax', 'np.nanmax', (['ccf'], {}), '(ccf)\n', (5803, 5808), True, 'import numpy as np\n'), ((5810, 5824), 'numpy.nanmin', 'np.nanmin', (['ccf'], {}), '(ccf)\n', (5819, 5824), True, 'import numpy as np\n'), ((5846, 5863), 'numpy.nanargmin', 'np.nanargmin', (['ccf'], {}), '(ccf)\n', (5858, 5863), True, 'import numpy as np\n'), ((5865, 5882), 'numpy.nanargmax', 'np.nanargmax', (['ccf'], {}), '(ccf)\n', (5877, 5882), True, 'import numpy as np\n'), ((6272, 6325), 'numpy.array', 'np.array', (['[diff / max_ccf, rv[argmax], 4 * rvdiff, 1]'], {}), '([diff / max_ccf, rv[argmax], 4 * rvdiff, 1])\n', (6280, 6325), True, 'import numpy as np\n'), ((9171, 9207), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (9194, 9207), False, 'import warnings\n'), ((9235, 9312), 'scipy.optimize.curve_fit', 'curve_fit', (['gauss_function', 'x', 'y'], {'p0': 'guess', 'sigma': 'weights', 'absolute_sigma': '(True)'}), '(gauss_function, x, y, p0=guess, sigma=weights, absolute_sigma=True)\n', (9244, 9312), False, 'from scipy.optimize import curve_fit\n'), ((9531, 9555), 'scipy.stats.chisquare', 'chisquare', (['y'], {'f_exp': 'yfit'}), '(y, f_exp=yfit)\n', (9540, 9555), False, 'from scipy.stats import chisquare\n'), ((11401, 11437), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (11424, 11437), False, 'import warnings\n'), ((12147, 12183), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (12170, 12183), False, 'import warnings\n'), ((15956, 15981), 'numpy.array', 'np.array', (['wave[order_num]'], {}), '(wave[order_num])\n', (15964, 15981), True, 'import numpy as np\n'), ((15999, 16025), 'numpy.array', 'np.array', (['image[order_num]'], {}), '(image[order_num])\n', (16007, 16025), True, 'import numpy as np\n'), ((16043, 16069), 'numpy.array', 'np.array', (['blaze[order_num]'], {}), '(blaze[order_num])\n', (16051, 16069), True, 'import numpy as np\n'), ((16264, 16311), 'numpy.nanpercentile', 'np.nanpercentile', (['bl_ord', 'BLAZE_NORM_PERCENTILE'], {}), '(bl_ord, BLAZE_NORM_PERCENTILE)\n', (16280, 16311), True, 'import numpy as np\n'), ((16616, 16644), 'numpy.nanmin', 'np.nanmin', (['wa_ord[blazemask]'], {}), '(wa_ord[blazemask])\n', (16625, 16644), True, 'import numpy as np\n'), ((16667, 16695), 'numpy.nanmax', 'np.nanmax', (['wa_ord[blazemask]'], {}), '(wa_ord[blazemask])\n', (16676, 16695), True, 'import numpy as np\n'), ((19502, 19523), 'numpy.zeros_like', 'np.zeros_like', (['rv_ccf'], {}), '(rv_ccf)\n', (19515, 19523), True, 'import numpy as np\n'), ((20782, 20807), 'numpy.nanmean', 'np.nanmean', (['omask_weights'], {}), '(omask_weights)\n', (20792, 20807), True, 'import numpy as np\n'), ((22617, 22638), 'numpy.nanmedian', 'np.nanmedian', (['ccf_ord'], {}), '(ccf_ord)\n', (22629, 22638), True, 'import numpy as np\n'), ((23117, 23130), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (23125, 23130), True, 'import numpy as np\n'), ((24853, 24896), 'numpy.nanmean', 'np.nanmean', (["(props['CCF_NOISE'] ** 2)"], {'axis': '(0)'}), "(props['CCF_NOISE'] ** 2, axis=0)\n", (24863, 24896), True, 'import numpy as np\n'), ((25668, 25720), 'numpy.nansum', 'np.nansum', (['(keep_ccf_slope ** 2 / keep_ccf_noise ** 2)'], {}), '(keep_ccf_slope ** 2 / keep_ccf_noise ** 2)\n', (25677, 25720), True, 'import numpy as np\n'), ((26780, 26791), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (26789, 26791), True, 'import matplotlib.pyplot as plt\n'), ((26813, 26843), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(1)', 'nrows': '(1)'}), '(ncols=1, nrows=1)\n', (26825, 26843), True, 'import matplotlib.pyplot as plt\n'), ((27245, 27255), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (27253, 27255), True, 'import matplotlib.pyplot as plt\n'), ((27264, 27275), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (27273, 27275), True, 'import matplotlib.pyplot as plt\n'), ((38330, 38364), 'astropy.io.fits.getdata', 'fits.getdata', (['IN_FILE'], {'header': '(True)'}), '(IN_FILE, header=True)\n', (38342, 38364), False, 'from astropy.io import fits\n'), ((38381, 38405), 'astropy.io.fits.getdata', 'fits.getdata', (['BLAZE_FILE'], {}), '(BLAZE_FILE)\n', (38393, 38405), False, 'from astropy.io import fits\n'), ((38747, 38770), 'os.path.isfile', 'os.path.isfile', (['outname'], {}), '(outname)\n', (38761, 38770), False, 'import os\n'), ((41858, 41885), 'os.path.basename', 'os.path.basename', (['MASK_FILE'], {}), '(MASK_FILE)\n', (41874, 41885), False, 'import os\n'), ((1806, 1834), 'numpy.array', 'np.array', (["table['ll_mask_e']"], {}), "(table['ll_mask_e'])\n", (1814, 1834), True, 'import numpy as np\n'), ((1865, 1893), 'numpy.array', 'np.array', (["table['ll_mask_s']"], {}), "(table['ll_mask_s'])\n", (1873, 1893), True, 'import numpy as np\n'), ((2183, 2208), 'numpy.array', 'np.array', (["table['w_mask']"], {}), "(table['w_mask'])\n", (2191, 2208), True, 'import numpy as np\n'), ((4313, 4328), 'numpy.sum', 'np.sum', (['nanmask'], {}), '(nanmask)\n', (4319, 4328), True, 'import numpy as np\n'), ((4432, 4498), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['x[~nanmask]', 'y[~nanmask]'], {'k': '(1)', 'ext': '(1)'}), '(x[~nanmask], y[~nanmask], k=1, ext=1)\n', (4460, 4498), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((5505, 5518), 'numpy.isnan', 'np.isnan', (['ccf'], {}), '(ccf)\n', (5513, 5518), True, 'import numpy as np\n'), ((5652, 5663), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (5660, 5663), True, 'import numpy as np\n'), ((5691, 5709), 'numpy.zeros_like', 'np.zeros_like', (['ccf'], {}), '(ccf)\n', (5704, 5709), True, 'import numpy as np\n'), ((6061, 6075), 'numpy.nanmax', 'np.nanmax', (['ccf'], {}), '(ccf)\n', (6070, 6075), True, 'import numpy as np\n'), ((6098, 6152), 'numpy.array', 'np.array', (['[-diff / max_ccf, rv[argmin], 4 * rvdiff, 0]'], {}), '([-diff / max_ccf, rv[argmin], 4 * rvdiff, 0])\n', (6106, 6152), True, 'import numpy as np\n'), ((6183, 6194), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (6191, 6194), True, 'import numpy as np\n'), ((6583, 6619), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (6606, 6619), False, 'import warnings\n'), ((6732, 6752), 'numpy.repeat', 'np.repeat', (['np.nan', '(4)'], {}), '(np.nan, 4)\n', (6741, 6752), True, 'import numpy as np\n'), ((7405, 7443), 'numpy.exp', 'np.exp', (['(-0.5 * ((x - x0) / sigma) ** 2)'], {}), '(-0.5 * ((x - x0) / sigma) ** 2)\n', (7411, 7443), True, 'import numpy as np\n'), ((9043, 9055), 'numpy.nanmax', 'np.nanmax', (['y'], {}), '(y)\n', (9052, 9055), True, 'import numpy as np\n'), ((9057, 9070), 'numpy.nanmean', 'np.nanmean', (['y'], {}), '(y)\n', (9067, 9070), True, 'import numpy as np\n'), ((9072, 9084), 'numpy.nanstd', 'np.nanstd', (['y'], {}), '(y)\n', (9081, 9084), True, 'import numpy as np\n'), ((9696, 9709), 'numpy.sqrt', 'np.sqrt', (['norm'], {}), '(norm)\n', (9703, 9709), True, 'import numpy as np\n'), ((12318, 12341), 'numpy.nansum', 'np.nansum', (['(1.0 / dvrms2)'], {}), '(1.0 / dvrms2)\n', (12327, 12341), True, 'import numpy as np\n'), ((14982, 14993), 'numpy.sum', 'np.sum', (['ker'], {}), '(ker)\n', (14988, 14993), True, 'import numpy as np\n'), ((16452, 16488), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (16475, 16488), False, 'import warnings\n'), ((17480, 17496), 'numpy.isnan', 'np.isnan', (['sp_ord'], {}), '(sp_ord)\n', (17488, 17496), True, 'import numpy as np\n'), ((17499, 17515), 'numpy.isnan', 'np.isnan', (['bl_ord'], {}), '(bl_ord)\n', (17507, 17515), True, 'import numpy as np\n'), ((17639, 17661), 'numpy.sum', 'np.sum', (['mask_wave_mask'], {}), '(mask_wave_mask)\n', (17645, 17661), True, 'import numpy as np\n'), ((18270, 18285), 'numpy.sum', 'np.sum', (['nanmask'], {}), '(nanmask)\n', (18276, 18285), True, 'import numpy as np\n'), ((21072, 21091), 'numpy.sum', 'np.sum', (['valid_lines'], {}), '(valid_lines)\n', (21078, 21091), True, 'import numpy as np\n'), ((9679, 9692), 'numpy.diag', 'np.diag', (['pcov'], {}), '(pcov)\n', (9686, 9692), True, 'import numpy as np\n'), ((10165, 10189), 'scipy.stats.chisquare', 'chisquare', (['y'], {'f_exp': 'yfit'}), '(y, f_exp=yfit)\n', (10174, 10189), False, 'from scipy.stats import chisquare\n'), ((14243, 14275), 'numpy.exp', 'np.exp', (['(-0.5 * (index / ew) ** 2)'], {}), '(-0.5 * (index / ew) ** 2)\n', (14249, 14275), True, 'import numpy as np\n'), ((16381, 16400), 'numpy.isfinite', 'np.isfinite', (['bl_ord'], {}), '(bl_ord)\n', (16392, 16400), True, 'import numpy as np\n'), ((17935, 17955), 'numpy.repeat', 'np.repeat', (['np.nan', '(4)'], {}), '(np.nan, 4)\n', (17944, 17955), True, 'import numpy as np\n'), ((18547, 18567), 'numpy.repeat', 'np.repeat', (['np.nan', '(4)'], {}), '(np.nan, 4)\n', (18556, 18567), True, 'import numpy as np\n'), ((21250, 21286), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (21273, 21286), False, 'import warnings\n'), ((21387, 21451), 'numpy.nansum', 'np.nansum', (['(ccf_element[valid_lines] * omask_weights[valid_lines])'], {}), '(ccf_element[valid_lines] * omask_weights[valid_lines])\n', (21396, 21451), True, 'import numpy as np\n'), ((21661, 21678), 'numpy.isnan', 'np.isnan', (['ccf_ord'], {}), '(ccf_ord)\n', (21669, 21678), True, 'import numpy as np\n'), ((21945, 21965), 'numpy.repeat', 'np.repeat', (['np.nan', '(4)'], {}), '(np.nan, 4)\n', (21954, 21965), True, 'import numpy as np\n'), ((22427, 22465), 'numpy.convolve', 'np.convolve', (['ccf_ord', 'ker'], {'mode': '"""same"""'}), "(ccf_ord, ker, mode='same')\n", (22438, 22465), True, 'import numpy as np\n'), ((30188, 30212), 'os.path.basename', 'os.path.basename', (['infile'], {}), '(infile)\n', (30204, 30212), False, 'import os\n'), ((30246, 30272), 'os.path.basename', 'os.path.basename', (['maskname'], {}), '(maskname)\n', (30262, 30272), False, 'import os\n'), ((40236, 40254), 'numpy.isnan', 'np.isnan', (['targetrv'], {}), '(targetrv)\n', (40244, 40254), True, 'import numpy as np\n'), ((10330, 10343), 'numpy.sqrt', 'np.sqrt', (['norm'], {}), '(norm)\n', (10337, 10343), True, 'import numpy as np\n'), ((12702, 12711), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (12708, 12711), True, 'import numpy as np\n'), ((13971, 14001), 'numpy.round', 'np.round', (['(kernel[1] / CCF_STEP)'], {}), '(kernel[1] / CCF_STEP)\n', (13979, 14001), True, 'import numpy as np\n'), ((23232, 23249), 'numpy.abs', 'np.abs', (['ccf_noise'], {}), '(ccf_noise)\n', (23238, 23249), True, 'import numpy as np\n'), ((40258, 40274), 'numpy.abs', 'np.abs', (['targetrv'], {}), '(targetrv)\n', (40264, 40274), True, 'import numpy as np\n'), ((43630, 43652), 'glob.glob', 'glob.glob', (['file_string'], {}), '(file_string)\n', (43639, 43652), False, 'import glob\n'), ((10313, 10326), 'numpy.diag', 'np.diag', (['pcov'], {}), '(pcov)\n', (10320, 10326), True, 'import numpy as np\n'), ((14191, 14202), 'numpy.ceil', 'np.ceil', (['ew'], {}), '(ew)\n', (14198, 14202), True, 'import numpy as np\n'), ((14208, 14219), 'numpy.ceil', 'np.ceil', (['ew'], {}), '(ew)\n', (14215, 14219), True, 'import numpy as np\n'), ((14719, 14730), 'numpy.ceil', 'np.ceil', (['ew'], {}), '(ew)\n', (14726, 14730), True, 'import numpy as np\n'), ((14736, 14747), 'numpy.ceil', 'np.ceil', (['ew'], {}), '(ew)\n', (14743, 14747), True, 'import numpy as np\n'), ((14785, 14803), 'numpy.abs', 'np.abs', (['(index / ew)'], {}), '(index / ew)\n', (14791, 14803), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
from .element import Element
from .equation import LeakyWallEquation
from . import besselnumba
class LineDoubletHoBase(Element):
'''Higher Order LineDoublet Base Class.
All Higher Order Line Doublet elements are derived from this class'''
def __init__(self, model, x1=-1, y1=0, x2=1, y2=0, tsandbc=
[(0.0, 0.0)], res='imp', order=0, layers=0, type='',
name='LineDoubletHoBase', label=None, addtomodel=True):
Element.__init__(self, model, nparam=1, nunknowns=0, layers=layers,
tsandbc=tsandbc, type=type, name=name, label=label)
self.order = order
self.nparam = (self.order + 1) * len(self.layers)
self.x1 = float(x1)
self.y1 = float(y1)
self.x2 = float(x2)
self.y2 = float(y2)
if res == 'imp':
self.res = np.inf
else:
self.res = float(res)
if addtomodel: self.model.addelement(self)
def __repr__(self):
return self.name + ' from ' + str((self.x1, self.y1)) +\
' to ' + str((self.x2, self.y2))
def initialize(self):
self.ncp = self.order + 1
self.z1 = self.x1 + 1j * self.y1
self.z2 = self.x2 + 1j * self.y2
self.L = np.abs(self.z1 - self.z2)
self.thetanormOut = np.arctan2(self.y2 - self.y1, self.x2 - self.x1) \
- np.pi / 2
self.cosout = np.cos(self.thetanormOut) * np.ones(self.ncp)
self.sinout = np.sin(self.thetanormOut) * np.ones(self.ncp)
#
thetacp = np.arange(np.pi, 0, -np.pi / self.ncp) \
- 0.5 * np.pi / self.ncp
Zcp = np.zeros(self.ncp, 'D')
Zcp.real = np.cos(thetacp)
# control point just on positive site (this is handy later on)
Zcp.imag = 1e-6
zcp = Zcp * (self.z2 - self.z1) / 2 + 0.5 * (self.z1 + self.z2)
self.xc = zcp.real
self.yc = zcp.imag
# control point just on negative side
# (this is needed for building the system of equations)
Zcp.imag = -1e-6
zcp = Zcp * (self.z2 - self.z1) / 2 + 0.5 * (self.z1 + self.z2)
self.xcneg = zcp.real
self.ycneg = zcp.imag # control points just on negative side
#
self.aq = self.model.aq.find_aquifer_data(self.xc[0], self.yc[0])
self.setbc()
coef = self.aq.coef[self.layers, :]
self.setflowcoef()
# shape (self.nlayers,self.aq.naq,self.model.npvalval)
self.term = self.flowcoef * coef
self.term2 = self.term.reshape(self.nlayers, self.aq.naq,
self.model.nint, self.model.npint)
self.resfac = self.aq.Haq[self.layers] / self.res
self.dischargeinf = self.flowcoef * coef
self.dischargeinflayers = np.sum(self.dischargeinf *
self.aq.eigvec[self.layers, :, :], 1)
def setflowcoef(self):
'''Separate function so that this can be overloaded for other types'''
self.flowcoef = 1.0 / self.model.p # Step function
def potinf(self,x,y,aq=None):
'''Can be called with only one x,y value'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rv = np.zeros((self.nparam, aq.naq, self.model.nint,
self.model.npint), 'D')
if aq == self.aq:
pot = np.zeros((self.order+1,self.model.npint),'D')
for i in range(self.aq.naq):
for j in range(self.model.nint):
if besselnumba.isinside(self.z1, self.z2, x+y*1j,
self.rzero*self.aq.lababs[i, j]):
pot[:,:] = besselnumba.besselldv2(x, y,
self.z1, self.z2, self.aq.lab2[i, j, :],
self.order,
self.rzero * self.aq.lababs[i, j]) / self.L
for k in range(self.nlayers):
rv[k::self.nlayers, i, j, :] = \
self.term2[k, i, j, :] * pot
rv.shape = (self.nparam, aq.naq, self.model.npval)
return rv
def disvecinf(self,x,y,aq=None):
'''Can be called with only one x,y value'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rvx = np.zeros((self.nparam, aq.naq, self.model.nint,
self.model.npint), 'D')
rvy = np.zeros((self.nparam, aq.naq, self.model.nint,
self.model.npint), 'D')
if aq == self.aq:
qxqy = np.zeros((2*(self.order+1),self.model.npint),'D')
for i in range(self.aq.naq):
for j in range(self.model.nint):
if besselnumba.isinside(self.z1, self.z2, x+y*1j,
self.rzero*self.aq.lababs[i, j]):
qxqy[:,:] = besselnumba.besselldqxqyv2(x, y,
self.z1, self.z2,self.aq.lab2[i, j, :],
self.order,
self.rzero * self.aq.lababs[i, j]) / self.L
for k in range(self.nlayers):
rvx[k::self.nlayers, i, j, :] = \
self.term2[k, i, j, :] * \
qxqy[:self.order + 1,:]
rvy[k::self.nlayers, i, j, :] = \
self.term2[k, i, j, :] * \
qxqy[self.order + 1:,:]
rvx.shape = (self.nparam, aq.naq, self.model.npval)
rvy.shape = (self.nparam, aq.naq, self.model.npval)
return rvx, rvy
def plot(self):
plt.plot([self.x1, self.x2], [self.y1, self.y2], 'k')
class LeakyLineDoublet(LineDoubletHoBase, LeakyWallEquation):
"""
Create a segment of a leaky wall, which is
simulated with a line-doublet. The specific discharge through
the wall is equal to the head difference across the wall
divided by the resistance of the wall.
Parameters
----------
model : Model object
Model to which the element is added
x1 : scalar
x-coordinate of fist point of line-doublet
y1 : scalar
y-coordinate of fist point of line-doublet
x2 : scalar
x-coordinate of second point of line-doublet
y2 : scalar
y-coordinate of second point of line-doublet
res : scalar or string
if string: 'imp' for an impermeable wall (same as res = np.inf)
if scalar: resistance of leaky wall
order : int (default is 0)
polynomial order of potential jump along line-doublet
(head jump if transmissivity is equal on each side of wall)
layers : scalar, list or array
layer(s) in which element is placed
if scalar: element is placed in this layer
if list or array: element is placed in all these layers
label: str or None
label of element
See Also
--------
:class:`.LeakyLineDoubletString`
"""
def __init__(self, model, x1=-1, y1=0, x2=1, y2=0, res='imp', order=0,
layers=0, label=None, addtomodel=True):
self.storeinput(inspect.currentframe())
LineDoubletHoBase.__init__(self, model, x1=x1, y1=y1, x2=x2, y2=y2,
tsandbc=[(0, 0)], res=res, order=order,
layers=layers, type='z',
name='LeakyLineDoublet',
label=label, addtomodel=addtomodel)
self.nunknowns = self.nparam
def initialize(self):
LineDoubletHoBase.initialize(self)
self.parameters = np.zeros((self.model.ngvbc, self.nparam,
self.model.npval), 'D')
class LeakyLineDoubletString(Element, LeakyWallEquation):
"""
Create a string of leaky wall segements consisting
of line-doublets
Parameters
----------
model : Model object
Model to which the element is added
xy : array or list
list or array of (x,y) pairs of coordinates of end-points of
the segements in the string
res : scalar or string
if string: 'imp' for an impermeable wall (same as res = np.inf)
if scalar: resistance of leaky wall
order : int (default is 0)
polynomial order of potential jump along line-doublet
(head jump if transmissivity is equal on each side of wall)
layers : scalar, list or array
layer(s) in which element is placed
if scalar: element is placed in this layer
if list or array: element is placed in all these layers
label: str or None
label of element
See Also
--------
:class:`.LeakyLineDoublet`
"""
def __init__(self, model, xy=[(-1, 0), (1, 0)], res='imp', order=0,
layers=0, label=None):
self.storeinput(inspect.currentframe())
Element.__init__(self, model, nparam=1, nunknowns=0, layers=layers,
tsandbc=[(0, 0)], type='z',
name='LeakyLineDoubletString', label=label)
self.res = res
self.order = order
self.ldlist = []
xy = np.atleast_2d(xy).astype('d')
self.x,self.y = xy[:,0], xy[:,1]
self.nld = len(self.x) - 1
for i in range(self.nld):
self.ldlist.append(LeakyLineDoublet(model,
x1=self.x[i], y1=self.y[i],
x2=self.x[i + 1], y2=self.y[i + 1],
res=self.res, order=self.order,
layers=layers, label=label,
addtomodel=False))
self.model.addelement(self)
def __repr__(self):
return self.name + ' with nodes ' + str(zip(self.x,self.y))
def initialize(self):
for ld in self.ldlist:
ld.initialize()
# Same order for all elements in string
self.ncp = self.nld * self.ldlist[0].ncp
self.nparam = self.nld * self.ldlist[0].nparam
self.nunknowns = self.nparam
self.xld,self.yld = np.empty((self.nld,2)), np.empty((self.nld,2))
for i,ld in enumerate(self.ldlist):
self.xld[i,:] = [ld.x1,ld.x2]
self.yld[i,:] = [ld.y1,ld.y2]
# Only used for layout when it is a continuous string
self.xldlayout = np.hstack((self.xld[:,0],self.xld[-1,1]))
self.yldlayout = np.hstack((self.yld[:,0],self.yld[-1,1]))
self.aq = self.model.aq.find_aquifer_data(self.ldlist[0].xc,
self.ldlist[0].yc)
self.parameters = np.zeros((self.model.ngvbc, self.nparam,
self.model.npval), 'D')
self.setbc()
# As parameters are only stored for the element not the list,
# we need to combine the following
self.resfac = self.ldlist[0].resfac # same for all elements in the list
self.xc, self.yc = np.zeros(self.ncp), np.zeros(self.ncp)
self.xcneg, self.ycneg = np.zeros(self.ncp), np.zeros(self.ncp)
self.cosout, self.sinout = np.zeros(self.ncp), np.zeros(self.ncp)
for i,ld in enumerate(self.ldlist):
self.xc[i * ld.ncp: (i + 1) * ld.ncp] = ld.xc
self.yc[i * ld.ncp: (i + 1) * ld.ncp] = ld.yc
self.xcneg[i * ld.ncp: (i + 1) * ld.ncp] = ld.xcneg
self.ycneg[i * ld.ncp: (i + 1) * ld.ncp] = ld.ycneg
self.cosout[i * ld.ncp: (i + 1) * ld.ncp] = ld.cosout
self.sinout[i * ld.ncp: (i + 1) * ld.ncp] = ld.sinout
def potinf(self, x, y, aq=None):
'''Returns array (nunknowns,nperiods)'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rv = np.zeros((self.nparam, aq.naq, self.model.npval), 'D')
for i,ld in enumerate(self.ldlist):
rv[i*ld.nparam:(i+1)*ld.nparam,:] = ld.potinf(x,y,aq)
return rv
def disvecinf(self, x, y, aq=None):
'''Returns array (nunknowns,nperiods)'''
if aq is None: aq = self.model.aq.find_aquifer_data(x, y)
rvx = np.zeros((self.nparam, aq.naq, self.model.npval), 'D')
rvy = np.zeros((self.nparam, aq.naq, self.model.npval), 'D')
for i,ld in enumerate(self.ldlist):
qx,qy = ld.disvecinf(x,y,aq)
rvx[i*ld.nparam:(i+1)*ld.nparam,:] = qx
rvy[i*ld.nparam:(i+1)*ld.nparam,:] = qy
return rvx,rvy
def plot(self):
plt.plot(self.xldlayout, self.yldlayout, 'k')
| [
"numpy.abs",
"numpy.sum",
"matplotlib.pyplot.plot",
"numpy.arctan2",
"numpy.empty",
"numpy.zeros",
"numpy.ones",
"numpy.hstack",
"numpy.sin",
"numpy.arange",
"numpy.cos",
"inspect.currentframe",
"numpy.atleast_2d"
] | [((1366, 1391), 'numpy.abs', 'np.abs', (['(self.z1 - self.z2)'], {}), '(self.z1 - self.z2)\n', (1372, 1391), True, 'import numpy as np\n'), ((1773, 1796), 'numpy.zeros', 'np.zeros', (['self.ncp', '"""D"""'], {}), "(self.ncp, 'D')\n", (1781, 1796), True, 'import numpy as np\n'), ((1816, 1831), 'numpy.cos', 'np.cos', (['thetacp'], {}), '(thetacp)\n', (1822, 1831), True, 'import numpy as np\n'), ((2934, 2998), 'numpy.sum', 'np.sum', (['(self.dischargeinf * self.aq.eigvec[self.layers, :, :])', '(1)'], {}), '(self.dischargeinf * self.aq.eigvec[self.layers, :, :], 1)\n', (2940, 2998), True, 'import numpy as np\n'), ((3374, 3445), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.nint, self.model.npint)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.nint, self.model.npint), 'D')\n", (3382, 3445), True, 'import numpy as np\n'), ((4466, 4537), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.nint, self.model.npint)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.nint, self.model.npint), 'D')\n", (4474, 4537), True, 'import numpy as np\n'), ((4577, 4648), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.nint, self.model.npint)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.nint, self.model.npint), 'D')\n", (4585, 4648), True, 'import numpy as np\n'), ((5865, 5918), 'matplotlib.pyplot.plot', 'plt.plot', (['[self.x1, self.x2]', '[self.y1, self.y2]', '"""k"""'], {}), "([self.x1, self.x2], [self.y1, self.y2], 'k')\n", (5873, 5918), True, 'import matplotlib.pyplot as plt\n'), ((7888, 7952), 'numpy.zeros', 'np.zeros', (['(self.model.ngvbc, self.nparam, self.model.npval)', '"""D"""'], {}), "((self.model.ngvbc, self.nparam, self.model.npval), 'D')\n", (7896, 7952), True, 'import numpy as np\n'), ((10667, 10711), 'numpy.hstack', 'np.hstack', (['(self.xld[:, 0], self.xld[-1, 1])'], {}), '((self.xld[:, 0], self.xld[-1, 1]))\n', (10676, 10711), True, 'import numpy as np\n'), ((10735, 10779), 'numpy.hstack', 'np.hstack', (['(self.yld[:, 0], self.yld[-1, 1])'], {}), '((self.yld[:, 0], self.yld[-1, 1]))\n', (10744, 10779), True, 'import numpy as np\n'), ((10942, 11006), 'numpy.zeros', 'np.zeros', (['(self.model.ngvbc, self.nparam, self.model.npval)', '"""D"""'], {}), "((self.model.ngvbc, self.nparam, self.model.npval), 'D')\n", (10950, 11006), True, 'import numpy as np\n'), ((12057, 12111), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.npval)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.npval), 'D')\n", (12065, 12111), True, 'import numpy as np\n'), ((12410, 12464), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.npval)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.npval), 'D')\n", (12418, 12464), True, 'import numpy as np\n'), ((12479, 12533), 'numpy.zeros', 'np.zeros', (['(self.nparam, aq.naq, self.model.npval)', '"""D"""'], {}), "((self.nparam, aq.naq, self.model.npval), 'D')\n", (12487, 12533), True, 'import numpy as np\n'), ((12779, 12824), 'matplotlib.pyplot.plot', 'plt.plot', (['self.xldlayout', 'self.yldlayout', '"""k"""'], {}), "(self.xldlayout, self.yldlayout, 'k')\n", (12787, 12824), True, 'import matplotlib.pyplot as plt\n'), ((1420, 1468), 'numpy.arctan2', 'np.arctan2', (['(self.y2 - self.y1)', '(self.x2 - self.x1)'], {}), '(self.y2 - self.y1, self.x2 - self.x1)\n', (1430, 1468), True, 'import numpy as np\n'), ((1533, 1558), 'numpy.cos', 'np.cos', (['self.thetanormOut'], {}), '(self.thetanormOut)\n', (1539, 1558), True, 'import numpy as np\n'), ((1561, 1578), 'numpy.ones', 'np.ones', (['self.ncp'], {}), '(self.ncp)\n', (1568, 1578), True, 'import numpy as np\n'), ((1601, 1626), 'numpy.sin', 'np.sin', (['self.thetanormOut'], {}), '(self.thetanormOut)\n', (1607, 1626), True, 'import numpy as np\n'), ((1629, 1646), 'numpy.ones', 'np.ones', (['self.ncp'], {}), '(self.ncp)\n', (1636, 1646), True, 'import numpy as np\n'), ((1675, 1713), 'numpy.arange', 'np.arange', (['np.pi', '(0)', '(-np.pi / self.ncp)'], {}), '(np.pi, 0, -np.pi / self.ncp)\n', (1684, 1713), True, 'import numpy as np\n'), ((3514, 3563), 'numpy.zeros', 'np.zeros', (['(self.order + 1, self.model.npint)', '"""D"""'], {}), "((self.order + 1, self.model.npint), 'D')\n", (3522, 3563), True, 'import numpy as np\n'), ((4719, 4774), 'numpy.zeros', 'np.zeros', (['(2 * (self.order + 1), self.model.npint)', '"""D"""'], {}), "((2 * (self.order + 1), self.model.npint), 'D')\n", (4727, 4774), True, 'import numpy as np\n'), ((7387, 7409), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (7407, 7409), False, 'import inspect\n'), ((9145, 9167), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (9165, 9167), False, 'import inspect\n'), ((10405, 10428), 'numpy.empty', 'np.empty', (['(self.nld, 2)'], {}), '((self.nld, 2))\n', (10413, 10428), True, 'import numpy as np\n'), ((10429, 10452), 'numpy.empty', 'np.empty', (['(self.nld, 2)'], {}), '((self.nld, 2))\n', (10437, 10452), True, 'import numpy as np\n'), ((11286, 11304), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11294, 11304), True, 'import numpy as np\n'), ((11306, 11324), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11314, 11324), True, 'import numpy as np\n'), ((11358, 11376), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11366, 11376), True, 'import numpy as np\n'), ((11378, 11396), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11386, 11396), True, 'import numpy as np\n'), ((11432, 11450), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11440, 11450), True, 'import numpy as np\n'), ((11452, 11470), 'numpy.zeros', 'np.zeros', (['self.ncp'], {}), '(self.ncp)\n', (11460, 11470), True, 'import numpy as np\n'), ((9457, 9474), 'numpy.atleast_2d', 'np.atleast_2d', (['xy'], {}), '(xy)\n', (9470, 9474), True, 'import numpy as np\n')] |
#!/usr/bin/python3
import cv2
import time
import threading
import subprocess
import numpy as np
from sys import exit
from os import system
from keras import backend as K
from keras.models import load_model
from yad2k.models.keras_yolo import yolo_eval, yolo_head
'''
---# GLOBAL VARIABLES #---
'''
#USER SETTINGS :
maxDays = 7 #The recorded videos will be destroyed after "maxDays" days
baseFolder = "/var/www/html/" #Apache's base folder
scriptFolder = "/home/pi/PiCamNN/" #The folder which contains main script (picam.py)
num_cam = -1 #Number of the camera (if -1 it will be the first camera read by the system)
frame_check = 17 #Frames to check before quit
time_chunck = 15 #Time to consider for a new action
telegram_user = "" #Your telegram user name so all the images will be sent to your telegram char with yourself
#IMAGES VARIABLES:
w = 0 #width
h = 0 #height
#Image processing vars:
blur1 = 2
blur2 = 1
erodeval = 7
#Volatile arrays:
frames = []
times = []
#General Log file
flog = open(baseFolder+"logs","a")
'''
---# END #---
'''
#when an error occur
def printExit(out):
print(out,"\nClosing....!")
exit(-1)
#Updating index.html :
# 1 Opening index.html
# 2 Adding new link for the new video
# 3 If there are more then maxDays links removing oldest one
# 4 Removing also the oldest video
def handleFile(name):
print("[PiCamNN] Updating file...")
f = open(baseFolder+"index.html","r")
cont = f.read()
f.close()
if cont.find(name) != -1:
print("[PiCamNN] File has been update yet !")
return False
f = open(baseFolder+"index.html","w")
lines = cont.split("\n")
day = 0
go = False
for i in range(len(lines)-1):
if lines[i].find("<!-- S -->") != -1:
i += 1
f.write("<!-- S -->\n <a href=\"{}.avi\" class=\"file\" >{}.avi</a><br />\n".format(name,name))
day += 1
go = True
elif lines[i].find("<!-- E -->") != -1:
f.write("{}\n".format(lines[i]))
go = False
if day > maxDays:
rm = lines[i-1]
rm = rm[rm.find("\"")+1:len(rm)]
rm = rm[0:rm.find("\"")]
try:
system("rm {}".format(baseFolder+rm))
print("[PiCamNN] Old file removed.")
except:
print("[PiCamNN] An error occured while removing old file!")
elif go:
day +=1
if day <= maxDays:f.write("{}\n".format(lines[i]))
else:f.write("{}\n".format(lines[i]))
f.close()
print("[PiCamNN] index.html UPDATED")
return True
# Some morphological operations on two input frames to check for movements
def movement(mat_1,mat_2):
mat_1_gray = cv2.cvtColor(mat_1.copy(),cv2.COLOR_BGR2GRAY)
mat_1_gray = cv2.blur(mat_1_gray,(blur1,blur1))
_,mat_1_gray = cv2.threshold(mat_1_gray,100,255,0)
mat_2_gray = cv2.cvtColor(mat_2.copy(),cv2.COLOR_BGR2GRAY)
mat_2_gray = cv2.blur(mat_2_gray,(blur1,blur1))
_,mat_2_gray = cv2.threshold(mat_2_gray,100,255,0)
mat_2_gray = cv2.bitwise_xor(mat_1_gray,mat_2_gray)
mat_2_gray = cv2.blur(mat_2_gray,(blur2,blur2))
_,mat_2_gray = cv2.threshold(mat_2_gray,70,255,0)
mat_2_gray = cv2.erode(mat_2_gray,np.ones((erodeval,erodeval)))
mat_2_gray = cv2.dilate(mat_2_gray,np.ones((4,4)))
_, contours,__ = cv2.findContours(mat_2_gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:return True #If there were any movements
return False #if not
#Pedestrian Recognition Thread
def yoloThread():
global frames,times
model_path = scriptFolder+"tiny.h5" #Model weights
sess = K.get_session()
print("[PiCam] Loading anchors file...")
anchors = [1.08,1.19,3.42,4.41,6.63,11.38,9.42,5.11,16.62,10.52] #Tiny Yolo anchors' values
anchors = np.array(anchors).reshape(-1, 2)
print("[PiCam] Loading yolo model ({})...".format(scriptFolder+"tiny.h5"))
yolo_model = load_model(model_path) #Loading Tiny YOLO
num_anchors = len(anchors)
print('[PiCam] YOLO model loaded !'.format(model_path))
model_image_size = yolo_model.layers[0].input_shape[1:3] #Get input shape
yolo_outputs = yolo_head(yolo_model.output, anchors, 20)
input_image_shape = K.placeholder(shape=(2, ))
boxes, scores, classes = yolo_eval(yolo_outputs,input_image_shape,score_threshold=0.3,iou_threshold=0.4)
num = 0 #Starting Photo's name
old_time = 0.0 #Latest time
print("[PiCam] YOLO Thread started!")
### Loop:
while True:
if len(frames) != 0:
try:
cv2.waitKey(17)
mat = frames[0] #Get First frame with movements
mat = cv2.resize(mat,(model_image_size[0],model_image_size[1]))
in_mat = np.array(mat,dtype='float32')
in_mat /= 255. #Removing mean
in_mat = np.expand_dims(in_mat, 0)
if (times[0] - old_time) > time_chunck:
#Searching for detection:
out_boxes, out_scores, out_classes = sess.run([boxes, scores, classes],feed_dict={yolo_model.input: in_mat,input_image_shape: [mat.shape[1], mat.shape[0]],K.learning_phase(): 0})
if len(out_boxes) > 0:
writ = False
xs,ys = [],[] #X's and Y's coordinate
for i, c in reversed(list(enumerate(out_classes))):
if c == 14: #14 is the label for persons
writ = True
box = out_boxes[i]
top, left, bottom, right = box
top = max(0, np.floor(top + 0.5).astype('int32'))
left = max(0, np.floor(left + 0.5).astype('int32'))
bottom = min(mat.shape[1], np.floor(bottom + 0.5).astype('int32'))
right = min(mat.shape[0], np.floor(right + 0.5).astype('int32'))
xs.append(left+i)
xs.append(right-i)
ys.append(top+i)
ys.append(bottom-i)
if writ:
img_name = scriptFolder+"imgs/{}.png".format(num)
cv2.imwrite(img_name,mat[min(ys):max(ys),min(xs):max(xs)]) #Only saving the rectangle in which persons' got detected
out_s = "[{}] Detected person (taken {}s)!\n".format(time.strftime("%H:%M:%S"),round(time.time()-times[0])) #Log output
print(out_s)
flog.write(out_s)
flog.flush()
try: #Preventig Problems like no connection #I've used subprocess to set a timeout
subprocess.call("telegram-cli -W -e \'send_photo {} {} \' ".format(telegram_user,img_name),timeout=30,shell=True)
except Exception as exc:
print("[PiCam] Some error occured in YOLO Thread ({}) :".format(time.strftime("%H:%M:%S")),exc)
num += 1
old_time = times[0] #Updating detection time
except Exception as ex:
print("[PiCam] Some error occured in YOLO Thread ({}) :".format(time.strftime("%H:%M:%S")),ex)
del times[0] #Deleting first Detection time
del frames[0] #Deleting first Frame
cv2.waitKey(50)
'''
Main code from here :
'''
if __name__ == "__main__":
print("Starting PiCam....")
name = time.strftime("%c").replace(" ","_")[0:10]
#Camera Input
cap = None
try:
cap = cv2.VideoCapture(num_cam) #Trying to open camera
_,dim = cap.read()
if not _ or dim.shape == (0,0,0) :
printExit("[PiCam] Error occured when opening the camera stream!")
h = dim.shape[0]
w = dim.shape[1]
print("[PiCam] Height:{} | Width:{}".format(h,w))
except:
printExit("[PiCam] Error occured when opening the camera stream!")
#Video Output
writer = None
err = "[PiCam] Error occured when opening the output video stream!"
load = handleFile(name) #Updating web_file
if not load:system("mv {}.avi {}_.avi".format(baseFolder+name,baseFolder+name))
writer = cv2.VideoWriter(baseFolder+name+".avi", cv2.VideoWriter_fourcc(*"MJPG"), 21,(w,h), True)
if not writer.isOpened():
printExit(err) #If output Stream is unavailable
#Loading video file of the same day:
if not load:
try:
print("[PiCam] Loading old video File...",end="")
read = cv2.VideoCapture(baseFolder+name+"_.avi")
_,mat = read.read()
while _ :
if mat.shape == (0,0,0) or mat.shape[0] != h or mat.shape[1] != w:
print("[PiCam] Couldn't load old file skipping(shape {})...!".format(mat.shape))
break
writer.write(mat)
_,mat = read.read()
del read,mat
print("loaded!")
except:
print("\n[PiCam] Couldn't load old file skipping...!")
system("rm {}_.avi".format(baseFolder+name)) #Removing old video file
#Starting Yolo thread
yoloThread = threading.Thread(target=yoloThread)
print("[PiCam] Starting Yolo Thread....")
yoloThread.start()
day = time.strftime("%d") #startin' day
frc = 0 #Frame count
#Loop's start
print("[PiCam] Starting main loop...")
while True:
try:
_,a = cap.read()
if a.shape == (0,0,0):
#If Frame was empty trying frame_check times and then breaking program
for i in range(frame_check):
_,a = cap.read()
if a.shape != (0,0,0):break
if i == frame_check-1:printExit("[PiCam] Error with camera stream!")
cv2.waitKey(33)
_,b = cap.read()
move = movement(a,b)
#if we have got a movement
if move:
print("[PiCam] Movement ({})".format(time.strftime("%H:%M:%S")))
if frc % 2 == 0: #Only each two frames with movement are passed to YOLO Thread
frames.append(b.copy()) #Frame with movement
times.append(time.time())#Detection Time
frc += 1 #FrameCount +1
cv2.putText(b,name.replace("_"," ")+" "+time.strftime("%H:%M:%S"),(50,h - 50),cv2.FONT_HERSHEY_SIMPLEX, 2,(255,255,255))
writer.write(cv2.resize(b,(w,h))) #Adding to File
if time.strftime("%d") != day:
writer.release() #Closing old video output
frc = 0
print("[PiCam] Cleaning imgs dir...")
system("rm {}".format(scriptFolder+"imgs/*"))
#Handling FLOG:
flog.close()
system("echo '### PiCam Live Logs###' > {}".format(baseFolder+"logs")) #Cleaning Logs file
flog = open(baseFolder+"logs","a")
#FLOG end
print("[PiCam] New day! Restarting video output....")
name = time.strftime("%c").replace(" ","_")[0:10]
writer = cv2.VideoWriter(baseFolder+name+".avi", cv2.VideoWriter_fourcc(*"MJPG"), 21,(w,h), True)
print("[PiCam] Updating index.html...")
handleFile(name)
day = time.strftime("%d")
print("[PiCam] Done! Resuming main loop...")
except Exception as ex:
print("Some error occured : ",ex)
sys.exit(-1)
| [
"keras.models.load_model",
"cv2.VideoWriter_fourcc",
"numpy.floor",
"time.strftime",
"numpy.ones",
"yad2k.models.keras_yolo.yolo_eval",
"keras.backend.placeholder",
"yad2k.models.keras_yolo.yolo_head",
"cv2.resize",
"threading.Thread",
"cv2.bitwise_xor",
"keras.backend.learning_phase",
"cv2.... | [((1160, 1168), 'sys.exit', 'exit', (['(-1)'], {}), '(-1)\n', (1164, 1168), False, 'from sys import exit\n'), ((2885, 2921), 'cv2.blur', 'cv2.blur', (['mat_1_gray', '(blur1, blur1)'], {}), '(mat_1_gray, (blur1, blur1))\n', (2893, 2921), False, 'import cv2\n'), ((2941, 2979), 'cv2.threshold', 'cv2.threshold', (['mat_1_gray', '(100)', '(255)', '(0)'], {}), '(mat_1_gray, 100, 255, 0)\n', (2954, 2979), False, 'import cv2\n'), ((3065, 3101), 'cv2.blur', 'cv2.blur', (['mat_2_gray', '(blur1, blur1)'], {}), '(mat_2_gray, (blur1, blur1))\n', (3073, 3101), False, 'import cv2\n'), ((3121, 3159), 'cv2.threshold', 'cv2.threshold', (['mat_2_gray', '(100)', '(255)', '(0)'], {}), '(mat_2_gray, 100, 255, 0)\n', (3134, 3159), False, 'import cv2\n'), ((3178, 3217), 'cv2.bitwise_xor', 'cv2.bitwise_xor', (['mat_1_gray', 'mat_2_gray'], {}), '(mat_1_gray, mat_2_gray)\n', (3193, 3217), False, 'import cv2\n'), ((3238, 3274), 'cv2.blur', 'cv2.blur', (['mat_2_gray', '(blur2, blur2)'], {}), '(mat_2_gray, (blur2, blur2))\n', (3246, 3274), False, 'import cv2\n'), ((3294, 3331), 'cv2.threshold', 'cv2.threshold', (['mat_2_gray', '(70)', '(255)', '(0)'], {}), '(mat_2_gray, 70, 255, 0)\n', (3307, 3331), False, 'import cv2\n'), ((3481, 3549), 'cv2.findContours', 'cv2.findContours', (['mat_2_gray', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(mat_2_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (3497, 3549), False, 'import cv2\n'), ((3806, 3821), 'keras.backend.get_session', 'K.get_session', ([], {}), '()\n', (3819, 3821), True, 'from keras import backend as K\n'), ((4127, 4149), 'keras.models.load_model', 'load_model', (['model_path'], {}), '(model_path)\n', (4137, 4149), False, 'from keras.models import load_model\n'), ((4365, 4406), 'yad2k.models.keras_yolo.yolo_head', 'yolo_head', (['yolo_model.output', 'anchors', '(20)'], {}), '(yolo_model.output, anchors, 20)\n', (4374, 4406), False, 'from yad2k.models.keras_yolo import yolo_eval, yolo_head\n'), ((4432, 4457), 'keras.backend.placeholder', 'K.placeholder', ([], {'shape': '(2,)'}), '(shape=(2,))\n', (4445, 4457), True, 'from keras import backend as K\n'), ((4488, 4574), 'yad2k.models.keras_yolo.yolo_eval', 'yolo_eval', (['yolo_outputs', 'input_image_shape'], {'score_threshold': '(0.3)', 'iou_threshold': '(0.4)'}), '(yolo_outputs, input_image_shape, score_threshold=0.3,\n iou_threshold=0.4)\n', (4497, 4574), False, 'from yad2k.models.keras_yolo import yolo_eval, yolo_head\n'), ((9550, 9585), 'threading.Thread', 'threading.Thread', ([], {'target': 'yoloThread'}), '(target=yoloThread)\n', (9566, 9585), False, 'import threading\n'), ((9667, 9686), 'time.strftime', 'time.strftime', (['"""%d"""'], {}), "('%d')\n", (9680, 9686), False, 'import time\n'), ((3371, 3400), 'numpy.ones', 'np.ones', (['(erodeval, erodeval)'], {}), '((erodeval, erodeval))\n', (3378, 3400), True, 'import numpy as np\n'), ((3444, 3459), 'numpy.ones', 'np.ones', (['(4, 4)'], {}), '((4, 4))\n', (3451, 3459), True, 'import numpy as np\n'), ((7733, 7748), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (7744, 7748), False, 'import cv2\n'), ((7946, 7971), 'cv2.VideoCapture', 'cv2.VideoCapture', (['num_cam'], {}), '(num_cam)\n', (7962, 7971), False, 'import cv2\n'), ((8628, 8659), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (8650, 8659), False, 'import cv2\n'), ((3998, 4015), 'numpy.array', 'np.array', (['anchors'], {}), '(anchors)\n', (4006, 4015), True, 'import numpy as np\n'), ((8911, 8956), 'cv2.VideoCapture', 'cv2.VideoCapture', (["(baseFolder + name + '_.avi')"], {}), "(baseFolder + name + '_.avi')\n", (8927, 8956), False, 'import cv2\n'), ((10195, 10210), 'cv2.waitKey', 'cv2.waitKey', (['(33)'], {}), '(33)\n', (10206, 10210), False, 'import cv2\n'), ((4766, 4781), 'cv2.waitKey', 'cv2.waitKey', (['(17)'], {}), '(17)\n', (4777, 4781), False, 'import cv2\n'), ((4869, 4928), 'cv2.resize', 'cv2.resize', (['mat', '(model_image_size[0], model_image_size[1])'], {}), '(mat, (model_image_size[0], model_image_size[1]))\n', (4879, 4928), False, 'import cv2\n'), ((4952, 4982), 'numpy.array', 'np.array', (['mat'], {'dtype': '"""float32"""'}), "(mat, dtype='float32')\n", (4960, 4982), True, 'import numpy as np\n'), ((5054, 5079), 'numpy.expand_dims', 'np.expand_dims', (['in_mat', '(0)'], {}), '(in_mat, 0)\n', (5068, 5079), True, 'import numpy as np\n'), ((7851, 7870), 'time.strftime', 'time.strftime', (['"""%c"""'], {}), "('%c')\n", (7864, 7870), False, 'import time\n'), ((10898, 10917), 'time.strftime', 'time.strftime', (['"""%d"""'], {}), "('%d')\n", (10911, 10917), False, 'import time\n'), ((11742, 11761), 'time.strftime', 'time.strftime', (['"""%d"""'], {}), "('%d')\n", (11755, 11761), False, 'import time\n'), ((10845, 10866), 'cv2.resize', 'cv2.resize', (['b', '(w, h)'], {}), '(b, (w, h))\n', (10855, 10866), False, 'import cv2\n'), ((11582, 11613), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (11604, 11613), False, 'import cv2\n'), ((10387, 10412), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (10400, 10412), False, 'import time\n'), ((10611, 10622), 'time.time', 'time.time', ([], {}), '()\n', (10620, 10622), False, 'import time\n'), ((10735, 10760), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (10748, 10760), False, 'import time\n'), ((7587, 7612), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (7600, 7612), False, 'import time\n'), ((11474, 11493), 'time.strftime', 'time.strftime', (['"""%c"""'], {}), "('%c')\n", (11487, 11493), False, 'import time\n'), ((5357, 5375), 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (5373, 5375), True, 'from keras import backend as K\n'), ((6728, 6753), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (6741, 6753), False, 'import time\n'), ((6760, 6771), 'time.time', 'time.time', ([], {}), '()\n', (6769, 6771), False, 'import time\n'), ((5872, 5891), 'numpy.floor', 'np.floor', (['(top + 0.5)'], {}), '(top + 0.5)\n', (5880, 5891), True, 'import numpy as np\n'), ((5955, 5975), 'numpy.floor', 'np.floor', (['(left + 0.5)'], {}), '(left + 0.5)\n', (5963, 5975), True, 'import numpy as np\n'), ((6052, 6074), 'numpy.floor', 'np.floor', (['(bottom + 0.5)'], {}), '(bottom + 0.5)\n', (6060, 6074), True, 'import numpy as np\n'), ((6150, 6171), 'numpy.floor', 'np.floor', (['(right + 0.5)'], {}), '(right + 0.5)\n', (6158, 6171), True, 'import numpy as np\n'), ((7329, 7354), 'time.strftime', 'time.strftime', (['"""%H:%M:%S"""'], {}), "('%H:%M:%S')\n", (7342, 7354), False, 'import time\n')] |
import os
import json
import argparse
import numpy as np
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-emb', '--emb_dir', required=True, type=str, help='path to the input dir')
parser.add_argument('-dict', '--dict_dir', required=True, type=str, help='path to the input dir')
parser.add_argument('-ent_vocab', '--ent_vocab', required=True, type=str, help='path to the input dir')
parser.add_argument('-rel_vocab', '--rel_vocab', required=True, type=str, help='path to the input dir')
parser.add_argument('-o', '--output_dir', required=True, type=str, help='path to the output dir')
opt = vars(parser.parse_args())
num_ents = 54865939
num_rels = 10024
emb_dim = 50
scale = 0.1
# Relation
rel2id = {}
with open(os.path.join(opt['dict_dir'], 'relation2id.txt'), 'r') as f:
f.readline()
for line in f:
rel, id_ = line.split('\t')
rel = '/' + rel.replace('.', '/')
rel2id[rel] = id_
rel2vec = np.memmap(os.path.join(opt['emb_dir'], 'relation2vec.bin'), dtype='float32', mode='r', shape=(num_rels, emb_dim))
rel_vocab = json.load(open(opt['rel_vocab'], 'r'))
hit_ratio = 0
with open(os.path.join(opt['output_dir'], 'rel_emb.ndjson'), 'w') as f:
for rel in rel_vocab:
if rel in rel2id and int(rel2id[rel]) < len(rel2vec):
emb = rel2vec[int(rel2id[rel])]
hit_ratio += 1
else:
emb = np.array(np.random.uniform(low=-scale, high=scale, size=(emb_dim,)), dtype=np.float32)
# f.write(json.dumps({'id':rel, 'vec':emb.tolist()}) + '\n')
f.write(json.dumps({rel:emb.tolist()}) + '\n')
print('hit_ratio: {}'.format(hit_ratio / len(rel_vocab)))
# Entity
ent2id = {}
with open(os.path.join(opt['dict_dir'], 'entity2id.txt'), 'r') as f:
f.readline()
for line in f:
ent, id_ = line.split('\t')
ent = '/' + ent.replace('.', '/')
ent2id[ent] = id_
ent2vec = np.memmap(os.path.join(opt['emb_dir'], 'entity2vec.bin'), dtype='float32', mode='r', shape=(num_ents, emb_dim))
ent_vocab = json.load(open(opt['ent_vocab'], 'r'))
hit_ratio = 0
with open(os.path.join(opt['output_dir'], 'ent_emb.ndjson'), 'w') as f:
for ent in ent_vocab:
if ent in ent2id and int(ent2id[ent]) < len(ent2vec):
emb = ent2vec[int(ent2id[ent])]
hit_ratio += 1
else:
emb = np.array(np.random.uniform(low=-scale, high=scale, size=(emb_dim,)), dtype=np.float32)
# f.write(json.dumps({'id':ent, 'vec':emb.tolist()}) + '\n')
f.write(json.dumps({ent:emb.tolist()}) + '\n')
print('hit_ratio: {}'.format(hit_ratio / len(ent_vocab)))
| [
"numpy.random.uniform",
"os.path.join",
"argparse.ArgumentParser"
] | [((100, 125), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (123, 125), False, 'import argparse\n'), ((1052, 1100), 'os.path.join', 'os.path.join', (["opt['emb_dir']", '"""relation2vec.bin"""'], {}), "(opt['emb_dir'], 'relation2vec.bin')\n", (1064, 1100), False, 'import os\n'), ((2091, 2137), 'os.path.join', 'os.path.join', (["opt['emb_dir']", '"""entity2vec.bin"""'], {}), "(opt['emb_dir'], 'entity2vec.bin')\n", (2103, 2137), False, 'import os\n'), ((807, 855), 'os.path.join', 'os.path.join', (["opt['dict_dir']", '"""relation2id.txt"""'], {}), "(opt['dict_dir'], 'relation2id.txt')\n", (819, 855), False, 'import os\n'), ((1244, 1293), 'os.path.join', 'os.path.join', (["opt['output_dir']", '"""rel_emb.ndjson"""'], {}), "(opt['output_dir'], 'rel_emb.ndjson')\n", (1256, 1293), False, 'import os\n'), ((1848, 1894), 'os.path.join', 'os.path.join', (["opt['dict_dir']", '"""entity2id.txt"""'], {}), "(opt['dict_dir'], 'entity2id.txt')\n", (1860, 1894), False, 'import os\n'), ((2281, 2330), 'os.path.join', 'os.path.join', (["opt['output_dir']", '"""ent_emb.ndjson"""'], {}), "(opt['output_dir'], 'ent_emb.ndjson')\n", (2293, 2330), False, 'import os\n'), ((1530, 1588), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-scale)', 'high': 'scale', 'size': '(emb_dim,)'}), '(low=-scale, high=scale, size=(emb_dim,))\n', (1547, 1588), True, 'import numpy as np\n'), ((2567, 2625), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-scale)', 'high': 'scale', 'size': '(emb_dim,)'}), '(low=-scale, high=scale, size=(emb_dim,))\n', (2584, 2625), True, 'import numpy as np\n')] |
import numpy as np
from pathlib import Path
import pandas as pd
from grid_simulations import MacroGen
if __name__ == "__main__":
np.random.seed(65432)
macgen = MacroGen()
macgen._base_geometry_cmd = "/control/execute setup_normal_run.mac"
macgen.run_macs = [#"run696keV.mac",
# "run1779keV.mac", "run2838keV.mac",
"runEx4617keV.mac",
"run4440keV.mac"
]
# print(macgen.run())
# nominal thicknesses in cm
dnominal = {'front': 0.2, 'radial': 0.1, 'reflector': 0.1,
'lidhalf': 0.1, 'det': 16}
dthick = {'front': 0.2, 'radial': 0.1, 'reflector': 0.1,
'lidhalf': 0.2, 'det': 16}
dsaintgb = {'front': 0.08, 'radial': 0.08, 'reflector': 0.22,
'lidhalf': 0.1, 'det': 16}
grid = [dnominal, dthick, dsaintgb]
print("Items to calculate: ", len(grid))
fnbase = Path("inbeam_grid_macs")
fnbase.mkdir(exist_ok=True)
for i, pars in enumerate(grid):
# print(f"Simulating gridpoint {i}")
dtmp = pars
macgen.outname_base = f"inbeam_grid_{i}_"
macgen.dgeometry = dtmp
macro = macgen.save(fnbase / f"grid_{i}.mac")
# create summary file with commands to run
# due to concerns on calculation time we may not calculate all values,
# but start with a random selection
indices = np.arange(len(grid))
# np.random.shuffle(indices)
cmds = [f"./OCL inbeam_grid_macs/grid_{i}.mac" for i in indices]
cmd_string = "\n".join(*[cmds])
fn_sum = Path("inbeam_grid_cmd_all.txt")
fn_sum.write_text(cmd_string)
# grid_out = np.column_stack((np.arange(len(grid)), grid))
# grid_out = pd.DataFrame(grid_out, columns=["grid_point", *dnominal.keys()])
# grid_out = grid_out.astype({"grid_point": 'int'}, copy=False)
# grid_out.to_pickle("inbeam_grid_inbeam.pickle")
| [
"pathlib.Path",
"numpy.random.seed",
"grid_simulations.MacroGen"
] | [((135, 156), 'numpy.random.seed', 'np.random.seed', (['(65432)'], {}), '(65432)\n', (149, 156), True, 'import numpy as np\n'), ((170, 180), 'grid_simulations.MacroGen', 'MacroGen', ([], {}), '()\n', (178, 180), False, 'from grid_simulations import MacroGen\n'), ((939, 963), 'pathlib.Path', 'Path', (['"""inbeam_grid_macs"""'], {}), "('inbeam_grid_macs')\n", (943, 963), False, 'from pathlib import Path\n'), ((1584, 1615), 'pathlib.Path', 'Path', (['"""inbeam_grid_cmd_all.txt"""'], {}), "('inbeam_grid_cmd_all.txt')\n", (1588, 1615), False, 'from pathlib import Path\n')] |
import numpy as np
class LPSolver:
"""Class for solving labeling problem on given graph."""
def __init__(self, graph):
self.graph = graph
self.labels = np.zeros(self.graph.vertex_weights.shape)
def solve(self):
"""Returns graph labeling (in our case sequence of letters) that minimizes
the path weight, and the minimum path weight itself."""
for i in np.arange(1, self.graph.objects_number):
for char in self.graph.mapping:
char_width = self.graph.alphabet[self.graph.mapping[char]].shape[1]
path_weights = self.graph.vertex_weights[i - char_width, :] + \
self.graph.edge_weights[i - char_width, i, :, char]
self.graph.vertex_weights[i, char] = np.min(path_weights)
self.labels[i, char] = np.argmin(path_weights)
result = ''
i = self.graph.objects_number - 1
while i > 0:
label = np.argmin(self.graph.vertex_weights[i, :])
result = self.graph.mapping[label] + result
i = i - self.graph.alphabet[self.graph.mapping[label]].shape[1]
min_path_weight = np.min(self.graph.vertex_weights[-1, :])
print('Minimum path weight: {}'.format(min_path_weight))
print('Recognized string: {}'.format(result))
return result, min_path_weight
| [
"numpy.min",
"numpy.zeros",
"numpy.arange",
"numpy.argmin"
] | [((179, 220), 'numpy.zeros', 'np.zeros', (['self.graph.vertex_weights.shape'], {}), '(self.graph.vertex_weights.shape)\n', (187, 220), True, 'import numpy as np\n'), ((407, 446), 'numpy.arange', 'np.arange', (['(1)', 'self.graph.objects_number'], {}), '(1, self.graph.objects_number)\n', (416, 446), True, 'import numpy as np\n'), ((1184, 1224), 'numpy.min', 'np.min', (['self.graph.vertex_weights[-1, :]'], {}), '(self.graph.vertex_weights[-1, :])\n', (1190, 1224), True, 'import numpy as np\n'), ((982, 1024), 'numpy.argmin', 'np.argmin', (['self.graph.vertex_weights[i, :]'], {}), '(self.graph.vertex_weights[i, :])\n', (991, 1024), True, 'import numpy as np\n'), ((793, 813), 'numpy.min', 'np.min', (['path_weights'], {}), '(path_weights)\n', (799, 813), True, 'import numpy as np\n'), ((854, 877), 'numpy.argmin', 'np.argmin', (['path_weights'], {}), '(path_weights)\n', (863, 877), True, 'import numpy as np\n')] |
import time
import threading
import os
import numpy as np
import zmq
import msgpack
import tensorflow as tf
from tensorflow.python.platform import test
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import resources
zmq_module = tf.load_op_library('./build/nvzmq_ops/kernel/nvzmq_ops.so')
zmq_op = zmq_module.nv_zmq
zmq_conn_handle = zmq_module.zmq_conn_handle
allowable_dtypes = {"uint8", "uint16", "int16", "int32", "float16", "float32", "float64"}
TADDR_ARGS = 'zrpull://127.0.0.1:5678'
ZMQ_HWM = 100
class TestZMQResourceHandle(test.TestCase):
def test_simple(self):
with self.session():
TADDR_VALID = 'zrpull://127.0.0.1:5555'
output = zmq_conn_handle(TADDR_VALID, ZMQ_HWM, 0)
resources.initialize_resources(resources.local_resources()).run()
# assertDTypeEqual not working for resource type. it trans tf.dtype to np.dtype and resource is incompatible with numpy
#self.assertDtypeEqual(output, dtypes.resource.as_numpy_type)
self.assertEqual(type(output.dtype), type(dtypes.resource))
def test_invalid_address_type(self):
INVALID_ADDR = 'localhost:8089'
with self.assertRaises(tf.errors.InvalidArgumentError):
with self.session():
zmq_conn_handle(INVALID_ADDR, ZMQ_HWM, 0).eval()
class TestZMQOpArguments(test.TestCase):
def test_no_arguments(self):
with self.assertRaises(TypeError):
zmq_op()
def test_invalid_type_format(self):
with self.assertRaises(TypeError):
zmq_op(handle=zmq_conn_handle(address=TADDR_ARGS, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=tf.int32)
def test_invalid_type_length(self):
with self.assertRaises(ValueError):
zmq_op(handle=zmq_conn_handle(address=TADDR_ARGS, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[])
def test_invalid_output_type(self):
with self.assertRaises(TypeError):
zmq_op(handle=zmq_conn_handle(address=TADDR_ARGS, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[tf.bool])
def test_valid_arguments(self):
zmq_layer = zmq_op(handle=zmq_conn_handle(address=TADDR_ARGS, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[tf.int32, tf.float32])
self.assertEqual(len(zmq_layer), 2)
self.assertEqual(type(zmq_layer[0]), tf.Tensor)
self.assertEqual(type(zmq_layer[1]), tf.Tensor)
self.assertEqual(zmq_layer[0].dtype, tf.int32)
self.assertEqual(zmq_layer[1].dtype, tf.float32)
self.assertEqual(zmq_layer[0].shape, tf.TensorShape(None))
self.assertEqual(zmq_layer[1].shape, tf.TensorShape(None))
class TestZMQOpParse(test.TestCase):
def send_msgs(socket, msgs, multipart = False):
if multipart:
socket.send_multipart(msgs)
else:
for msg in msgs:
socket.send(msg)
time.sleep(len(msg) / 1000)
# dlinput
def np2dict(a, parts=None, allow_float64=False):
"""Recursively convert numpy tensors in data structures to dictionaries."""
if isinstance(a, np.ndarray):
assert allow_float64 or a.dtype != np.dtype("float64")
dtype = str(a.dtype)
assert dtype in allowable_dtypes, dtype
if parts is None:
return dict(_shape=list(a.shape),
_dtype=dtype,
_data=a.tobytes())
else:
index = len(parts)
parts.append(a.tobytes())
return dict(_shape=list(a.shape),
_dtype=dtype,
_part=index)
elif isinstance(a, list):
return [TestZMQOpParse.np2dict(x, parts) for x in a]
elif isinstance(a, dict):
return {k: TestZMQOpParse.np2dict(v, parts) for k,v in a.items()}
else:
return a
def test_corrupt_msg_pack_data(self):
CORRUPT_ADDR = 'zrpull://127.0.0.1:5555'
TSENDER_ADDR_CORRUPT = 'tcp://127.0.0.1:5555'
ctx = zmq.Context(1)
socket = ctx.socket(zmq.PUSH)
try:
socket.bind(TSENDER_ADDR_CORRUPT)
tensor_msg = msgpack.packb([['garbage data']], use_bin_type=True)
thread = self.checkedThread(target=TestZMQOpParse.send_msgs, args=(socket, [tensor_msg]))
thread.start()
with self.assertRaises(tf.errors.DataLossError):
with self.session() as sess:
zmq_op(handle=zmq_conn_handle(address=CORRUPT_ADDR, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[tf.int32])[0].eval()
except Exception as e:
self.fail()
finally:
thread.join()
socket.close()
ctx.term()
'''
If no timeout setting, comment following two timeout tests
'''
# def test_timeout(self):
# TADDR_VALID = 'zrpull://127.0.0.1:5555'
# output = zmq_op(handle=zmq_conn_handle(), address=TADDR_VALID, types=[tf.float32, tf.int32])
# with self.assertRaises(tf.errors.CancelledError):
# with tf.Session() as sess:
# sess.run(output)
# def test_timeout_multithread(self):
# TADDR_VALID = 'zrpull://127.0.0.1:5555'
# handle = zmq_conn_handle()
# ops = []
# for i in range(2):
# ops.extend(zmq_op(handle=handle, address=TADDR_VALID, types=[tf.float32, tf.int32]))
# with self.assertRaises(tf.errors.CancelledError):
# with self.session() as sess:
# sess.run(tf.tuple(ops))
def test_single_op_valid(self):
TADDR_VALID = 'zrpull://127.0.0.1:5555'
TSENDER_ADDR_VALID = 'tcp://127.0.0.1:5555'
SINGLE_DATA = [44]
ctx = zmq.Context(1)
socket = ctx.socket(zmq.PUSH)
try:
socket.bind(TSENDER_ADDR_VALID)
tensor_data1 = np.arange(16, dtype=np.uint8).reshape((4,4))
tensor_data2 = np.array(SINGLE_DATA, dtype=np.int32)
tensor_data_list = [tensor_data1, tensor_data2]
packed = msgpack.dumps(TestZMQOpParse.np2dict(tensor_data_list))
thread = self.checkedThread(target=TestZMQOpParse.send_msgs, args=(socket, [packed]))
thread.start()
tensors = zmq_op(handle=zmq_conn_handle(address=TADDR_VALID, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[tf.uint8, tf.int32])
with self.session() as sess:
outputs = sess.run(tensors)
self.assertEqual(len(outputs), 2)
self.assertTrue(np.array_equal(outputs[0], np.arange(16, dtype=np.float32).reshape(4,4)))
self.assertTrue(np.array_equal(outputs[1], np.array(SINGLE_DATA, dtype=np.int32)))
except Exception as e:
self.fail()
finally:
thread.join()
socket.close()
ctx.term()
def test_multithread(self):
TADDR_VALID = 'zrpull://127.0.0.1:5556'
TSENDER_ADDR_VALID = 'tcp://127.0.0.1:5556'
NUM_THREAD= 4
try:
ctx = zmq.Context(1)
socket = ctx.socket(zmq.PUSH)
socket.bind(TSENDER_ADDR_VALID)
msgs = []
expected = []
for i in range(1, NUM_THREAD + 1):
tensor_data1 = np.arange(i*i, dtype=np.float32).reshape((i*i))
tensor_data2 = np.array([i], dtype=np.int32)
tensor_data3 = np.array([i], dtype=np.uint8)
tensor_data_list = [tensor_data1, tensor_data2, tensor_data3]
expected.append(tensor_data_list)
packed = msgpack.dumps(TestZMQOpParse.np2dict(tensor_data_list))
msgs.append(packed)
thread = self.checkedThread(target=TestZMQOpParse.send_msgs, args=(socket, msgs))
thread.start()
handle = zmq_conn_handle(address=TADDR_VALID, zmq_hwm=ZMQ_HWM, zmq_buff=0)
tensor_lists = []
for i in range(NUM_THREAD):
tensors = zmq_op(handle=handle, types=[tf.float32, tf.int32, tf.uint8])
tensor_lists.append(tensors)
with self.session() as sess:
# Writing a graph on tensorboard
# cwd = os.getcwd()
# writer = tf.summary.FileWriter(cwd + '/tfboardlogs/', sess.graph)
output = sess.run(tensor_lists)
self.assertEqual(len(output), len(expected))
output.sort(key=lambda x: (x[0].shape[0]))
for a, b in zip(output, expected):
for x, y in zip(a, b):
self.assertAllEqual(x, y)
# writer.close()
except Exception as e:
self.fail()
finally:
thread.join()
socket.close()
ctx.term()
def test_multipart(self):
TADDR_VALID = 'zrpull://127.0.0.1:5555'
TSENDER_ADDR_VALID = 'tcp://127.0.0.1:5555'
SINGLE_DATA = [44]
ctx = zmq.Context(1)
socket = ctx.socket(zmq.PUSH)
try:
socket.bind(TSENDER_ADDR_VALID)
tensor_data1 = np.arange(16, dtype=np.uint8).reshape((4,4))
tensor_data2 = np.array(SINGLE_DATA, dtype=np.int32)
tensor_data_list = [tensor_data1, tensor_data2]
parts = [None]
packed = msgpack.dumps(TestZMQOpParse.np2dict(tensor_data_list, parts))
parts[0] = packed
thread = self.checkedThread(target=TestZMQOpParse.send_msgs, args=(socket, parts, True))
thread.start()
tensors = zmq_op(handle=zmq_conn_handle(address=TADDR_VALID, zmq_hwm=ZMQ_HWM, zmq_buff=0), types=[tf.uint8, tf.int32])
with self.session() as sess:
outputs = sess.run(tensors)
self.assertEqual(len(outputs), 2)
self.assertTrue(np.array_equal(outputs[0], np.arange(16, dtype=np.float32).reshape(4,4)))
self.assertTrue(np.array_equal(outputs[1], np.array(SINGLE_DATA, dtype=np.int32)))
except Exception as e:
self.fail()
finally:
thread.join()
socket.close()
ctx.term()
if __name__ == '__main__':
test.main()
| [
"tensorflow.load_op_library",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.resources.local_resources",
"numpy.dtype",
"tensorflow.TensorShape",
"numpy.array",
"numpy.arange",
"msgpack.packb",
"zmq.Context"
] | [((260, 319), 'tensorflow.load_op_library', 'tf.load_op_library', (['"""./build/nvzmq_ops/kernel/nvzmq_ops.so"""'], {}), "('./build/nvzmq_ops/kernel/nvzmq_ops.so')\n", (278, 319), True, 'import tensorflow as tf\n'), ((8575, 8586), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (8584, 8586), False, 'from tensorflow.python.platform import test\n'), ((3515, 3529), 'zmq.Context', 'zmq.Context', (['(1)'], {}), '(1)\n', (3526, 3529), False, 'import zmq\n'), ((4944, 4958), 'zmq.Context', 'zmq.Context', (['(1)'], {}), '(1)\n', (4955, 4958), False, 'import zmq\n'), ((7553, 7567), 'zmq.Context', 'zmq.Context', (['(1)'], {}), '(1)\n', (7564, 7567), False, 'import zmq\n'), ((2332, 2352), 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), '(None)\n', (2346, 2352), True, 'import tensorflow as tf\n'), ((2393, 2413), 'tensorflow.TensorShape', 'tf.TensorShape', (['None'], {}), '(None)\n', (2407, 2413), True, 'import tensorflow as tf\n'), ((3622, 3674), 'msgpack.packb', 'msgpack.packb', (["[['garbage data']]"], {'use_bin_type': '(True)'}), "([['garbage data']], use_bin_type=True)\n", (3635, 3674), False, 'import msgpack\n'), ((5114, 5151), 'numpy.array', 'np.array', (['SINGLE_DATA'], {'dtype': 'np.int32'}), '(SINGLE_DATA, dtype=np.int32)\n', (5122, 5151), True, 'import numpy as np\n'), ((6036, 6050), 'zmq.Context', 'zmq.Context', (['(1)'], {}), '(1)\n', (6047, 6050), False, 'import zmq\n'), ((7723, 7760), 'numpy.array', 'np.array', (['SINGLE_DATA'], {'dtype': 'np.int32'}), '(SINGLE_DATA, dtype=np.int32)\n', (7731, 7760), True, 'import numpy as np\n'), ((6273, 6302), 'numpy.array', 'np.array', (['[i]'], {'dtype': 'np.int32'}), '([i], dtype=np.int32)\n', (6281, 6302), True, 'import numpy as np\n'), ((6322, 6351), 'numpy.array', 'np.array', (['[i]'], {'dtype': 'np.uint8'}), '([i], dtype=np.uint8)\n', (6330, 6351), True, 'import numpy as np\n'), ((2841, 2860), 'numpy.dtype', 'np.dtype', (['"""float64"""'], {}), "('float64')\n", (2849, 2860), True, 'import numpy as np\n'), ((5051, 5080), 'numpy.arange', 'np.arange', (['(16)'], {'dtype': 'np.uint8'}), '(16, dtype=np.uint8)\n', (5060, 5080), True, 'import numpy as np\n'), ((7660, 7689), 'numpy.arange', 'np.arange', (['(16)'], {'dtype': 'np.uint8'}), '(16, dtype=np.uint8)\n', (7669, 7689), True, 'import numpy as np\n'), ((759, 786), 'tensorflow.python.ops.resources.local_resources', 'resources.local_resources', ([], {}), '()\n', (784, 786), False, 'from tensorflow.python.ops import resources\n'), ((5744, 5781), 'numpy.array', 'np.array', (['SINGLE_DATA'], {'dtype': 'np.int32'}), '(SINGLE_DATA, dtype=np.int32)\n', (5752, 5781), True, 'import numpy as np\n'), ((6206, 6240), 'numpy.arange', 'np.arange', (['(i * i)'], {'dtype': 'np.float32'}), '(i * i, dtype=np.float32)\n', (6215, 6240), True, 'import numpy as np\n'), ((8403, 8440), 'numpy.array', 'np.array', (['SINGLE_DATA'], {'dtype': 'np.int32'}), '(SINGLE_DATA, dtype=np.int32)\n', (8411, 8440), True, 'import numpy as np\n'), ((5650, 5681), 'numpy.arange', 'np.arange', (['(16)'], {'dtype': 'np.float32'}), '(16, dtype=np.float32)\n', (5659, 5681), True, 'import numpy as np\n'), ((8309, 8340), 'numpy.arange', 'np.arange', (['(16)'], {'dtype': 'np.float32'}), '(16, dtype=np.float32)\n', (8318, 8340), True, 'import numpy as np\n')] |
"""
Global configuration for the problem settings
"""
import numpy as np
from scipy import stats
horizon = 300
runs = 40
DefaultConfiguration = {
"price_buy" : [1.2,2.1,3.3],
"price_sell" : [1,2,3],
"price_probabilities" : np.array([[0.8, 0.1, 0.1],[0.1, 0.8, 0.1],[0.1, 0.1, 0.8]]),
"initial_capacity" : 1,
"initial_inventory" : 0.5,
"degradation" : {"fun":"polynomial","charge":[0.0,0,0.01],
"discharge":[0.01,-0.02,0.01] },
"capacity_cost" : 1,
"change_capacity" : False # assume that the capacity does not change
}
def construct_martingale(prices, variance):
"""
Constructs a definitions with a martingale definition of transition probabilities.
The change in price is modeled as a normal distribution with zero mean and
the specified variance.
The capacity of the battery does in fact change
Parameters
----------
prices : array
**Sell** prices that correspond to states in the Martingale price state
process. **Buy** prices are 10% higher.
variance : float
Variance of the normal distribution
Returns
-------
out : dict
Configuration that corresponds to the martingale
"""
states = len(prices)
# defines over how many states the probability is spread over
spread = min(5,states-1)
if type(prices) is not np.ndarray:
prices = np.array(prices)
# relative transition probabilities
p = stats.norm(0,variance).pdf(np.arange(-spread,spread+1))
p = p / p.sum()
# add extra 0s to both ends of p
p = np.concatenate((np.zeros(states-spread-1), p, np.zeros(states-spread-1)))
P = [p[states-i-1:2*states-i-1] for i in range(states)]
P = np.array(P)
P = np.diag(1/P.sum(1)).dot(P)
configuration = {
"price_buy" : 1.1 * prices,
"price_sell" : prices,
"price_probabilities" : P,
"initial_capacity" : 1,
"initial_inventory" : 0.5,
"degradation" : {"fun":"polynomial","charge":[0.0,0,0.01],
"discharge":[0.01,0.02,0.01] },
"capacity_cost" : 1,
"change_capacity" : True # assume that the capacity does not change
}
return configuration
def construct_massdata(degrade):
"""
Returns a problem definition on what is described in the experimental
section of the paper
This uses a simple uniform quantization of energy prices
Paramaters
----------
degrade : bool
Whether the battery degrades
"""
prices = np.array([25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0])
P = np.array([[ 8.15584416e-01, 1.76623377e-01, 5.19480519e-03,
2.59740260e-03, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00],
[ 4.70114171e-02, 8.72397582e-01, 7.25319006e-02,
7.38750839e-03, 0.00000000e+00, 6.71591672e-04,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00],
[ 1.19904077e-03, 1.31894484e-01, 7.79376499e-01,
6.95443645e-02, 1.43884892e-02, 3.59712230e-03,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00],
[ 0.00000000e+00, 4.24528302e-02, 2.83018868e-01,
5.14150943e-01, 1.22641509e-01, 2.35849057e-02,
9.43396226e-03, 0.00000000e+00, 0.00000000e+00,
4.71698113e-03],
[ 0.00000000e+00, 2.15053763e-02, 9.67741935e-02,
2.68817204e-01, 4.30107527e-01, 1.29032258e-01,
4.30107527e-02, 1.07526882e-02, 0.00000000e+00,
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 3.22580645e-02,
2.58064516e-01, 3.54838710e-01, 1.93548387e-01,
9.67741935e-02, 6.45161290e-02, 0.00000000e+00,
0.00000000e+00],
[ 0.00000000e+00, 7.14285714e-02, 1.42857143e-01,
0.00000000e+00, 7.14285714e-02, 2.14285714e-01,
2.85714286e-01, 1.42857143e-01, 7.14285714e-02,
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 1.42857143e-01,
0.00000000e+00, 2.85714286e-01, 0.00000000e+00,
0.00000000e+00, 2.85714286e-01, 2.85714286e-01,
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 2.50000000e-01, 2.50000000e-01,
2.50000000e-01, 0.00000000e+00, 2.50000000e-01,
0.00000000e+00],
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
1.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00]])
if degrade:
degradation = {"fun":"polynomial","charge" : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.00142857142857143],
"discharge" : [0.0, 0.00500000000000000, -0.00750000000000000, 0.00500000000000000, -0.00125000000000000] }
else:
degradation = {"fun":"polynomial","charge" : [0.0],
"discharge" : [0.0] }
configuration = {
"price_buy" : 1.05 * prices,
"price_sell" : 0.95 * prices,
"price_probabilities" : P,
"initial_capacity" : 1,
"initial_inventory" : 0.5,
"degradation" : degradation,
"capacity_cost" : 20000,
"change_capacity" : True
}
return configuration
| [
"numpy.zeros",
"scipy.stats.norm",
"numpy.array",
"numpy.arange"
] | [((238, 299), 'numpy.array', 'np.array', (['[[0.8, 0.1, 0.1], [0.1, 0.8, 0.1], [0.1, 0.1, 0.8]]'], {}), '([[0.8, 0.1, 0.1], [0.1, 0.8, 0.1], [0.1, 0.1, 0.8]])\n', (246, 299), True, 'import numpy as np\n'), ((1782, 1793), 'numpy.array', 'np.array', (['P'], {}), '(P)\n', (1790, 1793), True, 'import numpy as np\n'), ((2638, 2715), 'numpy.array', 'np.array', (['[25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0]'], {}), '([25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 250.0, 300.0])\n', (2646, 2715), True, 'import numpy as np\n'), ((2729, 3721), 'numpy.array', 'np.array', (['[[0.815584416, 0.176623377, 0.00519480519, 0.0025974026, 0.0, 0.0, 0.0, 0.0,\n 0.0, 0.0], [0.0470114171, 0.872397582, 0.0725319006, 0.00738750839, 0.0,\n 0.000671591672, 0.0, 0.0, 0.0, 0.0], [0.00119904077, 0.131894484, \n 0.779376499, 0.0695443645, 0.0143884892, 0.0035971223, 0.0, 0.0, 0.0, \n 0.0], [0.0, 0.0424528302, 0.283018868, 0.514150943, 0.122641509, \n 0.0235849057, 0.00943396226, 0.0, 0.0, 0.00471698113], [0.0, \n 0.0215053763, 0.0967741935, 0.268817204, 0.430107527, 0.129032258, \n 0.0430107527, 0.0107526882, 0.0, 0.0], [0.0, 0.0, 0.0322580645, \n 0.258064516, 0.35483871, 0.193548387, 0.0967741935, 0.064516129, 0.0, \n 0.0], [0.0, 0.0714285714, 0.142857143, 0.0, 0.0714285714, 0.214285714, \n 0.285714286, 0.142857143, 0.0714285714, 0.0], [0.0, 0.0, 0.142857143, \n 0.0, 0.285714286, 0.0, 0.0, 0.285714286, 0.285714286, 0.0], [0.0, 0.0, \n 0.0, 0.0, 0.25, 0.25, 0.25, 0.0, 0.25, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, \n 0.0, 1.0, 0.0, 0.0, 0.0]]'], {}), '([[0.815584416, 0.176623377, 0.00519480519, 0.0025974026, 0.0, 0.0,\n 0.0, 0.0, 0.0, 0.0], [0.0470114171, 0.872397582, 0.0725319006, \n 0.00738750839, 0.0, 0.000671591672, 0.0, 0.0, 0.0, 0.0], [0.00119904077,\n 0.131894484, 0.779376499, 0.0695443645, 0.0143884892, 0.0035971223, 0.0,\n 0.0, 0.0, 0.0], [0.0, 0.0424528302, 0.283018868, 0.514150943, \n 0.122641509, 0.0235849057, 0.00943396226, 0.0, 0.0, 0.00471698113], [\n 0.0, 0.0215053763, 0.0967741935, 0.268817204, 0.430107527, 0.129032258,\n 0.0430107527, 0.0107526882, 0.0, 0.0], [0.0, 0.0, 0.0322580645, \n 0.258064516, 0.35483871, 0.193548387, 0.0967741935, 0.064516129, 0.0, \n 0.0], [0.0, 0.0714285714, 0.142857143, 0.0, 0.0714285714, 0.214285714, \n 0.285714286, 0.142857143, 0.0714285714, 0.0], [0.0, 0.0, 0.142857143, \n 0.0, 0.285714286, 0.0, 0.0, 0.285714286, 0.285714286, 0.0], [0.0, 0.0, \n 0.0, 0.0, 0.25, 0.25, 0.25, 0.0, 0.25, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, \n 0.0, 1.0, 0.0, 0.0, 0.0]])\n', (2737, 3721), True, 'import numpy as np\n'), ((1444, 1460), 'numpy.array', 'np.array', (['prices'], {}), '(prices)\n', (1452, 1460), True, 'import numpy as np\n'), ((1541, 1571), 'numpy.arange', 'np.arange', (['(-spread)', '(spread + 1)'], {}), '(-spread, spread + 1)\n', (1550, 1571), True, 'import numpy as np\n'), ((1514, 1537), 'scipy.stats.norm', 'stats.norm', (['(0)', 'variance'], {}), '(0, variance)\n', (1524, 1537), False, 'from scipy import stats\n'), ((1651, 1680), 'numpy.zeros', 'np.zeros', (['(states - spread - 1)'], {}), '(states - spread - 1)\n', (1659, 1680), True, 'import numpy as np\n'), ((1681, 1710), 'numpy.zeros', 'np.zeros', (['(states - spread - 1)'], {}), '(states - spread - 1)\n', (1689, 1710), True, 'import numpy as np\n')] |
import streamlit as st
import pandas as pd
import numpy as np
import scipy.stats
from scipy.stats import norm
import altair as alt
st.set_page_config(
page_title="A/B Test Comparison", page_icon="📈", initial_sidebar_state="expanded"
)
def conversion_rate(conversions, visitors):
return (conversions / visitors) * 100
def lift(cra, crb):
return ((crb - cra) / cra) * 100
def std_err(cr, visitors):
return np.sqrt((cr / 100 * (1 - cr / 100)) / visitors)
def std_err_diff(sea, seb):
return np.sqrt(sea ** 2 + seb ** 2)
def z_score(cra, crb, error):
return ((crb - cra) / error) / 100
def p_value(z, hypothesis):
if hypothesis == "One-sided" and z < 0:
return 1 - norm().sf(z)
elif hypothesis == "One-sided" and z >= 0:
return norm().sf(z) / 2
else:
return norm().sf(z)
def significance(alpha, p):
return "YES" if p < alpha else "NO"
def plot_chart(df):
chart = (
alt.Chart(df)
.mark_bar(color="#61b33b")
.encode(
x=alt.X("Group:O", axis=alt.Axis(labelAngle=0)),
y=alt.Y("Conversion:Q", title="Conversion rate (%)"),
opacity="Group:O",
)
.properties(width=500, height=500)
)
chart_text = chart.mark_text(
align="center", baseline="middle", dy=-10, color="black"
).encode(text=alt.Text("Conversion:Q", format=",.3g"))
return st.altair_chart((chart + chart_text).interactive())
def style_negative(v, props=""):
return props if v < 0 else None
def style_p_value(v, props=""):
return np.where(v < st.session_state.alpha, "color:green;", props)
def calculate_significance(
conversions_a, conversions_b, visitors_a, visitors_b, hypothesis, alpha
):
st.session_state.cra = conversion_rate(int(conversions_a), int(visitors_a))
st.session_state.crb = conversion_rate(int(conversions_b), int(visitors_b))
st.session_state.uplift = lift(st.session_state.cra, st.session_state.crb)
st.session_state.sea = std_err(st.session_state.cra, float(visitors_a))
st.session_state.seb = std_err(st.session_state.crb, float(visitors_b))
st.session_state.sed = std_err_diff(st.session_state.sea, st.session_state.seb)
st.session_state.z = z_score(
st.session_state.cra, st.session_state.crb, st.session_state.sed
)
st.session_state.p = p_value(st.session_state.z, st.session_state.hypothesis)
st.session_state.significant = significance(
st.session_state.alpha, st.session_state.p
)
placeholder = st.empty()
placeholder.title("A/B Test Comparison")
with st.sidebar:
uploaded_file = st.file_uploader("Upload CSV", type=".csv")
if uploaded_file:
df = pd.read_csv(uploaded_file)
st.markdown("#### Data preview")
st.dataframe(df.head())
ab = st.multiselect("A/B column", options=df.columns)
if ab:
control = df[ab[0]].unique()[0]
treatment = df[ab[0]].unique()[1]
decide = st.radio(f"Is {treatment} Variant B?", options=["Yes", "No"])
if decide == "No":
control, treatment = treatment, control
visitors_a = df[ab[0]].value_counts()[control]
visitors_b = df[ab[0]].value_counts()[treatment]
result = st.multiselect("Result column", options=df.columns)
if result:
conversions_a = (
df[[ab[0], result[0]]].groupby(ab[0]).agg("sum")[result[0]][control]
)
conversions_b = (
df[[ab[0], result[0]]].groupby(ab[0]).agg("sum")[result[0]][treatment]
)
with st.sidebar.form("parameters"):
st.markdown("### Parameters")
st.radio(
"Hypothesis type",
options=["One-sided", "Two-sided"],
index=0,
key="hypothesis",
help="TBD",
)
st.slider(
"Significance level (α)",
min_value=0.01,
max_value=0.10,
value=0.05,
step=0.01,
key="alpha",
help=" The probability of mistakenly rejecting the null hypothesis, if the null hypothesis is true. This is also called false positive and type I error. ",
)
submit = st.form_submit_button("Apply changes", on_click=None)
if submit:
placeholder.empty() # Remove title
calculate_significance(
conversions_a,
conversions_b,
visitors_a,
visitors_b,
st.session_state.hypothesis,
st.session_state.alpha,
)
mcol1, mcol2 = st.beta_columns(2)
with mcol1:
st.metric(
"Delta",
value=f"{(st.session_state.crb - st.session_state.cra):.3g}%",
delta=f"{(st.session_state.crb - st.session_state.cra):.3g}%",
)
with mcol2:
st.metric("Significant?", value=st.session_state.significant)
results_df = pd.DataFrame(
{
"Group": ["Control", "Treatment"],
"Conversion": [st.session_state.cra, st.session_state.crb],
}
)
plot_chart(results_df)
table = pd.DataFrame(
{
"Converted": [conversions_a, conversions_b],
"Total": [visitors_a, visitors_b],
"% Converted": [st.session_state.cra, st.session_state.crb],
},
index=pd.Index(["Control", "Treatment"]),
)
st.write(table.style.format(formatter={("% Converted"): "{:.3g}%"}))
metrics = pd.DataFrame(
{
"p-value": [st.session_state.p],
"z-score": [st.session_state.z],
"uplift": [st.session_state.uplift],
},
index=pd.Index(["Metrics"]),
)
st.write(
metrics.style.format(
formatter={("p-value", "z-score"): "{:.3g}", ("uplift"): "{:.3g}%"}
)
.applymap(style_negative, props="color:red;")
.apply(style_p_value, props="color:red;", axis=1, subset=["p-value"])
)
| [
"pandas.read_csv",
"altair.Chart",
"streamlit.radio",
"altair.Text",
"streamlit.sidebar.form",
"pandas.DataFrame",
"streamlit.set_page_config",
"scipy.stats.norm",
"altair.Y",
"streamlit.metric",
"streamlit.beta_columns",
"streamlit.slider",
"streamlit.file_uploader",
"streamlit.form_submi... | [((132, 237), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""A/B Test Comparison"""', 'page_icon': '"""📈"""', 'initial_sidebar_state': '"""expanded"""'}), "(page_title='A/B Test Comparison', page_icon='📈',\n initial_sidebar_state='expanded')\n", (150, 237), True, 'import streamlit as st\n'), ((2536, 2546), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (2544, 2546), True, 'import streamlit as st\n'), ((427, 472), 'numpy.sqrt', 'np.sqrt', (['(cr / 100 * (1 - cr / 100) / visitors)'], {}), '(cr / 100 * (1 - cr / 100) / visitors)\n', (434, 472), True, 'import numpy as np\n'), ((516, 544), 'numpy.sqrt', 'np.sqrt', (['(sea ** 2 + seb ** 2)'], {}), '(sea ** 2 + seb ** 2)\n', (523, 544), True, 'import numpy as np\n'), ((1575, 1634), 'numpy.where', 'np.where', (['(v < st.session_state.alpha)', '"""color:green;"""', 'props'], {}), "(v < st.session_state.alpha, 'color:green;', props)\n", (1583, 1634), True, 'import numpy as np\n'), ((2627, 2670), 'streamlit.file_uploader', 'st.file_uploader', (['"""Upload CSV"""'], {'type': '""".csv"""'}), "('Upload CSV', type='.csv')\n", (2643, 2670), True, 'import streamlit as st\n'), ((3623, 3652), 'streamlit.sidebar.form', 'st.sidebar.form', (['"""parameters"""'], {}), "('parameters')\n", (3638, 3652), True, 'import streamlit as st\n'), ((3658, 3687), 'streamlit.markdown', 'st.markdown', (['"""### Parameters"""'], {}), "('### Parameters')\n", (3669, 3687), True, 'import streamlit as st\n'), ((3692, 3798), 'streamlit.radio', 'st.radio', (['"""Hypothesis type"""'], {'options': "['One-sided', 'Two-sided']", 'index': '(0)', 'key': '"""hypothesis"""', 'help': '"""TBD"""'}), "('Hypothesis type', options=['One-sided', 'Two-sided'], index=0,\n key='hypothesis', help='TBD')\n", (3700, 3798), True, 'import streamlit as st\n'), ((3846, 4119), 'streamlit.slider', 'st.slider', (['"""Significance level (α)"""'], {'min_value': '(0.01)', 'max_value': '(0.1)', 'value': '(0.05)', 'step': '(0.01)', 'key': '"""alpha"""', 'help': '""" The probability of mistakenly rejecting the null hypothesis, if the null hypothesis is true. This is also called false positive and type I error. """'}), "('Significance level (α)', min_value=0.01, max_value=0.1, value=\n 0.05, step=0.01, key='alpha', help=\n ' The probability of mistakenly rejecting the null hypothesis, if the null hypothesis is true. This is also called false positive and type I error. '\n )\n", (3855, 4119), True, 'import streamlit as st\n'), ((4182, 4235), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Apply changes"""'], {'on_click': 'None'}), "('Apply changes', on_click=None)\n", (4203, 4235), True, 'import streamlit as st\n'), ((4497, 4515), 'streamlit.beta_columns', 'st.beta_columns', (['(2)'], {}), '(2)\n', (4512, 4515), True, 'import streamlit as st\n'), ((4838, 4952), 'pandas.DataFrame', 'pd.DataFrame', (["{'Group': ['Control', 'Treatment'], 'Conversion': [st.session_state.cra, st\n .session_state.crb]}"], {}), "({'Group': ['Control', 'Treatment'], 'Conversion': [st.\n session_state.cra, st.session_state.crb]})\n", (4850, 4952), True, 'import pandas as pd\n'), ((2707, 2733), 'pandas.read_csv', 'pd.read_csv', (['uploaded_file'], {}), '(uploaded_file)\n', (2718, 2733), True, 'import pandas as pd\n'), ((2743, 2775), 'streamlit.markdown', 'st.markdown', (['"""#### Data preview"""'], {}), "('#### Data preview')\n", (2754, 2775), True, 'import streamlit as st\n'), ((2822, 2870), 'streamlit.multiselect', 'st.multiselect', (['"""A/B column"""'], {'options': 'df.columns'}), "('A/B column', options=df.columns)\n", (2836, 2870), True, 'import streamlit as st\n'), ((3284, 3335), 'streamlit.multiselect', 'st.multiselect', (['"""Result column"""'], {'options': 'df.columns'}), "('Result column', options=df.columns)\n", (3298, 3335), True, 'import streamlit as st\n'), ((4541, 4691), 'streamlit.metric', 'st.metric', (['"""Delta"""'], {'value': 'f"""{st.session_state.crb - st.session_state.cra:.3g}%"""', 'delta': 'f"""{st.session_state.crb - st.session_state.cra:.3g}%"""'}), "('Delta', value=\n f'{st.session_state.crb - st.session_state.cra:.3g}%', delta=\n f'{st.session_state.crb - st.session_state.cra:.3g}%')\n", (4550, 4691), True, 'import streamlit as st\n'), ((4758, 4819), 'streamlit.metric', 'st.metric', (['"""Significant?"""'], {'value': 'st.session_state.significant'}), "('Significant?', value=st.session_state.significant)\n", (4767, 4819), True, 'import streamlit as st\n'), ((1354, 1393), 'altair.Text', 'alt.Text', (['"""Conversion:Q"""'], {'format': '""",.3g"""'}), "('Conversion:Q', format=',.3g')\n", (1362, 1393), True, 'import altair as alt\n'), ((2997, 3058), 'streamlit.radio', 'st.radio', (['f"""Is {treatment} Variant B?"""'], {'options': "['Yes', 'No']"}), "(f'Is {treatment} Variant B?', options=['Yes', 'No'])\n", (3005, 3058), True, 'import streamlit as st\n'), ((5263, 5297), 'pandas.Index', 'pd.Index', (["['Control', 'Treatment']"], {}), "(['Control', 'Treatment'])\n", (5271, 5297), True, 'import pandas as pd\n'), ((5582, 5603), 'pandas.Index', 'pd.Index', (["['Metrics']"], {}), "(['Metrics'])\n", (5590, 5603), True, 'import pandas as pd\n'), ((709, 715), 'scipy.stats.norm', 'norm', ([], {}), '()\n', (713, 715), False, 'from scipy.stats import norm\n'), ((826, 832), 'scipy.stats.norm', 'norm', ([], {}), '()\n', (830, 832), False, 'from scipy.stats import norm\n'), ((1094, 1144), 'altair.Y', 'alt.Y', (['"""Conversion:Q"""'], {'title': '"""Conversion rate (%)"""'}), "('Conversion:Q', title='Conversion rate (%)')\n", (1099, 1144), True, 'import altair as alt\n'), ((784, 790), 'scipy.stats.norm', 'norm', ([], {}), '()\n', (788, 790), False, 'from scipy.stats import norm\n'), ((953, 966), 'altair.Chart', 'alt.Chart', (['df'], {}), '(df)\n', (962, 966), True, 'import altair as alt\n'), ((1055, 1077), 'altair.Axis', 'alt.Axis', ([], {'labelAngle': '(0)'}), '(labelAngle=0)\n', (1063, 1077), True, 'import altair as alt\n')] |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from unittest import mock
import numpy as np
import torch
from ax.models.torch.alebo import (
ALEBO,
ALEBOGP,
ALEBOKernel,
alebo_acqf_optimizer,
ei_or_nei,
extract_map_statedict,
get_batch_model,
get_fitted_model,
get_map_model,
)
from ax.utils.common.testutils import TestCase
from botorch.acquisition.analytic import ExpectedImprovement
from botorch.acquisition.monte_carlo import qNoisyExpectedImprovement
from botorch.models.model_list_gp_regression import ModelListGP
class ALEBOTest(TestCase):
def testALEBOKernel(self):
B = torch.tensor(
[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=torch.double
)
k = ALEBOKernel(B=B, batch_shape=torch.Size([]))
self.assertEqual(k.d, 2)
self.assertTrue(torch.equal(B, k.B))
self.assertTrue(
torch.equal(k.triu_indx[0], torch.tensor([0, 0, 1], dtype=torch.long))
)
self.assertTrue(
torch.equal(k.triu_indx[1], torch.tensor([0, 1, 1], dtype=torch.long))
)
self.assertEqual(k.Uvec.shape, torch.Size([3]))
k.Uvec.requires_grad_(False)
k.Uvec.copy_(torch.tensor([1.0, 2.0, 3.0], dtype=torch.double))
k.Uvec.requires_grad_(True)
x1 = torch.tensor([[0.0, 0.0], [1.0, 1.0]], dtype=torch.double)
x2 = torch.tensor([[1.0, 1.0], [0.0, 0.0]], dtype=torch.double)
K = k.forward(x1, x2)
Ktrue = torch.tensor(
[[np.exp(-0.5 * 18), 1.0], [1.0, np.exp(-0.5 * 18)]], dtype=torch.double
)
self.assertTrue(torch.equal(K, Ktrue))
def testALEBOGP(self):
# First non-batch
B = torch.tensor(
[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=torch.double
)
train_X = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=torch.double)
train_Y = torch.tensor([[1.0], [2.0], [3.0]], dtype=torch.double)
train_Yvar = 0.1 * torch.ones(3, 1, dtype=torch.double)
mll = get_map_model(
B=B,
train_X=train_X,
train_Y=train_Y,
train_Yvar=train_Yvar,
restarts=1,
init_state_dict=None,
)
m = mll.model
m.eval()
self.assertIsInstance(m, ALEBOGP)
self.assertIsInstance(m.covar_module.base_kernel, ALEBOKernel)
X = torch.tensor([[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]], dtype=torch.double)
f = m(X)
self.assertEqual(f.mean.shape, torch.Size([3]))
self.assertEqual(f.variance.shape, torch.Size([3]))
self.assertEqual(f.covariance_matrix.shape, torch.Size([3, 3]))
# Batch
Uvec_b = m.covar_module.base_kernel.Uvec.repeat(5, 1)
mean_b = m.mean_module.constant.repeat(5, 1)
output_scale_b = m.covar_module.raw_outputscale.repeat(5)
m_b = get_batch_model(
B=B,
train_X=train_X,
train_Y=train_Y,
train_Yvar=train_Yvar,
Uvec_batch=Uvec_b,
mean_constant_batch=mean_b,
output_scale_batch=output_scale_b,
)
self.assertEqual(m_b._aug_batch_shape, torch.Size([5]))
f = m_b(X)
self.assertEqual(f.mean.shape, torch.Size([3]))
self.assertEqual(f.variance.shape, torch.Size([3]))
self.assertEqual(f.covariance_matrix.shape, torch.Size([3, 3]))
self.assertEqual(
m_b.posterior(X).mvn.covariance_matrix.shape, torch.Size([3, 3])
)
# The whole process in get_fitted_model
init_state_dict = m.state_dict()
m_b2 = get_fitted_model(
B=B,
train_X=train_X,
train_Y=train_Y,
train_Yvar=train_Yvar,
restarts=1,
nsamp=5,
init_state_dict=init_state_dict,
)
self.assertEqual(m_b2._aug_batch_shape, torch.Size([5]))
# Test extract_map_statedict
map_sds = extract_map_statedict(m_b=m_b, num_outputs=1)
self.assertEqual(len(map_sds), 1)
self.assertEqual(len(map_sds[0]), 3)
self.assertEqual(
set(map_sds[0]),
{
"covar_module.base_kernel.Uvec",
"covar_module.raw_outputscale",
"mean_module.constant",
},
)
self.assertEqual(
map_sds[0]["covar_module.base_kernel.Uvec"].shape, torch.Size([3])
)
ml = ModelListGP(m_b, m_b2)
map_sds = extract_map_statedict(m_b=ml, num_outputs=2)
self.assertEqual(len(map_sds), 2)
for i in range(2):
self.assertEqual(len(map_sds[i]), 3)
self.assertEqual(
set(map_sds[i]),
{
"covar_module.base_kernel.Uvec",
"covar_module.raw_outputscale",
"mean_module.constant",
},
)
self.assertEqual(
map_sds[i]["covar_module.base_kernel.Uvec"].shape, torch.Size([3])
)
def testAcq(self):
B = torch.tensor(
[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=torch.double
)
train_X = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=torch.double)
train_Y = torch.tensor([[1.0], [2.0], [3.0]], dtype=torch.double)
train_Yvar = 0.1 * torch.ones(3, 1, dtype=torch.double)
m = ALEBOGP(B=B, train_X=train_X, train_Y=train_Y, train_Yvar=train_Yvar)
m.eval()
objective_weights = torch.tensor([1.0], dtype=torch.double)
acq = ei_or_nei(
model=m,
objective_weights=objective_weights,
outcome_constraints=None,
X_observed=train_X,
X_pending=None,
q=1,
noiseless=True,
)
self.assertIsInstance(acq, ExpectedImprovement)
self.assertEqual(acq.best_f.item(), 3.0)
objective_weights = torch.tensor([-1.0], dtype=torch.double)
acq = ei_or_nei(
model=m,
objective_weights=objective_weights,
outcome_constraints=None,
X_observed=train_X,
X_pending=None,
q=1,
noiseless=True,
)
self.assertEqual(acq.best_f.item(), 1.0)
acq = ei_or_nei(
model=m,
objective_weights=objective_weights,
outcome_constraints=None,
X_observed=train_X,
X_pending=None,
q=1,
noiseless=False,
)
self.assertIsInstance(acq, qNoisyExpectedImprovement)
with mock.patch(
"ax.models.torch.alebo.optimize_acqf", autospec=True
) as optim_mock:
alebo_acqf_optimizer(
acq_function=acq,
bounds=None,
n=1,
inequality_constraints=5.0,
fixed_features=None,
rounding_func=None,
raw_samples=100,
num_restarts=5,
B=B,
)
self.assertIsInstance(
optim_mock.mock_calls[0][2]["acq_function"], qNoisyExpectedImprovement
)
self.assertEqual(optim_mock.mock_calls[0][2]["num_restarts"], 5)
self.assertEqual(optim_mock.mock_calls[0][2]["inequality_constraints"], 5.0)
X = optim_mock.mock_calls[0][2]["batch_initial_conditions"]
self.assertEqual(X.shape, torch.Size([5, 1, 2]))
# Make sure initialization is inside subspace
Z = (B @ torch.pinverse(B) @ X[:, 0, :].t()).t()
self.assertTrue(torch.allclose(Z, X[:, 0, :]))
def testALEBO(self):
B = torch.tensor(
[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=torch.double
)
train_X = torch.tensor(
[
[0.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 1.0, 1.0, 1.0],
[2.0, 2.0, 2.0, 2.0, 2.0],
],
dtype=torch.double,
)
train_Y = torch.tensor([[1.0], [2.0], [3.0]], dtype=torch.double)
train_Yvar = 0.1 * torch.ones(3, 1, dtype=torch.double)
m = ALEBO(B=B, laplace_nsamp=5, fit_restarts=1)
self.assertTrue(torch.equal(B, m.B))
self.assertEqual(m.laplace_nsamp, 5)
self.assertEqual(m.fit_restarts, 1)
self.assertEqual(m.refit_on_update, True)
self.assertEqual(m.refit_on_cv, False)
self.assertEqual(m.warm_start_refitting, False)
# Test fit
m.fit(
Xs=[train_X, train_X],
Ys=[train_Y, train_Y],
Yvars=[train_Yvar, train_Yvar],
bounds=[(-1, 1)] * 5,
task_features=[],
feature_names=[],
metric_names=[],
fidelity_features=[],
)
self.assertIsInstance(m.model, ModelListGP)
self.assertTrue(torch.allclose(m.Xs[0], (B @ train_X.t()).t()))
# Test predict
f, cov = m.predict(X=B)
self.assertEqual(f.shape, torch.Size([2, 2]))
self.assertEqual(cov.shape, torch.Size([2, 2, 2]))
# Test best point
objective_weights = torch.tensor([1.0, 0.0], dtype=torch.double)
with self.assertRaises(NotImplementedError):
m.best_point(bounds=[(-1, 1)] * 5, objective_weights=objective_weights)
# Test gen
# With clipping
with mock.patch(
"ax.models.torch.alebo.optimize_acqf",
autospec=True,
return_value=(m.Xs[0], torch.tensor([])),
):
Xopt, _, _, _ = m.gen(
n=1,
bounds=[(-1, 1)] * 5,
objective_weights=torch.tensor([1.0, 0.0], dtype=torch.double),
)
self.assertFalse(torch.allclose(Xopt, train_X))
self.assertTrue(Xopt.min() >= -1)
self.assertTrue(Xopt.max() <= 1)
# Without
with mock.patch(
"ax.models.torch.alebo.optimize_acqf",
autospec=True,
return_value=(torch.ones(1, 2, dtype=torch.double), torch.tensor([])),
):
Xopt, _, _, _ = m.gen(
n=1,
bounds=[(-1, 1)] * 5,
objective_weights=torch.tensor([1.0, 0.0], dtype=torch.double),
)
self.assertTrue(
torch.allclose(
Xopt, torch.tensor([[-0.2, -0.1, 0.0, 0.1, 0.2]], dtype=torch.double)
)
)
# Test update
train_X2 = torch.tensor(
[
[3.0, 3.0, 3.0, 3.0, 3.0],
[1.0, 1.0, 1.0, 1.0, 1.0],
[2.0, 2.0, 2.0, 2.0, 2.0],
],
dtype=torch.double,
)
m.update(
Xs=[train_X, train_X2],
Ys=[train_Y, train_Y],
Yvars=[train_Yvar, train_Yvar],
)
self.assertTrue(torch.allclose(m.Xs[0], (B @ train_X.t()).t()))
self.assertTrue(torch.allclose(m.Xs[1], (B @ train_X2.t()).t()))
m.refit_on_update = False
m.update(
Xs=[train_X, train_X2],
Ys=[train_Y, train_Y],
Yvars=[train_Yvar, train_Yvar],
)
# Test get_and_fit with single meric
gp = m.get_and_fit_model(
Xs=[(B @ train_X.t()).t()], Ys=[train_Y], Yvars=[train_Yvar]
)
self.assertIsInstance(gp, ALEBOGP)
# Test cross_validate
f, cov = m.cross_validate(
Xs_train=[train_X],
Ys_train=[train_Y],
Yvars_train=[train_Yvar],
X_test=train_X2,
)
self.assertEqual(f.shape, torch.Size([3, 1]))
self.assertEqual(cov.shape, torch.Size([3, 1, 1]))
m.refit_on_cv = True
f, cov = m.cross_validate(
Xs_train=[train_X],
Ys_train=[train_Y],
Yvars_train=[train_Yvar],
X_test=train_X2,
)
self.assertEqual(f.shape, torch.Size([3, 1]))
self.assertEqual(cov.shape, torch.Size([3, 1, 1]))
| [
"ax.models.torch.alebo.get_batch_model",
"torch.ones",
"torch.pinverse",
"ax.models.torch.alebo.ALEBOGP",
"ax.models.torch.alebo.alebo_acqf_optimizer",
"torch.equal",
"botorch.models.model_list_gp_regression.ModelListGP",
"ax.models.torch.alebo.ei_or_nei",
"unittest.mock.patch",
"ax.models.torch.a... | [((783, 876), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=\n torch.double)\n', (795, 876), False, 'import torch\n'), ((1481, 1539), 'torch.tensor', 'torch.tensor', (['[[0.0, 0.0], [1.0, 1.0]]'], {'dtype': 'torch.double'}), '([[0.0, 0.0], [1.0, 1.0]], dtype=torch.double)\n', (1493, 1539), False, 'import torch\n'), ((1553, 1611), 'torch.tensor', 'torch.tensor', (['[[1.0, 1.0], [0.0, 0.0]]'], {'dtype': 'torch.double'}), '([[1.0, 1.0], [0.0, 0.0]], dtype=torch.double)\n', (1565, 1611), False, 'import torch\n'), ((1881, 1974), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=\n torch.double)\n', (1893, 1974), False, 'import torch\n'), ((2010, 2080), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=torch.double)\n', (2022, 2080), False, 'import torch\n'), ((2099, 2154), 'torch.tensor', 'torch.tensor', (['[[1.0], [2.0], [3.0]]'], {'dtype': 'torch.double'}), '([[1.0], [2.0], [3.0]], dtype=torch.double)\n', (2111, 2154), False, 'import torch\n'), ((2234, 2347), 'ax.models.torch.alebo.get_map_model', 'get_map_model', ([], {'B': 'B', 'train_X': 'train_X', 'train_Y': 'train_Y', 'train_Yvar': 'train_Yvar', 'restarts': '(1)', 'init_state_dict': 'None'}), '(B=B, train_X=train_X, train_Y=train_Y, train_Yvar=train_Yvar,\n restarts=1, init_state_dict=None)\n', (2247, 2347), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((2592, 2662), 'torch.tensor', 'torch.tensor', (['[[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]'], {'dtype': 'torch.double'}), '([[2.0, 2.0], [3.0, 3.0], [4.0, 4.0]], dtype=torch.double)\n', (2604, 2662), False, 'import torch\n'), ((3080, 3248), 'ax.models.torch.alebo.get_batch_model', 'get_batch_model', ([], {'B': 'B', 'train_X': 'train_X', 'train_Y': 'train_Y', 'train_Yvar': 'train_Yvar', 'Uvec_batch': 'Uvec_b', 'mean_constant_batch': 'mean_b', 'output_scale_batch': 'output_scale_b'}), '(B=B, train_X=train_X, train_Y=train_Y, train_Yvar=\n train_Yvar, Uvec_batch=Uvec_b, mean_constant_batch=mean_b,\n output_scale_batch=output_scale_b)\n', (3095, 3248), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((3825, 3962), 'ax.models.torch.alebo.get_fitted_model', 'get_fitted_model', ([], {'B': 'B', 'train_X': 'train_X', 'train_Y': 'train_Y', 'train_Yvar': 'train_Yvar', 'restarts': '(1)', 'nsamp': '(5)', 'init_state_dict': 'init_state_dict'}), '(B=B, train_X=train_X, train_Y=train_Y, train_Yvar=\n train_Yvar, restarts=1, nsamp=5, init_state_dict=init_state_dict)\n', (3841, 3962), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((4174, 4219), 'ax.models.torch.alebo.extract_map_statedict', 'extract_map_statedict', ([], {'m_b': 'm_b', 'num_outputs': '(1)'}), '(m_b=m_b, num_outputs=1)\n', (4195, 4219), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((4667, 4689), 'botorch.models.model_list_gp_regression.ModelListGP', 'ModelListGP', (['m_b', 'm_b2'], {}), '(m_b, m_b2)\n', (4678, 4689), False, 'from botorch.models.model_list_gp_regression import ModelListGP\n'), ((4708, 4752), 'ax.models.torch.alebo.extract_map_statedict', 'extract_map_statedict', ([], {'m_b': 'ml', 'num_outputs': '(2)'}), '(m_b=ml, num_outputs=2)\n', (4729, 4752), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((5297, 5390), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=\n torch.double)\n', (5309, 5390), False, 'import torch\n'), ((5426, 5496), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=torch.double)\n', (5438, 5496), False, 'import torch\n'), ((5515, 5570), 'torch.tensor', 'torch.tensor', (['[[1.0], [2.0], [3.0]]'], {'dtype': 'torch.double'}), '([[1.0], [2.0], [3.0]], dtype=torch.double)\n', (5527, 5570), False, 'import torch\n'), ((5647, 5716), 'ax.models.torch.alebo.ALEBOGP', 'ALEBOGP', ([], {'B': 'B', 'train_X': 'train_X', 'train_Y': 'train_Y', 'train_Yvar': 'train_Yvar'}), '(B=B, train_X=train_X, train_Y=train_Y, train_Yvar=train_Yvar)\n', (5654, 5716), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((5763, 5802), 'torch.tensor', 'torch.tensor', (['[1.0]'], {'dtype': 'torch.double'}), '([1.0], dtype=torch.double)\n', (5775, 5802), False, 'import torch\n'), ((5817, 5960), 'ax.models.torch.alebo.ei_or_nei', 'ei_or_nei', ([], {'model': 'm', 'objective_weights': 'objective_weights', 'outcome_constraints': 'None', 'X_observed': 'train_X', 'X_pending': 'None', 'q': '(1)', 'noiseless': '(True)'}), '(model=m, objective_weights=objective_weights, outcome_constraints\n =None, X_observed=train_X, X_pending=None, q=1, noiseless=True)\n', (5826, 5960), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((6185, 6225), 'torch.tensor', 'torch.tensor', (['[-1.0]'], {'dtype': 'torch.double'}), '([-1.0], dtype=torch.double)\n', (6197, 6225), False, 'import torch\n'), ((6240, 6383), 'ax.models.torch.alebo.ei_or_nei', 'ei_or_nei', ([], {'model': 'm', 'objective_weights': 'objective_weights', 'outcome_constraints': 'None', 'X_observed': 'train_X', 'X_pending': 'None', 'q': '(1)', 'noiseless': '(True)'}), '(model=m, objective_weights=objective_weights, outcome_constraints\n =None, X_observed=train_X, X_pending=None, q=1, noiseless=True)\n', (6249, 6383), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((6538, 6682), 'ax.models.torch.alebo.ei_or_nei', 'ei_or_nei', ([], {'model': 'm', 'objective_weights': 'objective_weights', 'outcome_constraints': 'None', 'X_observed': 'train_X', 'X_pending': 'None', 'q': '(1)', 'noiseless': '(False)'}), '(model=m, objective_weights=objective_weights, outcome_constraints\n =None, X_observed=train_X, X_pending=None, q=1, noiseless=False)\n', (6547, 6682), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((7898, 7991), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]]'], {'dtype': 'torch.double'}), '([[1.0, 2.0, 3.0, 4.0, 5.0], [2.0, 3.0, 4.0, 5.0, 6.0]], dtype=\n torch.double)\n', (7910, 7991), False, 'import torch\n'), ((8027, 8147), 'torch.tensor', 'torch.tensor', (['[[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0,\n 2.0]]'], {'dtype': 'torch.double'}), '([[0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, \n 2.0, 2.0, 2.0, 2.0]], dtype=torch.double)\n', (8039, 8147), False, 'import torch\n'), ((8259, 8314), 'torch.tensor', 'torch.tensor', (['[[1.0], [2.0], [3.0]]'], {'dtype': 'torch.double'}), '([[1.0], [2.0], [3.0]], dtype=torch.double)\n', (8271, 8314), False, 'import torch\n'), ((8392, 8435), 'ax.models.torch.alebo.ALEBO', 'ALEBO', ([], {'B': 'B', 'laplace_nsamp': '(5)', 'fit_restarts': '(1)'}), '(B=B, laplace_nsamp=5, fit_restarts=1)\n', (8397, 8435), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((9387, 9431), 'torch.tensor', 'torch.tensor', (['[1.0, 0.0]'], {'dtype': 'torch.double'}), '([1.0, 0.0], dtype=torch.double)\n', (9399, 9431), False, 'import torch\n'), ((10718, 10838), 'torch.tensor', 'torch.tensor', (['[[3.0, 3.0, 3.0, 3.0, 3.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0,\n 2.0]]'], {'dtype': 'torch.double'}), '([[3.0, 3.0, 3.0, 3.0, 3.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, \n 2.0, 2.0, 2.0, 2.0]], dtype=torch.double)\n', (10730, 10838), False, 'import torch\n'), ((1009, 1028), 'torch.equal', 'torch.equal', (['B', 'k.B'], {}), '(B, k.B)\n', (1020, 1028), False, 'import torch\n'), ((1305, 1320), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (1315, 1320), False, 'import torch\n'), ((1381, 1430), 'torch.tensor', 'torch.tensor', (['[1.0, 2.0, 3.0]'], {'dtype': 'torch.double'}), '([1.0, 2.0, 3.0], dtype=torch.double)\n', (1393, 1430), False, 'import torch\n'), ((1792, 1813), 'torch.equal', 'torch.equal', (['K', 'Ktrue'], {}), '(K, Ktrue)\n', (1803, 1813), False, 'import torch\n'), ((2182, 2218), 'torch.ones', 'torch.ones', (['(3)', '(1)'], {'dtype': 'torch.double'}), '(3, 1, dtype=torch.double)\n', (2192, 2218), False, 'import torch\n'), ((2719, 2734), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (2729, 2734), False, 'import torch\n'), ((2779, 2794), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (2789, 2794), False, 'import torch\n'), ((2848, 2866), 'torch.Size', 'torch.Size', (['[3, 3]'], {}), '([3, 3])\n', (2858, 2866), False, 'import torch\n'), ((3383, 3398), 'torch.Size', 'torch.Size', (['[5]'], {}), '([5])\n', (3393, 3398), False, 'import torch\n'), ((3458, 3473), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (3468, 3473), False, 'import torch\n'), ((3518, 3533), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (3528, 3533), False, 'import torch\n'), ((3587, 3605), 'torch.Size', 'torch.Size', (['[3, 3]'], {}), '([3, 3])\n', (3597, 3605), False, 'import torch\n'), ((3691, 3709), 'torch.Size', 'torch.Size', (['[3, 3]'], {}), '([3, 3])\n', (3701, 3709), False, 'import torch\n'), ((4101, 4116), 'torch.Size', 'torch.Size', (['[5]'], {}), '([5])\n', (4111, 4116), False, 'import torch\n'), ((4627, 4642), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (4637, 4642), False, 'import torch\n'), ((5598, 5634), 'torch.ones', 'torch.ones', (['(3)', '(1)'], {'dtype': 'torch.double'}), '(3, 1, dtype=torch.double)\n', (5608, 5634), False, 'import torch\n'), ((6849, 6913), 'unittest.mock.patch', 'mock.patch', (['"""ax.models.torch.alebo.optimize_acqf"""'], {'autospec': '(True)'}), "('ax.models.torch.alebo.optimize_acqf', autospec=True)\n", (6859, 6913), False, 'from unittest import mock\n'), ((6963, 7134), 'ax.models.torch.alebo.alebo_acqf_optimizer', 'alebo_acqf_optimizer', ([], {'acq_function': 'acq', 'bounds': 'None', 'n': '(1)', 'inequality_constraints': '(5.0)', 'fixed_features': 'None', 'rounding_func': 'None', 'raw_samples': '(100)', 'num_restarts': '(5)', 'B': 'B'}), '(acq_function=acq, bounds=None, n=1,\n inequality_constraints=5.0, fixed_features=None, rounding_func=None,\n raw_samples=100, num_restarts=5, B=B)\n', (6983, 7134), False, 'from ax.models.torch.alebo import ALEBO, ALEBOGP, ALEBOKernel, alebo_acqf_optimizer, ei_or_nei, extract_map_statedict, get_batch_model, get_fitted_model, get_map_model\n'), ((7671, 7692), 'torch.Size', 'torch.Size', (['[5, 1, 2]'], {}), '([5, 1, 2])\n', (7681, 7692), False, 'import torch\n'), ((7829, 7858), 'torch.allclose', 'torch.allclose', (['Z', 'X[:, 0, :]'], {}), '(Z, X[:, 0, :])\n', (7843, 7858), False, 'import torch\n'), ((8342, 8378), 'torch.ones', 'torch.ones', (['(3)', '(1)'], {'dtype': 'torch.double'}), '(3, 1, dtype=torch.double)\n', (8352, 8378), False, 'import torch\n'), ((8460, 8479), 'torch.equal', 'torch.equal', (['B', 'm.B'], {}), '(B, m.B)\n', (8471, 8479), False, 'import torch\n'), ((9253, 9271), 'torch.Size', 'torch.Size', (['[2, 2]'], {}), '([2, 2])\n', (9263, 9271), False, 'import torch\n'), ((9309, 9330), 'torch.Size', 'torch.Size', (['[2, 2, 2]'], {}), '([2, 2, 2])\n', (9319, 9330), False, 'import torch\n'), ((9995, 10024), 'torch.allclose', 'torch.allclose', (['Xopt', 'train_X'], {}), '(Xopt, train_X)\n', (10009, 10024), False, 'import torch\n'), ((11844, 11862), 'torch.Size', 'torch.Size', (['[3, 1]'], {}), '([3, 1])\n', (11854, 11862), False, 'import torch\n'), ((11900, 11921), 'torch.Size', 'torch.Size', (['[3, 1, 1]'], {}), '([3, 1, 1])\n', (11910, 11921), False, 'import torch\n'), ((12162, 12180), 'torch.Size', 'torch.Size', (['[3, 1]'], {}), '([3, 1])\n', (12172, 12180), False, 'import torch\n'), ((12218, 12239), 'torch.Size', 'torch.Size', (['[3, 1, 1]'], {}), '([3, 1, 1])\n', (12228, 12239), False, 'import torch\n'), ((935, 949), 'torch.Size', 'torch.Size', (['[]'], {}), '([])\n', (945, 949), False, 'import torch\n'), ((1095, 1136), 'torch.tensor', 'torch.tensor', (['[0, 0, 1]'], {'dtype': 'torch.long'}), '([0, 0, 1], dtype=torch.long)\n', (1107, 1136), False, 'import torch\n'), ((1213, 1254), 'torch.tensor', 'torch.tensor', (['[0, 1, 1]'], {'dtype': 'torch.long'}), '([0, 1, 1], dtype=torch.long)\n', (1225, 1254), False, 'import torch\n'), ((5231, 5246), 'torch.Size', 'torch.Size', (['[3]'], {}), '([3])\n', (5241, 5246), False, 'import torch\n'), ((10588, 10651), 'torch.tensor', 'torch.tensor', (['[[-0.2, -0.1, 0.0, 0.1, 0.2]]'], {'dtype': 'torch.double'}), '([[-0.2, -0.1, 0.0, 0.1, 0.2]], dtype=torch.double)\n', (10600, 10651), False, 'import torch\n'), ((1687, 1704), 'numpy.exp', 'np.exp', (['(-0.5 * 18)'], {}), '(-0.5 * 18)\n', (1693, 1704), True, 'import numpy as np\n'), ((1718, 1735), 'numpy.exp', 'np.exp', (['(-0.5 * 18)'], {}), '(-0.5 * 18)\n', (1724, 1735), True, 'import numpy as np\n'), ((9909, 9953), 'torch.tensor', 'torch.tensor', (['[1.0, 0.0]'], {'dtype': 'torch.double'}), '([1.0, 0.0], dtype=torch.double)\n', (9921, 9953), False, 'import torch\n'), ((10452, 10496), 'torch.tensor', 'torch.tensor', (['[1.0, 0.0]'], {'dtype': 'torch.double'}), '([1.0, 0.0], dtype=torch.double)\n', (10464, 10496), False, 'import torch\n'), ((7765, 7782), 'torch.pinverse', 'torch.pinverse', (['B'], {}), '(B)\n', (7779, 7782), False, 'import torch\n'), ((9751, 9767), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (9763, 9767), False, 'import torch\n'), ((10256, 10292), 'torch.ones', 'torch.ones', (['(1)', '(2)'], {'dtype': 'torch.double'}), '(1, 2, dtype=torch.double)\n', (10266, 10292), False, 'import torch\n'), ((10294, 10310), 'torch.tensor', 'torch.tensor', (['[]'], {}), '([])\n', (10306, 10310), False, 'import torch\n')] |
"""Integrated gradient based attribution"""
from typing import Callable, List, Optional, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from scipy import ndimage
class ModelWrapper:
def zero_grad(self):
raise NotImplementedError()
def __call__(self, x):
return self.forward(x)
def forward(self, x):
raise NotImplementedError()
def eval(self):
raise NotImplementedError()
def blur_image(spectrogram: torch.Tensor, sigmas: List[float]) -> np.ndarray:
"""For every sigma construct a Gaussian blurred spectrogram.
Args:
spectrogram (torch.Tensor): Base spectrogram.
sigmas (List[float]): List of differnt sigma level.
"""
spectrograms = []
for sigma in sigmas:
spectrograms.append(ndimage.gaussian_filter(
spectrogram.numpy(), sigma=[sigma, sigma], mode="constant"))
return np.array(spectrograms)
def compute_gradients(
spectrograms: np.ndarray,
model: ModelWrapper,
feature_fn: Optional[Callable] = None,
) -> torch.Tensor:
"""Compute the gradient attributions for every image.
Args:
images - Images to compute gradients for.
model - Model to use.
target_class_idx - Id of the target class.
preprocess_fn - Function for preprocessing the images (default - ImageNet preprocessing).
binary_classification - classification is simple binary prediction.
"""
# TODO: Vectorize once torch.vmap is available
grads = []
model.eval()
for spec in spectrograms:
# forwards pass
# switch from HxWxC to CxHxW
spectrogram = torch.from_numpy(spec).detach().requires_grad_(True)
spectrogram = spectrogram.float()
if feature_fn is not None:
inputs = feature_fn(spectrogram)
inputs = inputs.view(inputs.shape[-2:]).T
else:
inputs = spectrogram
output = model(inputs)
# compute grad
model.zero_grad()
output.backward()
gradient = spectrogram.grad.detach().cpu()
grads.append(gradient)
grads = torch.stack(grads)
return grads
def integral_approximation(gradients: torch.Tensor) -> torch.Tensor:
"""Use Riemann trapezoidal to approximate the path integral.
"""
grads = (gradients[:-1] + gradients[1:]) / 2.
attribution = torch.mean(grads, axis=0)
return attribution
def blur_gradients(
spectrogram: torch.Tensor,
model: ModelWrapper,
steps: int,
max_sigma: int = 50,
feature_fn: Optional[Callable] = None,
) -> Tuple[np.ndarray, np.ndarray, torch.Tensor]:
"""Calculate (blur) integrated gradients.
Args:
spectrogram (torch.Tensor): Spectrogram to attribute
model (torch.nn.Module): Model to use.
steps (int): Blurring steps to perform.
max_sigma (int): Maximum sigma of the Gaussian blur.
"""
# Setup for IG
baseline_img = torch.zeros_like(spectrogram)
sigmas = [float(i)*max_sigma/float(steps) for i in range(0, steps+1)]
interpolation = blur_image(spectrogram, sigmas)
path_gradients = compute_gradients(
spectrograms=interpolation, model=model, feature_fn=feature_fn)
attribution = integral_approximation(path_gradients)
return baseline_img, interpolation, attribution
| [
"torch.mean",
"torch.stack",
"torch.zeros_like",
"numpy.array",
"torch.from_numpy"
] | [((911, 933), 'numpy.array', 'np.array', (['spectrograms'], {}), '(spectrograms)\n', (919, 933), True, 'import numpy as np\n'), ((2146, 2164), 'torch.stack', 'torch.stack', (['grads'], {}), '(grads)\n', (2157, 2164), False, 'import torch\n'), ((2394, 2419), 'torch.mean', 'torch.mean', (['grads'], {'axis': '(0)'}), '(grads, axis=0)\n', (2404, 2419), False, 'import torch\n'), ((2974, 3003), 'torch.zeros_like', 'torch.zeros_like', (['spectrogram'], {}), '(spectrogram)\n', (2990, 3003), False, 'import torch\n'), ((1666, 1688), 'torch.from_numpy', 'torch.from_numpy', (['spec'], {}), '(spec)\n', (1682, 1688), False, 'import torch\n')] |
import copy
import csv
import glob
import os
import random
import sys
import cv2
import numpy as np
import torch
from PIL.Image import Image
import skimage
import skimage.color
import skimage.io
import skimage.transform
from pycocotools import coco
from pycocotools.coco import COCO
from torch.utils.data import Dataset, Sampler
from .utils import draw_bbox
from importlib import import_module
from .image import ImageData
from .custom_transforms import *
import pandas as pd
np.set_printoptions(suppress=True)
augmentations = ['Translate_Y',
'Translate_Y_BBoxes',
'Translate_X',
'Translate_X_BBoxes',
'CutOut',
'CutOut_BBoxes',
'Rotate',
'ShearX',
'ShearX_BBoxes',
'ShearY',
'ShearY_BBoxes',
'Equalize',
'Equalize_BBoxes',
'Solarize',
'Solarize_BBoxes',
'Color',
'Color_BBoxes',
'FlipLR'
]
class CustomDataset(Dataset):
def __init__(self, dir_path, data_format, annotation_path=None, function_transforms=None, built_in_transforms=None, dataset="train"):
"""
Args:
dir_path: the dataset path, if the annotation_path is None, then it will search all the files, if the annotation is not None, it will search the images.
data_format: dataset format. i.e. CoCo or Yolo.
annotation_path: if has, input the .json or txt annotation path directly
functions_of_transform" is a list of string with single/variety of transform functions.
built_in_augmentations: is a list of string with single/variety of augmentations in the library.
dataset is train or test
"""
self.dir_path = dir_path
self.data_format = data_format
self.annot_path = annotation_path
self.function_transforms = function_transforms
self.built_in_transforms = built_in_transforms
self.dataset = dataset
self.img_path_list = []
self.img_file_list = []
self.img = []
self.annot = []
self.ann_path_list = []
if self.data_format == 'yolo':
# get image list
self.img_path_list = glob.glob(dir_path + '/' + '*.jpg')+glob.glob(
dir_path + '/' + '*.jpeg')+glob.glob(dir_path + '/' + '*.png')
if self.annot_path is None:
# get annotation list
self.ann_path_list = glob.glob(dir_path + '/'+'*.txt')
else:
self.ann_path_list = self.annot_path
self.classes_set = set()
self.calculate_classes()
self.img_path_list.sort()
self.ann_path_list.sort()
# get all the image file path
elif self.data_format == 'coco':
self.set_name = 'train'
self.img_path_list = glob.glob(
dir_path + '/images/' + self.set_name + '/'+'*.jpg')
if self.annot_path is None:
self.coco = COCO(os.path.join(
self.dir_path, 'annotations', 'instances_' + self.set_name + '.json'))
else:
self.coco = COCO(
self.annot_path)
self.image_ids = self.coco.getImgIds()
self.load_classes()
self.img_path_list.sort()
self.ann_path_list.sort()
elif self.data_format == 'csv':
if self.annot_path is None:
self.dir_path_list = glob.glob(self.dir_path + '/' + '*.csv')
else:
self.dir_path_list = self.annot_path
self.data = pd.read_csv(self.dir_path_list[0], header=None)
self.data.columns = ['0', '1']
self.load_all_pictures()
# read the txt file and separate to two culomn (filename & category)and save as dataFrame
elif self.data_format == 'txt':
column_zero = []
column_one = []
if self.annot_path is None:
self.dir_path_list = glob.glob(self.dir_path + '/' + '*.txt')
else:
self.dir_path_list = glob.glob(annotation_path)
with open(self.dir_path_list[0]) as f:
for line in f.readlines():
line = line.strip('\n')
split_list = line.split(" ")
column_zero.append(split_list.pop(0))
column_one += split_list
dict = {'0': column_zero, '1': column_one}
self.data = pd.DataFrame(dict)
self.load_all_pictures()
# from all folder ,get all the pictures
def load_all_pictures(self):
for index in range(len(self.data['0'])):
img_file = (glob.glob(self.dir_path + '/'+self.dataset+'/' + self.data['0'][index] + "/" + '*.jpg')
+ glob.glob(self.dir_path + '/'+self.dataset+'/' +
self.data['0'][index] + "/" + '*.jpeg')
+ glob.glob(self.dir_path + '/'+self.dataset+'/' + self.data['0'][index] + "/" + '*.png'))
for i in img_file:
self.img_file_list.append(i)
def load_classes(self):
# load class names (name -> label)
categories = self.coco.loadCats(self.coco.getCatIds())
categories.sort(key=lambda x: x['id'])
self.classes = {}
self.coco_labels = {}
self.coco_labels_inverse = {}
for c in categories:
self.coco_labels[len(self.classes)] = c['id']
self.coco_labels_inverse[c['id']] = len(self.classes)
self.classes[c['name']] = len(self.classes)
# also load the reverse (label -> name)
self.labels = {}
for key, value in self.classes.items():
self.labels[value] = key
def __getitem__(self, index):
if self.data_format == 'csv' or self.data_format == 'txt':
full_filename = self.img_file_list[index]
filename_split = full_filename.split("/")
filename = filename_split[-1]
category = filename_split[-2]
for i in range(len(self.data)):
if category == self.data['0'][i]:
category = self.data['1'][i]
break
# make the image array value between [0,1]
image = skimage.io.imread(full_filename)
image = image/255.0
image_data = ImageData(
flag=False, filename=filename, image=image, label=category)
return image_data
mask_category = []
scale = None
filename = self.img_path_list[index].split("/")[-1]
if self.data_format == 'yolo':
path = self.img_path_list[index]
self.img = self.load_image(index, path)
dh, dw, _ = self.img.shape
self.annot = self.load_annotations_yolo(index, dh, dw)
mask_category = None
elif self.data_format == 'coco':
image_info = self.coco.loadImgs(self.image_ids[index])[0]
path = os.path.join(self.dir_path, 'images',
self.set_name, image_info['file_name'])
self.img = self.load_image(index, path)
self.annot = self.load_annotations(index)
ann_id = self.coco.getAnnIds(imgIds=self.image_ids[index])
coco_annotations = self.coco.loadAnns(ann_id)
for ann in coco_annotations:
if ann['segmentation'] is not None:
mask = self.coco.annToMask(ann)
category = ann['category_id']
mask_category.append([mask, category])
image_data = ImageData(filename=filename, image=self.img,
annotation=self.annot, scale=scale, masks_and_category=mask_category)
if self.function_transforms is not None:
for tsfm in self.function_transforms:
tsfm(image_data)
elif self.built_in_transforms is not None:
aug = Augmentation(self.built_in_transforms)
aug(image_data)
return image_data
def __len__(self):
if self.data_format == 'yolo':
return len(self.img_path_list)
elif self.data_format == 'coco':
return len(self.image_ids)
elif self.data_format == 'csv' or self.data_format == 'txt':
return len(self.img_file_list)
def visualize(self, save_path):
if self.data_format == 'csv' or self.data_format == 'txt':
all_picture = []
for index, image in enumerate(self.img_file_list):
all_picture.append(self.__getitem__(index))
filename_split = image.split("/")
filename = filename_split[-1]
for pic in all_picture:
img = pic.image
label = pic.label
# write category on the image
cv2.putText(img, str("Label-"+label), (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 1)
os.makedirs(save_path, exist_ok=True)
save_img_path = os.path.join(save_path, filename)
skimage.io.imsave(save_img_path, img)
if self.data_format == 'yolo':
sample_list = []
file = []
if self.function_transforms is not None:
for image in range(len(self.img_path_list)):
filename = self.img_path_list[image].split("/")[-1]
sample_list.append(self.__getitem__(image))
file.append(filename)
for sample in sample_list:
img = sample.image
annot = sample.annot
for bbox in annot:
label = bbox[4].astype(str)
x1 = int(bbox[0])
y1 = int(bbox[1])
x2 = int(bbox[2])
y2 = int(bbox[3])
bbox = [x1, y1, x2, y2]
draw_bbox(img, bbox, label)
# save to the path
os.makedirs(save_path, exist_ok=True)
save_img_path = os.path.join(save_path, filename)
skimage.io.imsave(save_img_path, img)
else:
for img_path, ann_path in zip(self.img_path_list, self.ann_path_list):
img = skimage.io.imread(img_path)
filename = img_path.split("/")[-1]
dh, dw, _ = img.shape
fl = open(ann_path, 'r')
data = fl.readlines()
fl.close()
# Taken from https://stackoverflow.com/questions/64096953/how-to-convert-yolo-format-bounding-box-coordinates-into-opencv-format
for dt in data:
# Split string to float
c, x, y, w, h = map(float, dt.split(' '))
left = int((x - w / 2) * dw)
right = int((x + w / 2) * dw)
top = int((y - h / 2) * dh)
bottom = int((y + h / 2) * dh)
if left < 0:
left = 0
if right > dw - 1:
right = dw - 1
if top < 0:
top = 0
if bottom > dh - 1:
bottom = dh - 1
bbox = [left, top, right, bottom]
draw_bbox(img, bbox, c)
# save to the path
os.makedirs(save_path, exist_ok=True)
save_img_path = os.path.join(save_path, filename)
skimage.io.imsave(save_img_path, img)
elif self.data_format == 'coco':
if self.function_transforms is not None:
sample_list = []
file = []
for image in range(len(self.img_path_list)):
filename = self.img_path_list[image].split("/")[-1]
sample_list.append(self.__getitem__(image))
file.append(filename)
for sample in sample_list:
img = sample.image
annot = sample.annot
for bbox in annot:
label = bbox[4].astype(str)
draw_bbox(img, bbox[:4], label)
os.makedirs(save_path, exist_ok=True)
save_img_path = os.path.join(save_path, filename)
skimage.io.imsave(save_img_path, img)
else:
for idx in range(len(self.image_ids)):
image_info = self.coco.loadImgs(self.image_ids[idx])[0]
path = os.path.join(
self.img_path, 'images', self.set_name, image_info['file_name'])
img = self.load_image(idx, path)
annot = self.load_annotations(idx)
for bbox in annot:
label = self.labels[bbox[4]]
draw_bbox(img, bbox[:4], label)
filename = self.coco.loadImgs(self.image_ids[idx])[
0]['file_name']
os.makedirs(save_path, exist_ok=True)
save_img_path = os.path.join(save_path, filename)
skimage.io.imsave(save_img_path, img)
def load_image(self, image_index, path):
try:
img = skimage.io.imread(path)
if len(img.shape) == 2:
img = skimage.color.gray2rgb(img)
return img.astype(np.float32) / 255.0
except Exception as e:
print(e)
def load_annotations_yolo(self, index, dh, dw):
ann = []
fl = open(self.ann_path_list[index], 'r')
for dt in fl.readlines():
dt = dt.strip()
# Split string to float
c, x, y, w, h = map(float, dt.split(' '))
left = int((x - w / 2) * dw)
right = int((x + w / 2) * dw)
top = int((y - h / 2) * dh)
bottom = int((y + h / 2) * dh)
if left < 0:
left = 0
if right > dw - 1:
right = dw - 1
if top < 0:
top = 0
if bottom > dh - 1:
bottom = dh - 1
temp_ann = [left, top, right, bottom, c]
ann.append(temp_ann)
fl.close()
return np.array(ann)
def load_annotations(self, image_index):
# get ground truth annotations in [x1, y1, x2, y2] format
annotations_ids = self.coco.getAnnIds(
imgIds=self.image_ids[image_index], iscrowd=False)
annotations = np.zeros((0, 5))
# some images appear to miss annotations (like image with id 257034)
if len(annotations_ids) == 0:
return annotations
# parse annotations
coco_annotations = self.coco.loadAnns(annotations_ids)
for idx, a in enumerate(coco_annotations):
# some annotations have basically no width / height, skip them
if a['bbox'][2] < 1 or a['bbox'][3] < 1:
continue
annotation = np.zeros((1, 5))
annotation[0, :4] = a['bbox']
annotation[0, 4] = self.coco_label_to_label(a['category_id'])
annotations = np.append(annotations, annotation, axis=0)
# transform from [x, y, w, h] to [x1, y1, x2, y2]
annotations[:, 2] = annotations[:, 0] + annotations[:, 2]
annotations[:, 3] = annotations[:, 1] + annotations[:, 3]
return annotations
# These two functions are so the network has every label from 0 - 80 consistently
def coco_label_to_label(self, coco_label):
return self.coco_labels_inverse[coco_label]
def label_to_coco_label(self, label):
return self.coco_labels[label]
def image_aspect_ratio(self, image_index):
image = self.coco.loadImgs(self.image_ids[image_index])[0]
return float(image['width']) / float(image['height'])
def calculate_classes(self):
for ann_file in self.ann_path_list:
with open(ann_file) as f:
ann = f.readline().split(" ")
self.classes_set.add(ann[0])
@ property
def num_classes(self):
if self.data_format == 'yolo':
return len(self.classes_set)
elif self.data_format == 'coco':
return len(self.classes)
class PredDataset(Dataset):
"""CSV dataset."""
def __init__(self, pred_on_path, class_list_path=None, transform=None, resize=None):
"""
Args:
train_file (string): CSV file with training annotations
annotations (string): CSV file with class list
test_file (string, optional): CSV file with testing annotations
"""
self.train_file = pred_on_path
self.class_list_path = class_list_path
self.transform = transform
# parse the provided class file
if self.class_list_path is not None:
try:
with self._open_for_csv(self.class_list_path) as file:
self.classes = self.load_classes(
csv.reader(file, delimiter=','))
except ValueError as e:
raise (ValueError('invalid CSV class file: {}: {}'.format(
self.class_list_path, e)), None)
self.labels = {}
for key, value in self.classes.items():
self.labels[value] = key
full_names = []
for name in os.listdir(pred_on_path):
try:
if name.split('.')[1] in ['jpg', 'png']:
full_names.append(os.path.join(pred_on_path, name))
except:
pass
image_data = {}
for full_name in full_names:
image_data[full_name] = []
self.image_data = image_data
self.image_names = full_names
self.resize = resize
self.transform_this = self.get_transform()
def _parse(self, value, function, fmt):
"""
Parse a string into a value, and format a nice ValueError if it fails.
Returns `function(value)`.
Any `ValueError` raised is catched and a new `ValueError` is raised
with message `fmt.format(e)`, where `e` is the caught `ValueError`.
"""
try:
return function(value)
except ValueError as e:
raise (ValueError(fmt.format(e)), None)
def _open_for_csv(self, path):
"""
Open a file with flags suitable for csv.reader.
This is different for python2 it means with mode 'rb',
for python3 this means 'r' with "universal newlines".
"""
if sys.version_info[0] < 3:
return open(path, 'rb')
else:
return open(path, 'r', newline='')
def load_classes(self, csv_reader):
result = {}
for line, row in enumerate(csv_reader):
try:
class_name, class_id = row
except ValueError:
class_name = row[0]
class_id = line
class_id = self._parse(
class_id, int, 'line {}: malformed class ID: {{}}'.format(line))
if class_name in result:
raise ValueError(
'line {}: duplicate class name: \'{}\''.format(line, class_name))
result[class_name] = class_id
line += 1
return result
def __len__(self):
return len(self.image_names)
def __getitem__(self, idx):
img = self.load_image(idx)
annot = self.load_annotations(idx)
sample = {'img': img, 'annot': annot}
if self.transform:
sample = self.transform(sample)
# sample = self.transform_this(sample)
return sample
def get_transform(self):
return TransformTr(resize=self.resize)
def load_image(self, image_index):
img = skimage.io.imread(self.image_names[image_index])
if len(img.shape) == 2:
img = skimage.color.gray2rgb(img)
return img.astype(np.float32) / 255.0
def load_annotations(self, image_index):
# get ground truth annotations
annotation_list = self.image_data[self.image_names[image_index]]
annotations = np.zeros((0, 5))
# some images appear to miss annotations (like image with id 257034)
if len(annotation_list) == 0:
return annotations
# parse annotations
for idx, a in enumerate(annotation_list):
# some annotations have basically no width / height, skip them
x1 = a['x1']
x2 = a['x2']
y1 = a['y1']
y2 = a['y2']
if (x2 - x1) < 1 or (y2 - y1) < 1:
continue
annotation = np.zeros((1, 5))
annotation[0, 0] = x1
annotation[0, 1] = y1
annotation[0, 2] = x2
annotation[0, 3] = y2
annotation[0, 4] = self.name_to_label(a['class'])
annotations = np.append(annotations, annotation, axis=0)
return annotations
def _read_annotations(self, csv_reader, classes):
result = {}
for line, row in enumerate(csv_reader):
line += 1
img_file = row[0]
if img_file not in result:
result[img_file] = []
return result
def name_to_label(self, name):
return self.classes[name]
def label_to_name(self, label):
return self.labels[label]
def num_classes(self):
return len(self.classes)
def image_aspect_ratio(self, image_index):
image = Image.open(self.image_names[image_index])
return float(image.width) / float(image.height)
class CSVDataset(Dataset):
"""CSV dataset."""
def __init__(self, train_file, class_list, transform=None, resize=None):
"""
Args:
train_file (string): CSV file with training annotations
annotations (string): CSV file with class list
test_file (string, optional): CSV file with testing annotations
"""
self.train_file = train_file
self.class_list = class_list
self.transform = transform
# parse the provided class file
try:
with self._open_for_csv(self.class_list) as file:
self.classes = self.load_classes(
csv.reader(file, delimiter=','))
except ValueError as e:
raise (ValueError('invalid CSV class file: {}: {}'.format(
self.class_list, e)), None)
self.labels = {}
for key, value in self.classes.items():
self.labels[value] = key
# csv with img_path, x1, y1, x2, y2, class_name
try:
with self._open_for_csv(self.train_file) as file:
self.image_data = self._read_annotations(
csv.reader(file, delimiter=','), self.classes)
except ValueError as e:
raise (ValueError('invalid CSV annotations file: {}: {}'.format(
self.train_file, e)), None)
self.image_names = list(self.image_data.keys())
self.resize = resize
self.transform_this = self.get_transform()
def _parse(self, value, function, fmt):
"""
Parse a string into a value, and format a nice ValueError if it fails.
Returns `function(value)`.
Any `ValueError` raised is catched and a new `ValueError` is raised
with message `fmt.format(e)`, where `e` is the caught `ValueError`.
"""
try:
return function(value)
except ValueError as e:
raise (ValueError(fmt.format(e)), None)
def _open_for_csv(self, path):
"""
Open a file with flags suitable for csv.reader.
This is different for python2 it means with mode 'rb',
for python3 this means 'r' with "universal newlines".
"""
if sys.version_info[0] < 3:
return open(path, 'rb')
else:
return open(path, 'r', newline='')
def load_classes(self, csv_reader):
result = {}
for line, row in enumerate(csv_reader):
try:
class_name, class_id = row
except ValueError:
class_name = row[0]
class_id = line
class_id = self._parse(
class_id, int, 'line {}: malformed class ID: {{}}'.format(line))
if class_name in result:
raise ValueError(
'line {}: duplicate class name: \'{}\''.format(line, class_name))
result[class_name] = class_id
line += 1
return result
def __len__(self):
return len(self.image_names)
def __getitem__(self, idx):
img = self.load_image(idx)
annot = self.load_annotations(idx)
sample = {'img': img, 'annot': annot}
if self.transform:
sample = self.transform(sample)
# sample = self.transform_this(sample)
return sample
def get_transform(self):
return TransformTr(resize=self.resize)
def load_image(self, image_index):
img = skimage.io.imread(self.image_names[image_index])
if len(img.shape) == 2:
img = skimage.color.gray2rgb(img)
return img.astype(np.float32) / 255.0
def load_annotations(self, image_index):
# get ground truth annotations
annotation_list = self.image_data[self.image_names[image_index]]
annotations = np.zeros((0, 5))
# some images appear to miss annotations (like image with id 257034)
if len(annotation_list) == 0:
return annotations
# parse annotations
for idx, a in enumerate(annotation_list):
# some annotations have basically no width / height, skip them
x1 = a['x1']
x2 = a['x2']
y1 = a['y1']
y2 = a['y2']
if (x2 - x1) < 1 or (y2 - y1) < 1:
continue
annotation = np.zeros((1, 5))
annotation[0, 0] = x1
annotation[0, 1] = y1
annotation[0, 2] = x2
annotation[0, 3] = y2
annotation[0, 4] = self.name_to_label(a['class'])
annotations = np.append(annotations, annotation, axis=0)
return annotations
def _read_annotations(self, csv_reader, classes):
result = {}
for line, row in enumerate(csv_reader):
line += 1
try:
img_file, x1, y1, x2, y2, class_name = row[:6]
except ValueError:
raise (ValueError(
'line {}: format should be \'img_file,x1,y1,x2,y2,class_name\' or \'img_file,,,,,\''.format(line)),
None)
if img_file not in result:
result[img_file] = []
# If a row contains only an image path, it's an image without annotations.
if (x1, y1, x2, y2, class_name) == ('', '', '', '', ''):
continue
x1 = self._parse(
x1, int, 'line {}: malformed x1: {{}}'.format(line))
y1 = self._parse(
y1, int, 'line {}: malformed y1: {{}}'.format(line))
x2 = self._parse(
x2, int, 'line {}: malformed x2: {{}}'.format(line))
y2 = self._parse(
y2, int, 'line {}: malformed y2: {{}}'.format(line))
# Check that the bounding box is valid.
if x2 <= x1:
raise ValueError(
'line {}: x2 ({}) must be higher than x1 ({})'.format(line, x2, x1))
if y2 <= y1:
raise ValueError(
'line {}: y2 ({}) must be higher than y1 ({})'.format(line, y2, y1))
# check if the current class name is correctly present
if class_name not in classes:
raise ValueError('line {}: unknown class name: \'{}\' (classes: {})'.format(
line, class_name, classes))
result[img_file].append(
{'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'class': class_name})
return result
def name_to_label(self, name):
return self.classes[name]
def label_to_name(self, label):
return self.labels[label]
def num_classes(self):
return len(self.classes)
def image_aspect_ratio(self, image_index):
image = Image.open(self.image_names[image_index])
return float(image.width) / float(image.height)
def collater(data):
imgs = [s.image for s in data]
annots = [s.annot for s in data]
scales = [s.scale for s in data]
widths = [int(s.shape[0]) for s in imgs]
heights = [int(s.shape[1]) for s in imgs]
batch_size = len(imgs)
max_width = np.array(widths).max()
max_height = np.array(heights).max()
padded_imgs = torch.zeros(batch_size, max_width, max_height, 3)
for i in range(batch_size):
img = imgs[i]
padded_imgs[i, :int(img.shape[0]), :int(img.shape[1]), :] = img
max_num_annots = max(annot.shape[0] for annot in annots)
if max_num_annots > 0:
annot_padded = torch.ones((len(annots), max_num_annots, 5)) * -1
if max_num_annots > 0:
for idx, annot in enumerate(annots):
# print(annot.shape)
if annot.shape[0] > 0:
annot_padded[idx, :annot.shape[0], :] = annot
else:
annot_padded = torch.ones((len(annots), 1, 5)) * -1
padded_imgs = padded_imgs.permute(0, 3, 1, 2)
image_data = ImageData(padded_imgs, annot_padded, scales)
return image_data
def detection_augment_list():
l = [
(Translate_Y, -0.3, 0.3),
(Translate_Y_BBoxes, -0.3, 0.3),
(Translate_X, -0.3, 0.3),
(Translate_X_BBoxes, -0.3, 0.3),
(CutOut, 6, 20),
(CutOut_BBoxes, 6, 20),
(Rotate, -30, 30),
(ShearX, -30, 30),
(ShearX_BBoxes, -30, 30),
(ShearY, -30, 30),
(ShearY_BBoxes, -30, 30),
(Equalize, 0, 1),
(Equalize_BBoxes, 0, 1),
(Solarize, -1., 1.),
(Solarize_BBoxes, -1., 1.),
(Color, 0., 3.),
(Color_BBoxes, 0., 3.),
(FlipLR, 0, 1)
]
return l
detection_augment_dict = {fn.__name__: (
fn, v1, v2) for fn, v1, v2 in detection_augment_list()}
def get_augment(name, detection=False):
if detection:
return detection_augment_dict[name]
else:
pass
def apply_augment(sample, name, level, detection=False):
augment_obj, low, high = get_augment(name, detection)
random_add = random.random() * 0.05
adjusted_level = (level + random_add) * (high - low) + low
augment_inst = augment_obj(adjusted_level)
return augment_inst(sample)
class Augmentation(object):
def __init__(self, policies, detection=True):
self.policies = policies
self.detection = detection
def __call__(self, sample):
for _ in range(1):
policy = random.choice(self.policies)
print("policy: ", policy)
for name, pr, level in [policy]:
if random.random() > pr:
continue
sample = apply_augment(sample, name, level, self.detection)
return sample
class Resizer(object):
"""Convert ndarrays in sample to Tensors."""
def __init__(self, min_side=608, max_side=1024):
self.min_side = min_side
self.max_side = max_side
def __call__(self, sample):
image, annots = sample[0], sample[1]
rows, cols, cns = image.shape
smallest_side = min(rows, cols)
# rescale the image so the smallest side is min_side
scale = self.min_side / smallest_side
# check if the largest side is now greater than max_side, which can happen
# when images have a large aspect ratio
largest_side = max(rows, cols)
if largest_side * scale > self.max_side:
scale = self.max_side / largest_side
# resize the image with the computed scale
image = skimage.transform.resize(
image, (int(round(rows * scale)), int(round((cols * scale)))))
rows, cols, cns = image.shape
# add padding for fpn
pad_w = 32 - rows % 32
pad_h = 32 - cols % 32
new_image = np.zeros(
(rows + pad_w, cols + pad_h, cns)).astype(np.float32)
new_image[:rows, :cols, :] = image.astype(np.float32)
annots[:, :4] *= scale
return torch.from_numpy(new_image), torch.from_numpy(annots), scale
class Augmenter(object):
"""Convert ndarrays in sample to Tensors."""
def __call__(self, sample, flip_x=0.5):
img, annots = sample[0], sample[1]
if np.random.rand() < flip_x:
img = img[:, ::-1, :]
rows, cols, channels = img.shape
x1 = annots[:, 0].copy()
x2 = annots[:, 2].copy()
x_tmp = x1.copy()
annots[:, 0] = cols - x2
annots[:, 2] = cols - x_tmp
return img, annots
class Normalizer(object):
def __init__(self):
self.mean = np.array([[[0.485, 0.456, 0.406]]])
self.std = np.array([[[0.229, 0.224, 0.225]]])
def __call__(self, sample):
image, annots = sample.image, sample.annot
return ((image.astype(np.float32) - self.mean) / self.std), annots
class UnNormalizer(object):
def __init__(self, mean=None, std=None):
if mean == None:
self.mean = [0.485, 0.456, 0.406]
else:
self.mean = mean
if std == None:
self.std = [0.229, 0.224, 0.225]
else:
self.std = std
def __call__(self, tensor):
"""
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
Returns:
Tensor: Normalized image.
"""
for t, m, s in zip(tensor, self.mean, self.std):
t.mul_(s).add_(m)
return tensor
class AspectRatioBasedSampler(Sampler):
def __init__(self, data_source, batch_size, drop_last):
self.data_source = data_source
self.batch_size = batch_size
self.drop_last = drop_last
self.groups = self.group_images()
def __iter__(self):
random.shuffle(self.groups)
for group in self.groups:
yield group
def __len__(self):
if self.drop_last:
return len(self.data_source) // self.batch_size
else:
return (len(self.data_source) + self.batch_size - 1) // self.batch_size
def group_images(self):
# determine the order of the images
order = list(range(len(self.data_source)))
order.sort(key=lambda x: self.data_source.image_aspect_ratio(x))
# divide into groups, one group = one batch
return [[order[x % len(order)] for x in range(i, i + self.batch_size)] for i in
range(0, len(order), self.batch_size)]
| [
"csv.reader",
"pandas.read_csv",
"random.shuffle",
"glob.glob",
"os.path.join",
"pandas.DataFrame",
"numpy.set_printoptions",
"numpy.append",
"torch.zeros",
"skimage.io.imsave",
"skimage.io.imread",
"PIL.Image.Image.open",
"random.random",
"skimage.color.gray2rgb",
"os.listdir",
"torch... | [((482, 516), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (501, 516), True, 'import numpy as np\n'), ((29500, 29549), 'torch.zeros', 'torch.zeros', (['batch_size', 'max_width', 'max_height', '(3)'], {}), '(batch_size, max_width, max_height, 3)\n', (29511, 29549), False, 'import torch\n'), ((14893, 14906), 'numpy.array', 'np.array', (['ann'], {}), '(ann)\n', (14901, 14906), True, 'import numpy as np\n'), ((15151, 15167), 'numpy.zeros', 'np.zeros', (['(0, 5)'], {}), '((0, 5))\n', (15159, 15167), True, 'import numpy as np\n'), ((18033, 18057), 'os.listdir', 'os.listdir', (['pred_on_path'], {}), '(pred_on_path)\n', (18043, 18057), False, 'import os\n'), ((20469, 20517), 'skimage.io.imread', 'skimage.io.imread', (['self.image_names[image_index]'], {}), '(self.image_names[image_index])\n', (20486, 20517), False, 'import skimage\n'), ((20824, 20840), 'numpy.zeros', 'np.zeros', (['(0, 5)'], {}), '((0, 5))\n', (20832, 20840), True, 'import numpy as np\n'), ((22197, 22238), 'PIL.Image.Image.open', 'Image.open', (['self.image_names[image_index]'], {}), '(self.image_names[image_index])\n', (22207, 22238), False, 'from PIL.Image import Image\n'), ((25765, 25813), 'skimage.io.imread', 'skimage.io.imread', (['self.image_names[image_index]'], {}), '(self.image_names[image_index])\n', (25782, 25813), False, 'import skimage\n'), ((26121, 26137), 'numpy.zeros', 'np.zeros', (['(0, 5)'], {}), '((0, 5))\n', (26129, 26137), True, 'import numpy as np\n'), ((29052, 29093), 'PIL.Image.Image.open', 'Image.open', (['self.image_names[image_index]'], {}), '(self.image_names[image_index])\n', (29062, 29093), False, 'from PIL.Image import Image\n'), ((31256, 31271), 'random.random', 'random.random', ([], {}), '()\n', (31269, 31271), False, 'import random\n'), ((33796, 33831), 'numpy.array', 'np.array', (['[[[0.485, 0.456, 0.406]]]'], {}), '([[[0.485, 0.456, 0.406]]])\n', (33804, 33831), True, 'import numpy as np\n'), ((33851, 33886), 'numpy.array', 'np.array', (['[[[0.229, 0.224, 0.225]]]'], {}), '([[[0.229, 0.224, 0.225]]])\n', (33859, 33886), True, 'import numpy as np\n'), ((34949, 34976), 'random.shuffle', 'random.shuffle', (['self.groups'], {}), '(self.groups)\n', (34963, 34976), False, 'import random\n'), ((6493, 6525), 'skimage.io.imread', 'skimage.io.imread', (['full_filename'], {}), '(full_filename)\n', (6510, 6525), False, 'import skimage\n'), ((13894, 13917), 'skimage.io.imread', 'skimage.io.imread', (['path'], {}), '(path)\n', (13911, 13917), False, 'import skimage\n'), ((15638, 15654), 'numpy.zeros', 'np.zeros', (['(1, 5)'], {}), '((1, 5))\n', (15646, 15654), True, 'import numpy as np\n'), ((15797, 15839), 'numpy.append', 'np.append', (['annotations', 'annotation'], {'axis': '(0)'}), '(annotations, annotation, axis=0)\n', (15806, 15839), True, 'import numpy as np\n'), ((20569, 20596), 'skimage.color.gray2rgb', 'skimage.color.gray2rgb', (['img'], {}), '(img)\n', (20591, 20596), False, 'import skimage\n'), ((21341, 21357), 'numpy.zeros', 'np.zeros', (['(1, 5)'], {}), '((1, 5))\n', (21349, 21357), True, 'import numpy as np\n'), ((21584, 21626), 'numpy.append', 'np.append', (['annotations', 'annotation'], {'axis': '(0)'}), '(annotations, annotation, axis=0)\n', (21593, 21626), True, 'import numpy as np\n'), ((25865, 25892), 'skimage.color.gray2rgb', 'skimage.color.gray2rgb', (['img'], {}), '(img)\n', (25887, 25892), False, 'import skimage\n'), ((26638, 26654), 'numpy.zeros', 'np.zeros', (['(1, 5)'], {}), '((1, 5))\n', (26646, 26654), True, 'import numpy as np\n'), ((26881, 26923), 'numpy.append', 'np.append', (['annotations', 'annotation'], {'axis': '(0)'}), '(annotations, annotation, axis=0)\n', (26890, 26923), True, 'import numpy as np\n'), ((29417, 29433), 'numpy.array', 'np.array', (['widths'], {}), '(widths)\n', (29425, 29433), True, 'import numpy as np\n'), ((29457, 29474), 'numpy.array', 'np.array', (['heights'], {}), '(heights)\n', (29465, 29474), True, 'import numpy as np\n'), ((31650, 31678), 'random.choice', 'random.choice', (['self.policies'], {}), '(self.policies)\n', (31663, 31678), False, 'import random\n'), ((33167, 33194), 'torch.from_numpy', 'torch.from_numpy', (['new_image'], {}), '(new_image)\n', (33183, 33194), False, 'import torch\n'), ((33196, 33220), 'torch.from_numpy', 'torch.from_numpy', (['annots'], {}), '(annots)\n', (33212, 33220), False, 'import torch\n'), ((33403, 33419), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (33417, 33419), True, 'import numpy as np\n'), ((2458, 2493), 'glob.glob', 'glob.glob', (["(dir_path + '/' + '*.png')"], {}), "(dir_path + '/' + '*.png')\n", (2467, 2493), False, 'import glob\n'), ((2609, 2644), 'glob.glob', 'glob.glob', (["(dir_path + '/' + '*.txt')"], {}), "(dir_path + '/' + '*.txt')\n", (2618, 2644), False, 'import glob\n'), ((3014, 3078), 'glob.glob', 'glob.glob', (["(dir_path + '/images/' + self.set_name + '/' + '*.jpg')"], {}), "(dir_path + '/images/' + self.set_name + '/' + '*.jpg')\n", (3023, 3078), False, 'import glob\n'), ((5142, 5237), 'glob.glob', 'glob.glob', (["(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] + '/' +\n '*.png')"], {}), "(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] +\n '/' + '*.png')\n", (5151, 5237), False, 'import glob\n'), ((7217, 7294), 'os.path.join', 'os.path.join', (['self.dir_path', '"""images"""', 'self.set_name', "image_info['file_name']"], {}), "(self.dir_path, 'images', self.set_name, image_info['file_name'])\n", (7229, 7294), False, 'import os\n'), ((9267, 9304), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (9278, 9304), False, 'import os\n'), ((9337, 9370), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (9349, 9370), False, 'import os\n'), ((9388, 9425), 'skimage.io.imsave', 'skimage.io.imsave', (['save_img_path', 'img'], {}), '(save_img_path, img)\n', (9405, 9425), False, 'import skimage\n'), ((13976, 14003), 'skimage.color.gray2rgb', 'skimage.color.gray2rgb', (['img'], {}), '(img)\n', (13998, 14003), False, 'import skimage\n'), ((32981, 33024), 'numpy.zeros', 'np.zeros', (['(rows + pad_w, cols + pad_h, cns)'], {}), '((rows + pad_w, cols + pad_h, cns))\n', (32989, 33024), True, 'import numpy as np\n'), ((2368, 2403), 'glob.glob', 'glob.glob', (["(dir_path + '/' + '*.jpg')"], {}), "(dir_path + '/' + '*.jpg')\n", (2377, 2403), False, 'import glob\n'), ((2404, 2440), 'glob.glob', 'glob.glob', (["(dir_path + '/' + '*.jpeg')"], {}), "(dir_path + '/' + '*.jpeg')\n", (2413, 2440), False, 'import glob\n'), ((3319, 3340), 'pycocotools.coco.COCO', 'COCO', (['self.annot_path'], {}), '(self.annot_path)\n', (3323, 3340), False, 'from pycocotools.coco import COCO\n'), ((3775, 3822), 'pandas.read_csv', 'pd.read_csv', (['self.dir_path_list[0]'], {'header': 'None'}), '(self.dir_path_list[0], header=None)\n', (3786, 3822), True, 'import pandas as pd\n'), ((4877, 4972), 'glob.glob', 'glob.glob', (["(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] + '/' +\n '*.jpg')"], {}), "(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] +\n '/' + '*.jpg')\n", (4886, 4972), False, 'import glob\n'), ((4991, 5087), 'glob.glob', 'glob.glob', (["(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] + '/' +\n '*.jpeg')"], {}), "(self.dir_path + '/' + self.dataset + '/' + self.data['0'][index] +\n '/' + '*.jpeg')\n", (5000, 5087), False, 'import glob\n'), ((10399, 10436), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (10410, 10436), False, 'import os\n'), ((10473, 10506), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (10485, 10506), False, 'import os\n'), ((10527, 10564), 'skimage.io.imsave', 'skimage.io.imsave', (['save_img_path', 'img'], {}), '(save_img_path, img)\n', (10544, 10564), False, 'import skimage\n'), ((10697, 10724), 'skimage.io.imread', 'skimage.io.imread', (['img_path'], {}), '(img_path)\n', (10714, 10724), False, 'import skimage\n'), ((11940, 11977), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (11951, 11977), False, 'import os\n'), ((12014, 12047), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (12026, 12047), False, 'import os\n'), ((12068, 12105), 'skimage.io.imsave', 'skimage.io.imsave', (['save_img_path', 'img'], {}), '(save_img_path, img)\n', (12085, 12105), False, 'import skimage\n'), ((22961, 22992), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (22971, 22992), False, 'import csv\n'), ((23462, 23493), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (23472, 23493), False, 'import csv\n'), ((31781, 31796), 'random.random', 'random.random', ([], {}), '()\n', (31794, 31796), False, 'import random\n'), ((3168, 3254), 'os.path.join', 'os.path.join', (['self.dir_path', '"""annotations"""', "('instances_' + self.set_name + '.json')"], {}), "(self.dir_path, 'annotations', 'instances_' + self.set_name +\n '.json')\n", (3180, 3254), False, 'import os\n'), ((3639, 3679), 'glob.glob', 'glob.glob', (["(self.dir_path + '/' + '*.csv')"], {}), "(self.dir_path + '/' + '*.csv')\n", (3648, 3679), False, 'import glob\n'), ((4669, 4687), 'pandas.DataFrame', 'pd.DataFrame', (['dict'], {}), '(dict)\n', (4681, 4687), True, 'import pandas as pd\n'), ((12817, 12854), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (12828, 12854), False, 'import os\n'), ((12891, 12924), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (12903, 12924), False, 'import os\n'), ((12945, 12982), 'skimage.io.imsave', 'skimage.io.imsave', (['save_img_path', 'img'], {}), '(save_img_path, img)\n', (12962, 12982), False, 'import skimage\n'), ((13159, 13236), 'os.path.join', 'os.path.join', (['self.img_path', '"""images"""', 'self.set_name', "image_info['file_name']"], {}), "(self.img_path, 'images', self.set_name, image_info['file_name'])\n", (13171, 13236), False, 'import os\n'), ((13650, 13687), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (13661, 13687), False, 'import os\n'), ((13724, 13757), 'os.path.join', 'os.path.join', (['save_path', 'filename'], {}), '(save_path, filename)\n', (13736, 13757), False, 'import os\n'), ((13778, 13815), 'skimage.io.imsave', 'skimage.io.imsave', (['save_img_path', 'img'], {}), '(save_img_path, img)\n', (13795, 13815), False, 'import skimage\n'), ((17669, 17700), 'csv.reader', 'csv.reader', (['file'], {'delimiter': '""","""'}), "(file, delimiter=',')\n", (17679, 17700), False, 'import csv\n'), ((18171, 18203), 'os.path.join', 'os.path.join', (['pred_on_path', 'name'], {}), '(pred_on_path, name)\n', (18183, 18203), False, 'import os\n'), ((4176, 4216), 'glob.glob', 'glob.glob', (["(self.dir_path + '/' + '*.txt')"], {}), "(self.dir_path + '/' + '*.txt')\n", (4185, 4216), False, 'import glob\n'), ((4272, 4298), 'glob.glob', 'glob.glob', (['annotation_path'], {}), '(annotation_path)\n', (4281, 4298), False, 'import glob\n')] |
"""
7. Reverse integer
Given an 32-bit signed integer, reverse the digits of an integer.
Example:
Input: 123
Output: 321
"""
class Solution:
def reverse(self, x: int) -> int:
# One way to do this is to iterate through powers of 10 and find the
# remainder after division. The reversed number would then be the
# remainder multiplied by the previous digit to the power of 10.
import numpy as np
# Handle case where the input is zero.
if x == 0:
return 0
sgn = np.sign(x)
x = np.abs(x)
pow = range(11, -1, -1) # 10^0 to 10^10
r = np.array([])
x_temp = x
for p in pow:
n = int(x / 10**p)
r = np.append(r, n)
if n > 0: # If the remainder is not zero, then keep the digit
x = x % 10**p # Update x with the remainder
# r now contains the digits that need to be reversed. However, we first
# need to remove any leading zeros
i = (r > 0).nonzero() # i is an array of ndarray
r = r[i[0][0]:]
# Now iterate over the elements in r
x = 0
for i in range(len(r)):
x = x + r[i] * 10**i
x = x * sgn
if (x < -2**31) | (x > (2**31 - 1)): x = 0
return int(x)
S = Solution()
S.reverse(123)
S.reverse(-123)
S.reverse(0) # Edge case -- causes a runtime error if not handled explicitly
"""
9. Palindrome number
Determine whether an integer is a palindrome.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false (is '121-' in reverse)
Example 3:
Input: 10
Output: false (reads '01' in reverse)
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
# For purposes of this exercise, it is probably easiest to convert the
# input into a string and reverse it. Doing things this way should
# make the problem fairly easy.
s = str(x)
s_rev = s[::-1]
return s == s_rev
S = Solution()
S.isPalindrome(121)
S.isPalindrome(-121)
S.isPalindrome(10)
"""
13. Roman numeral to integer
Convert a roman numeral to an integer.
I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000
Rules:
- Each letter can be repeated up to 3 times
- The preceeding letter can be placed in front to decrease the value (IV = 4)
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
"""
class Solution:
def romanToInt(self, s: str) -> int:
# Define two dicts. The first one indicates the order of the letters
# from largest to smallest. This is used to determine the sign of the
# numbers corresponding to each letter. The second dict specifies the
# absolute value of the number for each letter.
codes = {
'M': 1,
'D': 2,
'C': 3,
'L': 4,
'X': 5,
'V': 6,
'I': 7
}
values = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
# Approach: iterate through the letters in the input. If the current
# letter specifies a lower number and is before a higher number (e.g.,
# 'I' before 'M'), then that number is negative. Once this is done, the
# Number multiplied by the sign can simply added to the overall sum.
# Initialize the output
num = 0
# Iterate over the letters in the input string
for i in range(len(s)):
# First determine the sign. If the code for the current letter is
# greater than that of the next letter, the sign is negative.
# Otherwise, the sign is positive.
if i == len(s) - 1:
# If this is the last letter, the sign will always be positive
sign = 1
elif codes[s[i]] > codes[s[i+1]]:
# If the code for the current number is less than the code for
# the next number, then the sign is negative
sign = -1
else:
sign = 1
# Add the number for the current letter to the total number
num = num + (values[s[i]] * sign)
return num
S = Solution()
S.romanToInt('III')
S.romanToInt('IV')
S.romanToInt('IX')
S.romanToInt('LVIII')
"""
14. Largest common prefix
Write a function to find the longest common prefix from an array of strings. If
there is no common prefix, return and empty string "".
Example 1:
Input: ["flower", "flow", "flight"]
Output: "fl"
Example 2:
Input: ["dog", "racecar", "car"]
Output: ""
"""
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# Handle case where the input is empty.
if len(strs) == 0:
return ''
# Find the shortest element
l = len(min(strs, key=len))
# Iterate over elements in all
prefix = ''
for i in range(l):
# Check to see if all strings in the list have the same letter.
# Make sure to lower the case of all strings.
letter = []
for s in strs:
letter.append(s[i].lower())
# Compare all of the letters to see if they are the same. If so,
# add the letter to the list
if len(set(letter)) == 1:
prefix = prefix + letter[0]
else:
break
# Return the answer
return prefix
S = Solution()
S.longestCommonPrefix(['Flower', 'flow', 'flight'])
S.longestCommonPrefix(['dog', 'racecar', 'car'])
S.longestCommonPrefix([])
"""
20. Valid parentheses
Given a string containing just the characters '(', ')', '[', ']', '{', or '}',
determine if the input string is valid. An input string is valid if:
1. Open brackets are closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
An empty string is also considered valid.
Example 1:
Input: '()'
Output: true
Example 2:
Input: '()[]{}'
Output: true
Example 3:
Input: '(]'
Output: false
Example 4:
Input: '([)]'
Output: false
Example 5:
Input: '{[]}'
Output: true
"""
class Solution:
def isValid(self, s: str) -> bool:
# Approach: use a list as a queue -- If an open bracket is encountered,
# push the appropriate closed bracket onto the queue. If a closed
# bracket is encountered, compare it to the most recent element on the
# queue. If the next element in the string is not the most recent
# element on the queue, return FALSE. If the entire string is parsed,
# return TRUE.
# Check to see if the number of elements in the string is even. If not,
# the input string cannot be valid.
if len(s) % 2 != 0:
return False
# Define open and closed bracket sets
valid_open = {'(', '[', '{'}
valid_closed = {')', ']', '}'}
bracket_pairs = {
'(': ')',
'[': ']',
'{': '}',
}
# Iterate over string
buffer = []
for elem in s:
if elem in valid_open:
buffer.append(bracket_pairs[elem])
if elem in valid_closed:
# Check to make sure the queue is not empty. If it is, then
# return False, since this would mean there was no matching
# open bracket.
if len(buffer) == 0:
return False
if elem != buffer.pop():
return False
# If the entire string has been parsed, check to make sure there are
# no elements remaining in the cue. If so, the string is invalid.
if len(buffer) > 0:
return False
else:
return True
S = Solution()
S.isValid('()')
S.isValid('()[]{}')
S.isValid('(]')
S.isValid('([)]')
S.isValid('{[]}')
S.isValid('')
S.isValid('((')
S.isValid('){')
"""
21. Merge two sorted lists
Merge two sorted linked lists and return the merged list. The new list should be
made by splicing together the nodes of the first two lists.
A singly-linked list contains two elements: a value and a link to the next
element.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
We can take advantage of the fact that the two input lists are already
sorted. To do this, step through the two lists at the same time.
Add the smaller of the two to the merged list and repeat until the end
of one of the two lists is found. At this point, the next element in the
merged list can be set to the next element in the list that has not
been fully parsed.
"""
# Initialize the ListNode. Here we create two identical pointers so that
# we can keep track of the starting point of the list.
l_a = l_b = ListNode(0)
# While both lists have not been parsed, keep adding the smaller of the
# two values to the merged list
while l1 and l2: # True as long as one element isn't 'None'
if l1.val <= l2.val:
l_a.next = l1 # Update the pointer to the next element
l1 = l1.next
else:
l_a.next = l2
l2 = l2.next
l_a = l_a.next # Update pointer
# Once the while loop has completed, either l1 or l2 will still have
# elements left. Thus, just point the merged list to the node that is
# not 'None'
l_a.next = l1 or l2
return l_b.next
# Define lists for testing
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
# Test
S = Solution()
l3 = S.mergeTwoLists(l1, l2)
"""
26. Remove duplicates from a sorted array
Given a sorted array, remove the duplicates in-place such that each element
appears only once. Return the new length of the array. For purposes of this
exercise, assume that the array is passed by reference, meaning that sorting the
list in the function will also update the list outside of the function.
Example 1:
Input: [1, 1, 2]
Output: 2
Example 2:
Input: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: 5
"""
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
"""
Approach
Define:
uni_num -- current unique number
n_uni_el -- current number of elements
- Initialize UNI_NUM to the first element, N_UNI_EL to 1
- Iterate through the list one element at a time
- If the current number in the list is greater than UNI_NUM, update the
list accordingly and increment N_UNI_EL
"""
# Check to see if input list is empty
n_el = len(nums)
if n_el == 0:
return 0
# Iterate through list
uni_num = nums[0]
n_uni_el = 1
for i in range(1, n_el):
# Check to see if the current number is greater than the current
# unique number
if nums[i] > uni_num:
uni_num = nums[i]
nums[n_uni_el] = uni_num
n_uni_el += 1
return n_uni_el
S = Solution()
nums = [1, 1, 2]
S.removeDuplicates(nums)
print(nums)
nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
S.removeDuplicates(nums)
print(nums)
"""
27. Remove element
Given an array NUMS and a value VAL, remove all instances of that value
in-place and return the new length. Do not allocate extra space for another
array, this must be done by modifying the input array in-place with O(1) extra
memory. The order of the elements can be changed. It doesn't matter what is left
beyond the new length.
Example 1:
Input: nums = [3, 2, 2, 3], val = 3
Output: 2, first two elements of nums should be [2, 2]
Example 2:
Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output: 5, first 5 elements contains 0, 1, 3, 0, and 4
"""
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
# Get the number of elements in the input list
n = n_el = len(nums)
# Iterate over elements in the list
for i in range(n):
# Check to see if the current number in the list should be removed
# Note that this might need to happen multiple times.
while nums[i] == val:
# Decrement number of elements
n_el -= 1
# Shift all elements
for j in range(i, n-1):
nums[j] = nums[j+1]
# Once n_el is equal to i+1, all numbers have been parsed
if (i >= n_el) or n_el == 0:
return n_el
# Need to return n_el if the entire list has been parsed
return n_el
# Test cases
S = Solution()
nums = [3, 2, 2, 3]
val = 3
S.removeElement(nums, val)
nums = [0, 1, 2, 2, 3, 0, 4, 2]
val = 2
S.removeElement(nums, val)
nums = [4, 5]
val = 4
S.removeElement(nums, val)
nums = [3, 3]
val = 3
S.removeElement(nums, val)
"""
28. Implement strStr()
Return the first occurance of the substring NEEDLE in the longer string
HAYSTACK. Return '-1' if the substring is not part of the string.
Example 1:
Input: haystack = 'hello', needle = 'll'
Output: 2
Example 2:
Input: haystack = 'aaaaa', needle = 'bba'
Output: -1
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
"""
Approach
- Iterate though HAYSTACK element-by-element
- Check the next substring of the same length as NEEDLE
- If the string is the same, return the current index
- If the entire string has been parsed, return '-1'
"""
# If the substring is empty, return 0
n = len(haystack) # Number of elements in the search string
n_sub = len(needle) # Number of elements in the input string
if n_sub == 0:
return 0
# Check to see if the search string is longer than the input string.
# In this case, return -1
if n < n_sub:
return -1
# Iterate over elements in the string
for i in range(0, n-n_sub+1):
if needle == haystack[i:i+n_sub]:
# Substring has been found, return the current index
return i
# The entire string has been parsed w/o finding the string, return -1
return -1
# Test cases
S = Solution()
haystack = 'hello'
needle = 'll'
S.strStr(haystack, needle)
haystack = 'aaaaa'
needle = 'bba'
S.strStr(haystack, needle)
haystack = 'test'
needle = 'st'
S.strStr(haystack, needle)
haystack = 'a'
needle = 'a'
S.strStr(haystack, needle)
| [
"numpy.array",
"numpy.append",
"numpy.abs",
"numpy.sign"
] | [((546, 556), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (553, 556), True, 'import numpy as np\n'), ((569, 578), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (575, 578), True, 'import numpy as np\n'), ((640, 652), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (648, 652), True, 'import numpy as np\n'), ((741, 756), 'numpy.append', 'np.append', (['r', 'n'], {}), '(r, n)\n', (750, 756), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import numpy as np
import pytest
import megengine as mge
import megengine.distributed as dist
from megengine import tensor
from megengine.distributed.functional import (
all_gather,
all_to_all,
gather,
reduce_scatter_sum,
scatter,
)
from megengine.jit import trace
@pytest.mark.require_ngpu(2)
@pytest.mark.parametrize("shape", [(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)], ids=str)
@pytest.mark.parametrize("symbolic", [False, True], ids=str)
@pytest.mark.parametrize("axis", [0, 1], ids=str)
@pytest.mark.isolated_distributed
def test_all_gather(shape, symbolic, axis):
@dist.launcher(n_gpus=2)
def worker(data, expect):
rank = dist.get_rank()
inp = tensor(data[rank])
def func():
output = all_gather(inp, axis=axis)
return output
func = trace(symbolic=symbolic)(func)
output = func()
assert np.allclose(output.numpy(), expect[rank])
x = np.random.random_sample(shape).astype("float32")
y = np.random.random_sample(shape).astype("float32")
z = np.concatenate((x, y), axis=axis)
data = (x, y)
expect = (z, z)
worker(data, expect)
@pytest.mark.require_ngpu(2)
@pytest.mark.parametrize(
"shape,symbolic", [((2, 4, 6, 8), False), ((2, 4, 6, 8), True)], ids=str
)
@pytest.mark.parametrize("axis", [1, 0, 2, 3], ids=str)
@pytest.mark.isolated_distributed
def test_reduce_scatter_sum(shape, symbolic, axis):
@dist.launcher(n_gpus=2)
def worker(data, expect):
rank = dist.get_rank()
inp = tensor(data[rank])
def func():
output = reduce_scatter_sum(inp, axis=axis)
return output
func = trace(symbolic=symbolic)(func)
output = func()
assert np.allclose(output.numpy(), expect[rank])
x = np.random.random_sample(shape).astype("float32")
y = np.random.random_sample(shape).astype("float32")
z = x + y
data = (x, y)
z = np.split(z, 2, axis=axis)
z = np.concatenate(z, axis=0)
expect = (z[: z.shape[0] // 2], z[z.shape[0] // 2 :])
worker(data, expect)
@pytest.mark.require_ngpu(2)
@pytest.mark.parametrize(
"shape,symbolic", [((2, 4, 6, 8), True), ((2, 4, 6, 8), False)], ids=str
)
@pytest.mark.parametrize("axis", [1, 0, 2, 3], ids=str)
@pytest.mark.isolated_distributed
def test_scatter(shape, symbolic, axis):
@dist.launcher(n_gpus=2)
def worker(data, expect):
rank = dist.get_rank()
inp = tensor(data[rank])
def func():
output = scatter(inp, axis=axis)
return output
func = trace(symbolic=symbolic)(func)
output = func()
assert np.allclose(output.numpy(), expect[rank])
x = np.random.random_sample(shape).astype("float32")
y = x + 1
data = (x, y)
_x = np.split(x, 2, axis=axis)
_x = np.concatenate(_x, axis=0)
expect = (_x[: _x.shape[0] // 2], _x[_x.shape[0] // 2 :])
worker(data, expect)
@pytest.mark.require_ngpu(2)
@pytest.mark.parametrize("shape", [(2, 4, 6, 8)], ids=str)
@pytest.mark.parametrize("symbolic", [False, True], ids=str)
@pytest.mark.parametrize(
"split_axis,concat_axis", [(0, 1), (1, 0), (2, 0), (0, 2), (2, 3)], ids=str
)
@pytest.mark.isolated_distributed
def test_all_to_all(shape, symbolic, split_axis, concat_axis):
@dist.launcher(n_gpus=2)
def worker(data):
rank = dist.get_rank()
inp = tensor(data[rank])
def func():
all_to_all_output = all_to_all(
inp, split_axis=split_axis, concat_axis=concat_axis
)
gather_C = gather(inp, axis=concat_axis)
gather_B = gather(all_to_all_output, axis=split_axis)
if rank == 0:
return gather_B, gather_C
return all_to_all_output
func = trace(symbolic=symbolic)(func)
ret = func()
if rank == 0:
assert np.allclose(ret[0], ret[1])
x = np.random.random_sample(shape).astype("float32")
y = np.random.random_sample(shape).astype("float32")
data = (x, y)
worker(data)
| [
"megengine.tensor",
"numpy.random.random_sample",
"megengine.distributed.functional.reduce_scatter_sum",
"megengine.distributed.get_rank",
"megengine.distributed.functional.all_gather",
"megengine.distributed.functional.scatter",
"numpy.allclose",
"numpy.split",
"megengine.distributed.functional.all... | [((666, 693), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (690, 693), False, 'import pytest\n'), ((695, 783), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)]'], {'ids': 'str'}), "('shape', [(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)],\n ids=str)\n", (718, 783), False, 'import pytest\n'), ((781, 840), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbolic"""', '[False, True]'], {'ids': 'str'}), "('symbolic', [False, True], ids=str)\n", (804, 840), False, 'import pytest\n'), ((842, 890), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1]'], {'ids': 'str'}), "('axis', [0, 1], ids=str)\n", (865, 890), False, 'import pytest\n'), ((1538, 1565), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (1562, 1565), False, 'import pytest\n'), ((1567, 1668), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape,symbolic"""', '[((2, 4, 6, 8), False), ((2, 4, 6, 8), True)]'], {'ids': 'str'}), "('shape,symbolic', [((2, 4, 6, 8), False), ((2, 4, 6,\n 8), True)], ids=str)\n", (1590, 1668), False, 'import pytest\n'), ((1672, 1726), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[1, 0, 2, 3]'], {'ids': 'str'}), "('axis', [1, 0, 2, 3], ids=str)\n", (1695, 1726), False, 'import pytest\n'), ((2468, 2495), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (2492, 2495), False, 'import pytest\n'), ((2497, 2598), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape,symbolic"""', '[((2, 4, 6, 8), True), ((2, 4, 6, 8), False)]'], {'ids': 'str'}), "('shape,symbolic', [((2, 4, 6, 8), True), ((2, 4, 6,\n 8), False)], ids=str)\n", (2520, 2598), False, 'import pytest\n'), ((2602, 2656), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[1, 0, 2, 3]'], {'ids': 'str'}), "('axis', [1, 0, 2, 3], ids=str)\n", (2625, 2656), False, 'import pytest\n'), ((3326, 3353), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (3350, 3353), False, 'import pytest\n'), ((3355, 3412), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(2, 4, 6, 8)]'], {'ids': 'str'}), "('shape', [(2, 4, 6, 8)], ids=str)\n", (3378, 3412), False, 'import pytest\n'), ((3414, 3473), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbolic"""', '[False, True]'], {'ids': 'str'}), "('symbolic', [False, True], ids=str)\n", (3437, 3473), False, 'import pytest\n'), ((3475, 3579), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""split_axis,concat_axis"""', '[(0, 1), (1, 0), (2, 0), (0, 2), (2, 3)]'], {'ids': 'str'}), "('split_axis,concat_axis', [(0, 1), (1, 0), (2, 0),\n (0, 2), (2, 3)], ids=str)\n", (3498, 3579), False, 'import pytest\n'), ((974, 997), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (987, 997), True, 'import megengine.distributed as dist\n'), ((1438, 1471), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {'axis': 'axis'}), '((x, y), axis=axis)\n', (1452, 1471), True, 'import numpy as np\n'), ((1818, 1841), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (1831, 1841), True, 'import megengine.distributed as dist\n'), ((2322, 2347), 'numpy.split', 'np.split', (['z', '(2)'], {'axis': 'axis'}), '(z, 2, axis=axis)\n', (2330, 2347), True, 'import numpy as np\n'), ((2356, 2381), 'numpy.concatenate', 'np.concatenate', (['z'], {'axis': '(0)'}), '(z, axis=0)\n', (2370, 2381), True, 'import numpy as np\n'), ((2737, 2760), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (2750, 2760), True, 'import megengine.distributed as dist\n'), ((3174, 3199), 'numpy.split', 'np.split', (['x', '(2)'], {'axis': 'axis'}), '(x, 2, axis=axis)\n', (3182, 3199), True, 'import numpy as np\n'), ((3209, 3235), 'numpy.concatenate', 'np.concatenate', (['_x'], {'axis': '(0)'}), '(_x, axis=0)\n', (3223, 3235), True, 'import numpy as np\n'), ((3684, 3707), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (3697, 3707), True, 'import megengine.distributed as dist\n'), ((1043, 1058), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (1056, 1058), True, 'import megengine.distributed as dist\n'), ((1073, 1091), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (1079, 1091), False, 'from megengine import tensor\n'), ((1887, 1902), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (1900, 1902), True, 'import megengine.distributed as dist\n'), ((1917, 1935), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (1923, 1935), False, 'from megengine import tensor\n'), ((2806, 2821), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (2819, 2821), True, 'import megengine.distributed as dist\n'), ((2836, 2854), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (2842, 2854), False, 'from megengine import tensor\n'), ((3745, 3760), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (3758, 3760), True, 'import megengine.distributed as dist\n'), ((3775, 3793), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (3781, 3793), False, 'from megengine import tensor\n'), ((1134, 1160), 'megengine.distributed.functional.all_gather', 'all_gather', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (1144, 1160), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((1203, 1227), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (1208, 1227), False, 'from megengine.jit import trace\n'), ((1324, 1354), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (1347, 1354), True, 'import numpy as np\n'), ((1381, 1411), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (1404, 1411), True, 'import numpy as np\n'), ((1978, 2012), 'megengine.distributed.functional.reduce_scatter_sum', 'reduce_scatter_sum', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (1996, 2012), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((2055, 2079), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (2060, 2079), False, 'from megengine.jit import trace\n'), ((2176, 2206), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (2199, 2206), True, 'import numpy as np\n'), ((2233, 2263), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (2256, 2263), True, 'import numpy as np\n'), ((2897, 2920), 'megengine.distributed.functional.scatter', 'scatter', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (2904, 2920), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((2963, 2987), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (2968, 2987), False, 'from megengine.jit import trace\n'), ((3084, 3114), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (3107, 3114), True, 'import numpy as np\n'), ((3847, 3910), 'megengine.distributed.functional.all_to_all', 'all_to_all', (['inp'], {'split_axis': 'split_axis', 'concat_axis': 'concat_axis'}), '(inp, split_axis=split_axis, concat_axis=concat_axis)\n', (3857, 3910), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((3964, 3993), 'megengine.distributed.functional.gather', 'gather', (['inp'], {'axis': 'concat_axis'}), '(inp, axis=concat_axis)\n', (3970, 3993), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((4017, 4059), 'megengine.distributed.functional.gather', 'gather', (['all_to_all_output'], {'axis': 'split_axis'}), '(all_to_all_output, axis=split_axis)\n', (4023, 4059), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((4181, 4205), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (4186, 4205), False, 'from megengine.jit import trace\n'), ((4274, 4301), 'numpy.allclose', 'np.allclose', (['ret[0]', 'ret[1]'], {}), '(ret[0], ret[1])\n', (4285, 4301), True, 'import numpy as np\n'), ((4311, 4341), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (4334, 4341), True, 'import numpy as np\n'), ((4368, 4398), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (4391, 4398), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import shutil
import argparse
import itertools
from Bio import SeqIO
import funannotate.library as lib
from funannotate.interlap import InterLap
from collections import defaultdict
from natsort import natsorted
import numpy as np
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.SeqIO.QualityIO import FastqGeneralIterator
def validateCDSmRNAPairs(gene, cds, mrna, strand):
'''
function to make sure CDS is contained inside mRNA exons
input is a list of lists of tuples for each
return the correctly phased lists, only move the mRNA as CDS is tied to the id
'''
def _order(lst):
return lst == sorted(lst) or lst == sorted(lst)[::-1]
# load first mRNA exon into InterLap
combined = []
num = len(cds)
warning = False
for i in range(0, num):
if strand == '+':
sortCDS = sorted(cds[i], key=lambda tup: tup[0])
else:
sortCDS = sorted(cds[i], key=lambda tup: tup[0], reverse=True)
compatible = []
for x in range(0, num):
if strand == '+':
sortExon = sorted(mrna[x], key=lambda tup: tup[0])
else:
sortExon = sorted(
mrna[x], key=lambda tup: tup[0], reverse=True)
# simple first, if more cds than exons it is not compatible
if len(sortCDS) > len(sortExon):
compatible.append(False)
continue
result = True
inter = InterLap(mrna[x])
for i, coord in enumerate(sortCDS):
if coord in inter:
hit = list(inter.find(coord))[0]
diff = np.subtract(coord, hit)
# then it cannot contain the cds so has to be wrong
if diff[0] < 0 or diff[1] > 0:
result = False
if len(sortCDS) > 1:
# if an internal CDS, then must match perfectly or its wrong
if i != 0 or (i+1) != len(sortCDS):
if diff[0] != 0 and diff[1] != 0:
result = False
elif i == 0:
if strand == '+':
if diff[1] != 0:
result = False
else:
if diff[0] != 0:
result = False
elif (i+1) == len(sortCDS):
if strand == '+':
if diff[0] != 0:
return False
else:
if diff[1] != 0:
return False
compatible.append(result)
combined.append(compatible)
valid_orders = []
for test in list(itertools.permutations(list(range(0, len(combined))), len(combined))):
# test is a tuple, slice list to see if all True
tester = []
for num, x in enumerate(test):
tester.append(combined[num][x])
if all(tester):
valid_orders.append(list(test))
mRNA_order = valid_orders[0]
if not _order(mRNA_order):
lib.log.debug(
'%s CDS/mRNA features out of phase, trying to fix. %s' % (gene, mRNA_order))
if len(valid_orders) > 1:
lib.log.debug(
'%s had %i possible solutions for CDS/mRNA, expect errors...' % (gene, len(valid_orders)))
warning = True
mRNAout = []
for y in mRNA_order:
mRNAout.append(mrna[y])
return cds, mRNAout, warning
def gbk2pasaNEW(input, gff, trnaout, fastaout, spliceout, exonout, proteinsout):
'''
function is to parse a genbank flat file and move protein coding genes into GFF3
and then parse out splice sites for hisat2. also filter tRNA gene models and move to
new GFF3 file for adding back after PASA
'''
LocusTags = []
multiExon = {}
genes = {}
with open(fastaout, 'w') as fasta:
with open(input, 'r') as gbk:
for record in SeqIO.parse(gbk, 'genbank'):
fasta.write(">%s\n%s\n" % (record.id, record.seq))
for f in record.features:
lib.gb_feature_add2dict(f, record, genes)
# out of order mRNA/CDS in genbank files can break this... so try to validate those with multiple transcripts
warn = False
for k, v in natsorted(list(genes.items())):
if v['type'] == 'mRNA' and len(v['ids']) > 1:
confirmedCDS, confirmedExons, warning = validateCDSmRNAPairs(
k, v['CDS'], v['mRNA'], v['strand'])
if warning:
warn = True
genes[k]['CDS'] = confirmedCDS
genes[k]['mRNA'] = confirmedExons
if warn:
lib.log.info("GenBank file has multiple transcripts per locus, I tried my hardest to match them up but can't gaurantee there aren't errors. You can blame NCBI. You may want to try to pass a GFF3 + FASTA files instead of GBK.")
with open(gff, 'w') as gffout:
gffout.write('##gff-version 3\n')
with open(trnaout, 'w') as trna:
with open(proteinsout, 'w') as protout:
for k, v in natsorted(list(genes.items())):
if not k in LocusTags:
LocusTags.append(k)
if v['type'] == 'mRNA':
# write GFF gene feature
if v['name']:
gffout.write("{:}\tGenBank\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};Name={:};\n".format(
v['contig'], v['location'][0], v['location'][1], v['strand'], k, v['name']))
else:
gffout.write("{:}\tGenBank\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};\n".format(
v['contig'], v['location'][0], v['location'][1], v['strand'], k))
for i in range(0, len(v['ids'])):
# now write mRNA feature
gffout.write("{:}\tGenBank\t{:}\t{:}\t{:}\t.\t{:}\t.\tID={:};Parent={:};product={:};\n".format(
v['contig'], v['type'], v['location'][0], v['location'][1], v['strand'], v['ids'][i], k, v['product'][i]))
protout.write('>%s %s\n%s\n' %
(v['ids'][i], k, v['protein'][i]))
# write the exons and CDS features
num_exons = len(v['mRNA'][i])
for x in range(0, num_exons):
ex_num = x + 1
gffout.write("{:}\tGenBank\texon\t{:}\t{:}\t.\t{:}\t.\tID={:}.exon{:};Parent={:};\n".format(
v['contig'], v['mRNA'][i][x][0], v['mRNA'][i][x][1], v['strand'], v['ids'][i], ex_num, v['ids'][i]))
if num_exons > 1:
# ss and exons are 0-based position, so 1 less than GFF
exons_start = int(v['mRNA'][i][x][0]) - 1
exons_end = int(v['mRNA'][i][x][1]) - 1
# add to exon dictionary
if not v['ids'][i] in multiExon:
multiExon[v['ids'][i]] = [
v['contig'], v['strand'], [(exons_start, exons_end)]]
else:
multiExon[v['ids'][i]][2].append(
(exons_start, exons_end))
num_cds = len(v['CDS'][i])
# GFF3 phase is 1 less than flat file
current_phase = v['codon_start'][i] - 1
for y in range(0, num_cds):
gffout.write("{:}\tGenBank\tCDS\t{:}\t{:}\t.\t{:}\t{:}\tID={:}.cds;Parent={:};\n".format(
v['contig'], v['CDS'][i][y][0], v['CDS'][i][y][1], v['strand'], current_phase, v['ids'][i], v['ids'][i]))
current_phase = (
current_phase - (int(v['CDS'][i][y][1]) - int(v['CDS'][i][y][0]) + 1)) % 3
if current_phase == 3:
current_phase = 0
elif v['type'] in ['tRNA', 'rRNA', 'ncRNA']:
# check length of tRNA gene should be between 50 and 150
if v['type'] == 'tRNA':
if v['strand'] == '+':
length = abs(
int(v['location'][1]) - int(v['location'][0]))
else:
length = abs(
int(v['location'][0]) - int(v['location'][1]))
else:
length = 100 # just a placeholder for rRNA features --> not sure if they have length requirements?
if length < 50 or length > 150:
continue
trna.write("{:}\tGenBank\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};\n".format(
v['contig'], v['location'][0], v['location'][1], v['strand'], k))
for i in range(0, len(v['ids'])):
trna.write("{:}\tGenBank\t{:}\t{:}\t{:}\t.\t{:}\t.\tID={:};Parent={:};product={:};\n".format(
v['contig'], v['type'], v['location'][0], v['location'][1], v['strand'], v['ids'][i], k, v['product'][i]))
if v['type'] == 'tRNA':
num_exons = len(v['mRNA'][i])
for x in range(0, num_exons):
ex_num = x + 1
trna.write("{:}\tGenBank\texon\t{:}\t{:}\t.\t{:}\t.\tID={:}.exon{:};Parent={:};\n".format(
v['contig'], v['mRNA'][i][x][0], v['mRNA'][i][x][1], v['strand'], v['ids'][i], ex_num, v['ids'][i]))
# parse splice sites and write to file
with open(exonout, 'w') as exon:
with open(spliceout, 'w') as splicer:
for k, v in natsorted(list(multiExon.items())):
sortedList = sorted(v[2], key=lambda tup: tup[0])
for y in sortedList:
exon.write("%s\t%i\t%i\t%s\n" % (v[0], y[0], y[1], v[1]))
splices = []
for i in range(1, len(sortedList)):
splices.append((sortedList[i-1][1], sortedList[i][0]))
for x in splices:
splicer.write('%s\t%i\t%i\t%s\n' %
(v[0], x[0], x[1], v[1]))
# finally lets return the base locus tag name and the last number
lastTag = natsorted(LocusTags)[-1]
if '_' in lastTag:
tag, count = lastTag.split('_')
tag = tag+'_'
else:
for i, c in enumerate(lastTag):
if c.isdigit():
tag = lastTag[:i]
count = lastTag[i:]
break
justify = len(count)
return tag, count, justify
def gff2pasa(gff_in, fasta, gff_out, trnaout, spliceout, exonout):
'''
function to parse GFF3 input file and split protein coding models from tRNA and/or rRNA
models. Generate Hisat2 splice and exon files for mapping.
'''
# load into funanotate structured dictionary
LocusTags = []
multiExon = {}
genes = {}
genes = lib.gff2dict(gff_in, fasta, genes)
# now loop through dictionary and output desired files
with open(gff_out, 'w') as gffout:
gffout.write('##gff-version 3\n')
with open(trnaout, 'w') as trna:
for k, v in natsorted(list(genes.items())):
if not k in LocusTags:
LocusTags.append(k)
if v['type'] == 'mRNA':
# write GFF gene feature
if v['name']:
gffout.write("{:}\t{:}\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};Name={:};\n".format(
v['contig'], v['source'], v['location'][0], v['location'][1], v['strand'], k, v['name']))
else:
gffout.write("{:}\t{:}\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};\n".format(
v['contig'], v['source'], v['location'][0], v['location'][1], v['strand'], k))
for i in range(0, len(v['ids'])):
# now write mRNA feature
gffout.write("{:}\t{:}\t{:}\t{:}\t{:}\t.\t{:}\t.\tID={:};Parent={:};product={:};\n".format(
v['contig'], v['source'], v['type'], v['location'][0], v['location'][1], v['strand'], v['ids'][i], k, v['product'][i]))
# write the exons and CDS features
num_exons = len(v['mRNA'][i])
for x in range(0, num_exons):
ex_num = x + 1
gffout.write("{:}\t{:}\texon\t{:}\t{:}\t.\t{:}\t.\tID={:}.exon{:};Parent={:};\n".format(
v['contig'], v['source'], v['mRNA'][i][x][0], v['mRNA'][i][x][1], v['strand'], v['ids'][i], ex_num, v['ids'][i]))
if num_exons > 1:
# ss and exons are 0-based position, so 1 less than GFF
exons_start = int(v['mRNA'][i][x][0]) - 1
exons_end = int(v['mRNA'][i][x][1]) - 1
# add to exon dictionary
if not v['ids'][i] in multiExon:
multiExon[v['ids'][i]] = [
v['contig'], v['strand'], [(exons_start, exons_end)]]
else:
multiExon[v['ids'][i]][2].append(
(exons_start, exons_end))
num_cds = len(v['CDS'][i])
# GFF3 phase is 1 less than flat file
current_phase = v['codon_start'][i] - 1
for y in range(0, num_cds):
gffout.write("{:}\t{:}\tCDS\t{:}\t{:}\t.\t{:}\t{:}\tID={:}.cds;Parent={:};\n".format(
v['contig'], v['source'], v['CDS'][i][y][0], v['CDS'][i][y][1], v['strand'], current_phase, v['ids'][i], v['ids'][i]))
current_phase = (
current_phase - (int(v['CDS'][i][y][1]) - int(v['CDS'][i][y][0]) + 1)) % 3
if current_phase == 3:
current_phase = 0
elif v['type'] in ['tRNA', 'rRNA', 'ncRNA']:
# check length of tRNA gene should be between 50 and 150
if v['type'] == 'tRNA':
if v['strand'] == '+':
length = abs(
int(v['location'][1]) - int(v['location'][0]))
else:
length = abs(
int(v['location'][0]) - int(v['location'][1]))
else:
length = 100 # just a placeholder for rRNA features --> not sure if they have length requirements?
if length < 50 or length > 150:
continue
trna.write("{:}\t{:}\tgene\t{:}\t{:}\t.\t{:}\t.\tID={:};\n".format(
v['contig'], v['source'], v['location'][0], v['location'][1], v['strand'], k))
for i in range(0, len(v['ids'])):
trna.write("{:}\t{:}\t{:}\t{:}\t{:}\t.\t{:}\t.\tID={:};Parent={:};product={:};\n".format(
v['contig'], v['source'], v['type'], v['location'][0], v['location'][1], v['strand'], v['ids'][i], k, v['product'][i]))
if v['type'] == 'tRNA':
num_exons = len(v['mRNA'][i])
for x in range(0, num_exons):
ex_num = x + 1
trna.write("{:}\t{:}\texon\t{:}\t{:}\t.\t{:}\t.\tID={:}.exon{:};Parent={:};\n".format(
v['contig'], v['source'], v['mRNA'][i][x][0], v['mRNA'][i][x][1], v['strand'], v['ids'][i], ex_num, v['ids'][i]))
# parse splice sites and write to file
with open(exonout, 'w') as exon:
with open(spliceout, 'w') as splicer:
for k, v in natsorted(list(multiExon.items())):
sortedList = sorted(v[2], key=lambda tup: tup[0])
for y in sortedList:
exon.write("%s\t%i\t%i\t%s\n" % (v[0], y[0], y[1], v[1]))
splices = []
for i in range(1, len(sortedList)):
splices.append((sortedList[i-1][1], sortedList[i][0]))
for x in splices:
splicer.write('%s\t%i\t%i\t%s\n' %
(v[0], x[0], x[1], v[1]))
# finally lets return the base locus tag name and the last number
lastTag = natsorted(LocusTags)[-1]
if '_' in lastTag:
tag, count = lastTag.split('_')
tag = tag+'_'
try:
count = int(count)
except ValueError: #means it is not a number, so then count gens
count = len(LocusTags) + 1
else:
for i, c in enumerate(lastTag):
if c.isdigit():
tag = lastTag[:i]
count = lastTag[i:]
break
count = str(count)
justify = len(count)
return tag, count, justify
def Funzip(input, output, cpus):
'''
function to unzip as fast as it can, pigz -> bgzip -> gzip
'''
if lib.which('pigz'):
cmd = ['pigz', '--decompress', '-c', '-p', str(cpus), input]
else:
cmd = ['gzip', '--decompress', '-c', input]
try:
lib.runSubprocess2(cmd, '.', lib.log, output)
except NameError:
with open(output, 'w') as outfile:
subprocess.call(cmd, stdout=outfile)
def Fzip(input, output, cpus):
'''
function to zip as fast as it can, pigz -> bgzip -> gzip
'''
if lib.which('pigz'):
cmd = ['pigz', '-c', '-p', str(cpus), input]
else:
cmd = ['gzip', '-c', input]
try:
lib.runSubprocess2(cmd, '.', lib.log, output)
except NameError:
with open(output, 'w') as outfile:
subprocess.call(cmd, stdout=outfile)
def runTrimmomaticPE(left, right, cpus=1):
'''
function is wrapper for Trinity trimmomatic
'''
# create tmpdir
folder = os.path.join(tmpdir, 'trimmomatic')
if not os.path.isdir(folder):
os.makedirs(folder)
lib.log.info("Adapter and Quality trimming PE reads with Trimmomatic")
left_paired = os.path.join(folder, 'trimmed_left.fastq')
left_single = os.path.join(folder, 'trimmed_left.unpaired.fastq')
right_paired = os.path.join(folder, 'trimmed_right.fastq')
right_single = os.path.join(folder, 'trimmed_right.unpaired.fastq')
cmd = ['trimmomatic', 'PE', '-threads', str(cpus), '-phred33',
left, right, left_paired, left_single, right_paired, right_single,
'ILLUMINACLIP:' +
os.path.join(parentdir, 'config', 'TruSeq3-PE.fa')+':2:30:10',
'SLIDINGWINDOW:4:5', 'LEADING:5', 'TRAILING:5', 'MINLEN:25']
lib.runSubprocess(cmd, '.', lib.log)
for x in [left_paired, left_single, right_paired, right_single]:
lib.Fzip_inplace(x, cpus)
trim_left = os.path.join(folder, 'trimmed_left.fastq.gz')
trim_right = os.path.join(folder, 'trimmed_right.fastq.gz')
return trim_left, trim_right
def runTrimmomaticSE(reads, cpus=1):
'''
function is wrapper for Trinity trimmomatic
'''
# create tmpdir
folder = os.path.join(tmpdir, 'trimmomatic')
if not os.path.isdir(folder):
os.makedirs(folder)
lib.log.info("Adapter and Quality trimming SE reads with Trimmomatic")
output = os.path.join(folder, 'trimmed_single.fastq')
cmd = ['trimmomatic', 'SE', '-threads', str(cpus), '-phred33',
reads, output, 'ILLUMINACLIP:' +
os.path.join(parentdir, 'config', 'TruSeq3-SE.fa')+':2:30:10',
'SLIDINGWINDOW:4:5', 'LEADING:5', 'TRAILING:5', 'MINLEN:25']
lib.runSubprocess(cmd, '.', lib.log)
lib.Fzip_inplace(output, cpus)
trim_single = os.path.join(folder, 'trimmed_single.fastq.gz')
return trim_single
def runNormalization(readTuple, memory, min_coverage=5, coverage=50, cpus=1, stranded='no'):
'''
function is wrapper for Trinity read normalization
have to run normalization separately for PE versus single
'''
left_norm, right_norm, single_norm = (None,)*3
SENormalLog = os.path.join(tmpdir, 'trinity_normalization.SE.log')
PENormalLog = os.path.join(tmpdir, 'trinity_normalization.PE.log')
lib.log.info("Running read normalization with Trinity")
if stranded != 'no':
cmd = [os.path.join(TRINITY, 'util', 'insilico_read_normalization.pl'), '--PARALLEL_STATS',
'--JM', memory, '--min_cov', str(
min_coverage), '--max_cov', str(coverage),
'--seqType', 'fq', '--output', os.path.join(
tmpdir, 'normalize'), '--CPU', str(cpus),
'--SS_lib_type', stranded]
else:
cmd = [os.path.join(TRINITY, 'util', 'insilico_read_normalization.pl'), '--PARALLEL_STATS',
'--JM', memory, '--min_cov', str(
min_coverage), '--max_cov', str(coverage),
'--seqType', 'fq', '--output', os.path.join(tmpdir, 'normalize'), '--CPU', str(cpus)]
if readTuple[2]: # single reads present, so run normalization just on those reads
cmd = cmd + ['--single', readTuple[2]]
lib.runSubprocess2(cmd, '.', lib.log, SENormalLog)
single_norm = os.path.join(tmpdir, 'normalize', 'single.norm.fq')
if readTuple[0] and readTuple[1]:
cmd = cmd + ['--pairs_together', '--left',
readTuple[0], '--right', readTuple[1]]
left_norm = os.path.join(tmpdir, 'normalize', 'left.norm.fq')
right_norm = os.path.join(tmpdir, 'normalize', 'right.norm.fq')
lib.runSubprocess2(cmd, '.', lib.log, PENormalLog)
return left_norm, right_norm, single_norm
def concatenateReads(input, output):
'''
Since I can't seem to get the comma separated lists to work with subprocess modules, just
concatenate FASTQ files in order and use a single file, input should be a list of FASTQ files
using system cat here so that gzipped files are concatenated correctly
'''
cmd = ['cat']
cmd = cmd + input
lib.runSubprocess2(cmd, '.', lib.log, output)
def getPASAinformation(configFile, DBname, folder, genome):
'''
function to dump GFF from existing PASA database, compare genome headers to what is in PASA
DB to make sure genome is same, return True if good to go, else error out
'''
# run some checks of the data to make sure it is same assembly
mysqlDB, mysqlUser, mysqlPass = (None,)*3
pasaconf_file = os.path.join(PASA, 'pasa_conf', 'conf.txt')
if os.environ.get('PASACONF'):
pasaconf_file = os.environ.get('PASACONF').strip()
with open(pasaconf_file, 'r') as pasaconf:
for line in pasaconf:
line = line.replace('\n', '')
if line.startswith('MYSQLSERVER='):
mysqlDB = line.split('=')[-1]
if line.startswith('MYSQL_RW_USER='):
mysqlUser = line.split('=')[-1]
if line.startswith('MYSQL_RW_PASSWORD='):
mysqlPass = line.split('=')[-1]
pasaExistingGFF = os.path.join(folder, 'existing_pasa.gff3')
cmd = [os.path.join(PASA, 'scripts', 'pasa_asmbl_genes_to_GFF3.dbi'),
'-M', DBname+':'+mysqlDB, '-p', mysqlUser+':'+mysqlPass]
lib.runSubprocess2(cmd, folder, lib.log, pasaExistingGFF)
if not lib.checkannotations(pasaExistingGFF):
return False
# now get number of genes and list of contigs
pasaContigs = []
geneCount = 0
with open(pasaExistingGFF, 'r') as infile:
for line in infile:
if line.startswith('\n'):
continue
cols = line.split('\t')
if not cols[0] in pasaContigs:
pasaContigs.append(cols[0])
if cols[2] == 'gene':
geneCount += 1
# now get fasta headers from genome
genomeContigs = []
with open(genome, 'r') as fasta:
for line in fasta:
if line.startswith('>'):
line = line.replace('\n', '')
line = line.replace('>', '')
if not line in genomeContigs:
genomeContigs.append(line)
# now make sure PASA headers in genome
genomeContigs = set(genomeContigs)
for contig in pasaContigs:
if not contig in genomeContigs:
return False
lib.log.info(
"Existing PASA database contains {:,} gene models, validated FASTA headers match".format(geneCount))
return True
def runPASA(genome, transcripts, cleanTranscripts, gff3_alignments,
stringtie_gtf, stranded, intronlen, cpus, previousGFF, dbname,
output, configFile, pasa_db='sqlite',
pasa_alignment_overlap=30, aligners=['blat'], min_pct_aligned=90,
min_avg_id=95, num_bp_perfect=3):
'''
function will run PASA align assembly, followed by 2 rounds of comparison to update
annotations for preexisting gene models
'''
pasa_cpus = int(cpus)
# create tmpdir
folder = os.path.join(tmpdir, 'pasa')
if not os.path.isdir(folder):
os.makedirs(folder)
pasaLOG = os.path.join(folder, 'pasa-assembly.log')
pasaLOG1 = os.path.join(folder, 'pasa-comparison1.log')
pasaLOG2 = os.path.join(folder, 'pasa-comparison2.log')
# get config files and edit
alignConfig = os.path.join(folder, 'alignAssembly.txt')
annotConfig = os.path.join(folder, 'annotCompare.txt')
# check if config file is passed, if so, get databasename and copy to assembly config file
# dashes will get stripped in MySQL
DataBaseName = dbname.replace('-', '_')
if pasa_db == 'sqlite':
DataBaseName = os.path.abspath(os.path.join(folder, DataBaseName))
if configFile:
with open(configFile, 'r') as infile:
for line in infile:
line = line.replace('\n', '')
if line.startswith('DATABASE=') or line.startswith('MYSQLDB='):
DataBaseName = line.split('=')[-1]
shutil.copyfile(configFile, alignConfig)
if pasa_db == 'mysql':
# check existing database
if not getPASAinformation(configFile, DataBaseName, folder, genome):
lib.log.error(
"MySQL database not found or headers in PASA database, do not match those in FASTA.")
# now run PASA alignment step
lib.log.info("Running PASA alignment step using " +
"{0:,}".format(lib.countfasta(cleanTranscripts))+" transcripts")
cmd = [LAUNCHPASA, '-c', os.path.abspath(alignConfig), '-r', '-C', '-R', '-g', os.path.abspath(genome),
'--IMPORT_CUSTOM_ALIGNMENTS', gff3_alignments, '-T',
'-t', os.path.abspath(
cleanTranscripts), '-u', os.path.abspath(transcripts),
'--stringent_alignment_overlap', pasa_alignment_overlap, '--TRANSDECODER',
'--MAX_INTRON_LENGTH', str(intronlen), '--CPU', str(pasa_cpus)]
if 'minimap2' in aligners:
aligners.remove('minimap2')
if aligners:
cmd.append('--ALIGNERS')
cmd.append(','.join(aligners))
if stranded != 'no':
cmd = cmd + ['--transcribed_is_aligned_orient']
if lib.checkannotations(stringtie_gtf):
cmd = cmd + ['--trans_gtf', stringtie_gtf]
lib.runSubprocess6(cmd, folder, lib.log, pasaLOG)
else:
lib.log.info('PASA database is SQLite: {:}'.format(DataBaseName))
# finally need to index the genome using cdbfasta so lookups can be done
CDBFASTA = lib.which_path('cdbfasta')
if not CDBFASTA:
CDBFASTA = os.path.join(PASA, 'bin', 'cdbfasta')
cmd = [CDBFASTA, genome]
lib.runSubprocess(cmd, '.', lib.log)
else:
# create new config file from template
with open(alignConfig, 'w') as config1:
with open(os.path.join(PASA, 'pasa_conf', 'pasa.alignAssembly.Template.txt'), 'r') as template1:
for line in template1:
if '<__DATABASE__>' in line:
line = line.replace('<__DATABASE__>', DataBaseName)
elif '<__MYSQLDB__>' in line:
line = line.replace('<__MYSQLDB__>', DataBaseName)
elif line.startswith('#script validate_alignments_in_db.dbi'):
line = line + '\n' + 'validate_alignments_in_db.dbi:--NUM_BP_PERFECT_SPLICE_BOUNDARY={}\n'.format(num_bp_perfect)
elif '<__MIN_PERCENT_ALIGNED__>' in line:
line = line.replace('<__MIN_PERCENT_ALIGNED__>', str(min_pct_aligned))
elif '<__MIN_AVG_PER_ID__>' in line:
line = line.replace('<__MIN_AVG_PER_ID__>', str(min_avg_id))
config1.write(line)
# align transcripts using minimap2
# now run PASA alignment step
lib.log.info("Running PASA alignment step using " +
"{0:,}".format(lib.countfasta(cleanTranscripts))+" transcripts")
cmd = [LAUNCHPASA, '-c', os.path.abspath(alignConfig), '-r', '-C',
'-R', '-g', os.path.abspath(genome),
'--IMPORT_CUSTOM_ALIGNMENTS', gff3_alignments, '-T',
'-t', os.path.abspath(cleanTranscripts),
'-u', os.path.abspath(transcripts),
'--stringent_alignment_overlap', pasa_alignment_overlap,
'--TRANSDECODER',
'--MAX_INTRON_LENGTH', str(intronlen), '--CPU', str(pasa_cpus)]
cmd += ['--ALIGNERS']
filtaligners = []
for x in aligners:
if x != 'minimap2':
filtaligners.append(x)
cmd.append(','.join(filtaligners))
if stranded != 'no':
cmd = cmd + ['--transcribed_is_aligned_orient']
if lib.checkannotations(stringtie_gtf):
cmd = cmd + ['--trans_gtf', stringtie_gtf]
lib.runSubprocess6(cmd, folder, lib.log, pasaLOG)
# generate comparison template file
with open(annotConfig, 'w') as config2:
with open(os.path.join(PASA, 'pasa_conf', 'pasa.annotationCompare.Template.txt'), 'r') as template2:
for line in template2:
line = line.replace('<__MYSQLDB__>', DataBaseName)
line = line.replace('<__DATABASE__>', DataBaseName)
config2.write(line)
# now run Annotation comparisons
lib.log.info("Running PASA annotation comparison step 1")
cmd = [LAUNCHPASA, '-c', os.path.abspath(annotConfig),
'-g', os.path.abspath(genome),
'-t', os.path.abspath(cleanTranscripts),
'-A', '-L', '--CPU', str(pasa_cpus)]
if lib.versionCheck(PASAVERSION, '2.3.0'):
cmd = cmd + ['--annots', os.path.abspath(previousGFF)]
else:
cmd = cmd + ['--annots_gff3', os.path.abspath(previousGFF)]
lib.runSubprocess6(cmd, folder, lib.log, pasaLOG1)
round1GFF = None
for file in os.listdir(folder):
if not file.endswith('.gff3'):
continue
if 'gene_structures_post_PASA_updates' in file:
round1GFF = os.path.join(folder, file)
if not round1GFF:
lib.log.error("PASA failed, check log, exiting")
sys.exit(1)
# run round 2 comparison
lib.log.info("Running PASA annotation comparison step 2")
cmd = [LAUNCHPASA, '-c', os.path.abspath(annotConfig),
'-g', os.path.abspath(genome),
'-t', os.path.abspath(cleanTranscripts),
'-A', '-L', '--CPU', str(pasa_cpus)]
if lib.versionCheck(PASAVERSION, '2.3.0'):
cmd = cmd + ['--annots', os.path.abspath(round1GFF)]
else:
cmd = cmd + ['--annots_gff3', os.path.abspath(round1GFF)]
lib.runSubprocess6(cmd, folder, lib.log, pasaLOG2)
round2GFF = None
for file in os.listdir(folder):
if not file.endswith('.gff3'):
continue
if file == os.path.basename(round1GFF):
continue
if 'gene_structures_post_PASA_updates' in file:
round2GFF = os.path.join(folder, file)
if not round2GFF:
lib.log.error("PASA failed, check log, exiting")
sys.exit(1)
lib.log.debug("copying final PASA GFF3 to output: %s" % round2GFF)
# grab final result
shutil.copyfile(round2GFF, output)
def pasa_transcript2gene(input):
# modify kallisto ouput to map gene names to each mRNA ID so you know what locus they have come from
mRNADict = {}
# since mRNA is unique, parse the transcript file which has mRNAID geneID in header
with open(input, 'r') as transin:
for line in transin:
if line.startswith('>'):
line = line.rstrip()
line = line.replace('>', '')
cols = line.split(' ')
mRNAID = cols[0]
geneID = cols[1]
location = cols[-1]
if not mRNAID in mRNADict:
mRNADict[mRNAID] = (geneID, location)
return mRNADict
def long2fasta(readTuple, cpus, tmpdir, combined, combinedClean):
'''
Run SeqClean on long reads, return cleaned tuple and combined output
tuple is (pb_iso, nano_cdna, nano_mrna)
'''
def _convert2fasta(file, output):
messy = []
with open(output, 'w') as outfile:
if file.endswith('.gz'):
newfile = file.replace('.gz', '')
messy.append(newfile)
lib.Funzip(file, newfile, cpus)
file = newfile
if file.endswith('.fa') or file.endswith('.fasta'):
with open(file, 'r') as infile:
for title, seq in SimpleFastaParser(infile):
if '/' in title:
title = title.replace('/', '_')
outfile.write('>{:}\n{:}\n'.format(title, lib.softwrap(seq)))
elif file.endswith('.fq') or file.endswith('.fastq'):
with open(file, 'r') as infile:
for title, seq, qual in FastqGeneralIterator(infile):
if '/' in title:
title = title.replace('/', '_')
outfile.write('>{:}\n{:}\n'.format(title, lib.softwrap(seq)))
# clean up
for x in messy:
lib.SafeRemove(x)
if os.path.islink(combined) or os.path.isfile(combined):
results = []
originals = []
for i in [PBiso+'.clean', nanocdna+'.clean', nanomrna+'.clean']:
if lib.checkannotations(i):
results.append(i)
originals.append(i.replace('.clean', ''))
else:
results.append(None)
originals.append(None)
return tuple(originals), tuple(results)
else:
lib.log.info(
'Processing long reads: converting to fasta and running SeqClean')
results = []
if readTuple[0] and not lib.checkannotations(PBiso+'.clean'):
_convert2fasta(readTuple[0], PBiso)
runSeqClean(PBiso, tmpdir, cpus=cpus)
if readTuple[1] and not lib.checkannotations(nanocdna+'.clean'):
_convert2fasta(readTuple[1], nanocdna)
runSeqClean(nanocdna, tmpdir, cpus=cpus)
if readTuple[2] and not lib.checkannotations(nanomrna+'.clean'):
_convert2fasta(readTuple[2], nanomrna)
runSeqClean(nanomrna, tmpdir, cpus=cpus)
for i in [PBiso+'.clean', nanocdna+'.clean', nanomrna+'.clean']:
if lib.checkannotations(i):
results.append(i)
else:
results.append(None)
validResults = [x for x in results if x is not None]
validOriginal = [x.replace('.clean', '') for x in validResults]
validCln = [x.replace('.clean', '.cln') for x in validResults]
ClnOut = combined+'.cln'
if len(validResults) > 1:
lib.catFiles(*validResults, output=combinedClean)
lib.catFiles(*validOriginal, output=combined)
lib.catFiles(*validCln, output=ClnOut)
else:
if not lib.checkannotations(combinedClean):
os.symlink(os.path.abspath(validResults[0]), combinedClean)
if not lib.checkannotations(combined):
os.symlink(os.path.abspath(validOriginal[0]), combined)
if not lib.checkannotations(ClnOut):
os.symlink(os.path.abspath(validCln[0]), ClnOut)
return tuple(validOriginal), tuple(results)
def runSeqClean(input, folder, cpus=1):
'''
wrapper to run PASA seqclean on Trinity transcripts
'''
if cpus > 16:
cpus = 16
if os.path.isfile(input + ".clean"):
lib.log.info('Existing SeqClean output found: {:}'.format(
os.path.join(folder, input + ".clean")))
else:
cmd = [os.path.join(PASA, 'bin', 'seqclean'),
os.path.basename(input), '-c', str(cpus)]
lib.runSubprocess(cmd, folder, lib.log)
for f in os.listdir(folder):
if os.path.isdir(os.path.join(folder, f)):
if f.startswith('cleaning'):
lib.SafeRemove(os.path.join(folder, f))
def bam2fasta(input, output, cpus=1):
tmpout = output+'.tmp'
cmd = ['samtools', 'fasta', '-@', str(cpus), '-F', '0x4', input]
lib.runSubprocess2(cmd, '.', lib.log, tmpout)
# make sure no empty sequences
with open(output, 'w') as outfile:
with open(tmpout, 'r') as infile:
for header, seq in SimpleFastaParser(infile):
if len(seq) > 0:
outfile.write('>{:}\n{:}\n'.format(header, lib.softwrap(seq)))
os.remove(tmpout)
def bam2fasta_unmapped(input, output, cpus=1):
tmpout = output+'.tmp'
cmd = ['samtools', 'fasta', '-@', str(cpus), '-f', '0x4', input]
lib.runSubprocess2(cmd, '.', lib.log, tmpout)
# make sure no empty sequences
with open(output, 'w') as outfile:
with open(tmpout, 'r') as infile:
for header, seq in SimpleFastaParser(infile):
if len(seq) > 0:
outfile.write('>{:}\n{:}\n'.format(header, lib.softwrap(seq)))
os.remove(tmpout)
def mapTranscripts(genome, longTuple, assembled, tmpdir, trinityBAM, allBAM, cpus=1, max_intronlen=3000):
'''
function will map long reads and trinity to genome, return sorted BAM
'''
isoBAM = os.path.join(tmpdir, 'isoseq.coordSorted.bam')
isoSeqs = os.path.join(tmpdir, 'isoseq.coordSorted.fasta')
nano_cdnaBAM = os.path.join(tmpdir, 'nano_cDNA.coordSorted.bam')
nano_cdnaSeqs = os.path.join(tmpdir, 'nano_cDNA.coordSorted.fasta')
nano_mrnaBAM = os.path.join(tmpdir, 'nano_mRNA.coordSorted.bam')
nano_mrnaSeqs = os.path.join(tmpdir, 'nano_mRNA.coordSorted.fasta')
mappedSeqs = []
mappedLong = os.path.join(tmpdir, 'long-reads.mapped.fasta')
# tuple is (iso-seq, nanopore_cDNA, nanopore_mRNA)
if not all(v is None for v in longTuple):
# run minimap2 alignment
lib.log.info('Aligning long reads to genome with minimap2')
if longTuple[0]: # run iso-seq method
lib.iso_seq_minimap2(
longTuple[0], genome, cpus, max_intronlen, isoBAM)
bam2fasta(isoBAM, isoSeqs, cpus=cpus)
if longTuple[1]: # run nano cDNA
lib.nanopore_cDNA_minimap2(
longTuple[1], genome, cpus, max_intronlen, nano_cdnaBAM)
bam2fasta(nano_cdnaBAM, nano_cdnaSeqs, cpus=cpus)
if longTuple[2]: # run nano mRNA
lib.nanopore_mRNA_minimap2(
longTuple[2], genome, cpus, max_intronlen, nano_mrnaBAM)
bam2fasta(nano_mrnaBAM, nano_mrnaSeqs, cpus=cpus)
for x in [isoSeqs, nano_cdnaSeqs, nano_mrnaSeqs]:
if lib.checkannotations(x):
mappedSeqs.append(x)
if len(mappedSeqs) > 0:
lib.catFiles(*mappedSeqs, output=mappedLong)
lib.SafeRemove(isoSeqs)
lib.SafeRemove(nano_cdnaSeqs)
lib.SafeRemove(nano_mrnaSeqs)
if lib.checkannotations(assembled): # Trinity transcripts
# want to recover any long-reads that don't map to Trinity transcripts but do map to genome
crosscheckBAM = os.path.join(tmpdir, 'trinity.vs.long-reads.bam')
unmappedLong = os.path.join(tmpdir, 'long-reads.trinity.unique.fasta')
if lib.checkannotations(mappedLong):
lib.log.info(
'Finding long-reads not represented in Trinity assemblies')
minimap2_cmd = ['minimap2', '-ax', 'map-ont', '-t',
str(cpus), '--secondary=no', assembled, mappedLong]
samtools_cmd = ['samtools', 'sort', '--reference', assembled,
'-@', '2', '-o', crosscheckBAM, '-']
if not lib.checkannotations(crosscheckBAM):
lib.log.debug('{} | {}'.format(' '.join(minimap2_cmd), ' '. join(samtools_cmd)))
p1 = subprocess.Popen(minimap2_cmd, stdout=subprocess.PIPE, stderr=FNULL)
p2 = subprocess.Popen(samtools_cmd, stdout=subprocess.PIPE, stderr=FNULL, stdin=p1.stdout)
p1.stdout.close()
p2.communicate()
bam2fasta_unmapped(crosscheckBAM, unmappedLong, cpus=cpus)
lib.log.info(
'Adding {:,} unique long-reads to Trinity assemblies'.format(lib.countfasta(unmappedLong)))
lib.SafeRemove(crosscheckBAM)
if lib.checkannotations(unmappedLong):
trinityCombined = os.path.join(tmpdir, 'trinity.long-reads.fasta')
trinityCombinedClean = trinityCombined+'.clean'
lib.catFiles(*[assembled, unmappedLong], output=trinityCombined)
runSeqClean(trinityCombined, tmpdir, cpus=cpus)
else:
trinityCombinedClean = assembled
trinityCombined = assembled.replace('.clean', '')
# finally run trinity mapping
lib.minimap2Align(trinityCombinedClean, genome,
cpus, max_intronlen, trinityBAM)
else:
trinityCombined = mappedLong
trinityCombinedClean = trinityCombined+'.clean'
runSeqClean(trinityCombined, tmpdir, cpus=cpus)
bamResults = [isoBAM, nano_cdnaBAM, nano_mrnaBAM, trinityBAM]
foundResults = []
for r in bamResults:
if lib.checkannotations(r):
foundResults.append(r)
if len(foundResults) > 1:
lib.log.info('Merging BAM files: {:}'.format(', '.join(foundResults)))
lib.mergeBAMs(*foundResults, cpus=cpus, output=allBAM)
elif len(foundResults) == 0:
lib.log.error(
'Alignment failed, BAM files empty. Please check logfile')
sys.exit(1)
else:
os.symlink(os.path.abspath(foundResults[0]), os.path.abspath(allBAM))
return trinityCombined, trinityCombinedClean
def runKallisto(input, fasta, readTuple, stranded, cpus, output):
'''
function takes GFF3 output from PASA compare, extracts transcripts, and then calculates TPM
using Kallisto to idenitfy the best scoring gene model for each locus, the left and right
these should be the adapter cleaned non-normalized Illumina reads
'''
lib.log.info(
"Using Kallisto TPM data to determine which PASA gene models to select at each locus")
# convert GFF to transcripts
folder = os.path.join(tmpdir, 'getBestModel')
os.makedirs(folder)
PASAtranscripts = os.path.join(folder, 'transcripts.fa')
cmd = [os.path.join(PASA, 'misc_utilities',
'gff3_file_to_proteins.pl'), input, fasta, 'cDNA']
lib.log.info("Building Kallisto index")
lib.runSubprocess2(cmd, '.', lib.log, PASAtranscripts)
# generate kallisto index
cmd = ['kallisto', 'index', '-i',
os.path.join(folder, 'bestModel'), PASAtranscripts]
lib.runSubprocess(cmd, '.', lib.log)
# use kallisto to map reads to index
# base command
cmd = ['kallisto', 'quant', '-i', os.path.join(folder, 'bestModel'), '-o', os.path.join(
folder, 'kallisto'), '--plaintext', '-t', str(cpus)]
# parse the strand information
if stranded == 'RF':
strandcmd = ['--rf-stranded']
elif stranded == 'FR':
strandcmd = ['--fr-stranded']
else:
strandcmd = []
# adapt command for input, i.e. single or PE ends -> what do you do if you have both?
# single, not just using estimated lengths and SD, I think this is okay? can make this an option otherwise
if readTuple[2] and not readTuple[0] and not readTuple[1]:
cmd = cmd + ['--single', '-l', '200', '-s', '20', readTuple[2]]
elif readTuple[0] and readTuple[1]:
cmd = cmd + strandcmd + [readTuple[0], readTuple[1]]
lib.log.info("Mapping reads using pseudoalignment in Kallisto")
lib.runSubprocess(cmd, '.', lib.log)
# modify kallisto ouput to map gene names to each mRNA ID so you know what locus they have come from
mRNADict = pasa_transcript2gene(PASAtranscripts)
# some PASA models can have incomplete CDS and are wrong, get list of incompletes to ignore list
ignore = []
with open(input, 'r') as infile:
for line in infile:
if line.startswith('#PROT'):
if line.endswith('\t\n'):
ID = line.split(' ')[1]
ignore.append(ID)
if len(ignore) > 0:
lib.log.debug("Ignoring %i incomplete PASA models: %s" %
(len(ignore), ','.join(ignore)))
# now make new tsv file with #mRNAID geneID location TPM
with open(output, 'w') as outfile:
outfile.write("#mRNA-ID\tgene-ID\tLocation\tTPM\n")
with open(os.path.join(folder, 'kallisto', 'abundance.tsv'), 'r') as infile:
for line in infile:
if line.startswith('targed_id'):
continue
line = line.rstrip()
cols = line.split('\t')
if cols[0] in ignore:
continue
if cols[0] in mRNADict:
geneHit = mRNADict.get(cols[0])
geneID = geneHit[0]
location = geneHit[1]
outfile.write('%s\t%s\t%s\t%s\n' %
(cols[0], geneID, location, cols[4]))
def getBestModels(input, fasta, abundances, alt_transcripts, outfile):
# function to parse PASA results and generate GFF3; supports multiple transcripts
if float(alt_transcripts) == 0:
lib.log.info(
"Parsing Kallisto results. Keeping all alt-splicing transcripts at each locus.")
elif float(alt_transcripts) < 1:
lib.log.info(
"Parsing Kallisto results. Keeping alt-splicing transcripts if expressed at least {0:.1f}% of highest transcript per locus.".format(float(alt_transcripts)*100))
else:
lib.log.info(
"Parsing Kallisto results. Keeping best transcript at each locus.")
bestModels = {}
locations = {}
with open(abundances, 'r') as tpms:
for line in tpms:
line = line.rstrip()
if line.startswith('#') or line.startswith('target_id'):
continue
transcriptID, geneID, Loc, TPM = line.split('\t')
if not Loc in locations:
locations[Loc] = geneID
geneLocus = geneID
else:
geneLocus = locations.get(geneID)
if not geneLocus in bestModels:
bestModels[geneLocus] = [(transcriptID, float(TPM))]
else:
bestModels[geneLocus].append((transcriptID, float(TPM)))
# now we have geneID dictionary containing list of tuples of of transcripts
# loop through each locus grabbing transcript IDs of those models to keep
# use best expression value * alt_transcript threshold to filter models
# alt_transcript == 1 would be then only keeping best hit
extractList = []
ExpValues = {}
for k, v in natsorted(list(bestModels.items())):
if len(v) < 2:
extractList.append(v[0][0])
if not v[0][0] in ExpValues:
ExpValues[v[0][0]] = v[0][1]
else:
sortedTranscripts = sorted(v, key=lambda tup: tup[1], reverse=True)
ExpThreshold = sortedTranscripts[0][1] * float(alt_transcripts)
for hit in sortedTranscripts:
if hit[1] >= ExpThreshold:
extractList.append(hit[0])
if not hit[0] in ExpValues:
ExpValues[hit[0]] = hit[1]
# now go through the PASA GFF file and generate filtered GFF3 file composed of extractList
extractList = set(extractList)
with open(outfile, 'w') as output:
output.write("##gff-version 3\n")
with open(input, 'r') as gff:
for line in gff:
if line.startswith("#") or line.startswith('\n'):
continue
line = line.rstrip()
cols = line.split('\t')
gffID = cols[8].split(';Parent')[0].replace('ID=', '')
if 'gene' in cols[2]:
continue
elif 'mRNA' in cols[2]:
if gffID in extractList:
geneID = cols[8].split(';Name=')[0]
geneID = 'ID=' + geneID.split(';Parent=')[-1]
mRNAID = cols[8].split(';Name=')[0]
expression = ExpValues.get(gffID)
output.write('{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:};\n'.format(
cols[0], 'PASA', 'gene', cols[3], cols[4], cols[5], cols[6], cols[7], geneID))
output.write('{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:};Note=TPM:{:0.2f};\n'.format(
cols[0], 'PASA', cols[2], cols[3], cols[4], cols[5], cols[6], cols[7], mRNAID, expression))
elif '_prime_UTR' in cols[2]:
utrID = gffID.split('.utr')[0]
if utrID in extractList:
output.write('{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:};\n'.format(
cols[0], 'PASA', cols[2], cols[3], cols[4], cols[5], cols[6], cols[7], cols[8]))
elif 'exon' in cols[2]:
exonID = gffID.split('.exon')[0]
if exonID in extractList:
output.write('{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:};\n'.format(
cols[0], 'PASA', cols[2], cols[3], cols[4], cols[5], cols[6], cols[7], cols[8]))
elif 'CDS' in cols[2]:
cdsID = gffID.split('cds.')[-1]
if cdsID in extractList:
output.write('{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:};\n'.format(
cols[0], 'PASA', cols[2], cols[3], cols[4], cols[5], cols[6], cols[7], cols[8]))
lib.log.info('Wrote {:,} transcripts derived from {:,} protein coding loci.'.format(
len(extractList), len(bestModels)))
def GFF2tblCombinedNEW(evm, genome, trnascan, prefix, genenumber, justify, SeqCenter, SeqRefNum, tblout, alt_transcripts='1'):
from collections import OrderedDict
'''
function to take GFF3 annotation to produce a GBK tbl file, support multiple transcripts per locus.
'''
def _sortDict(d):
return (d[1]['contig'], d[1]['location'][0])
# make sure genenumber is integer
genenumber = int(genenumber)
# generate genome length dictionary used for feature tbl generation
scaffLen = {}
with open(genome, 'r') as fastain:
for record in SeqIO.parse(fastain, 'fasta'):
if not record.id in scaffLen:
scaffLen[record.id] = len(record.seq)
# setup interlap database for genes on each chromosome and load EVM models into dictionary
gene_inter = defaultdict(InterLap)
Genes = {}
gene_inter, Genes = lib.gff2interlapDict(
evm, genome, gene_inter, Genes)
# now load tRNA predictions
gene_inter, Genes = lib.gff2interlapDict(
trnascan, genome, gene_inter, Genes)
# now sort dictionary by contig and location, rename using prefix
sGenes = sorted(iter(Genes.items()), key=_sortDict)
sortedGenes = OrderedDict(sGenes)
renamedGenes = {}
scaff2genes = {}
SeqRecords = SeqIO.to_dict(SeqIO.parse(genome, 'fasta'))
skipList = []
dropped = 0
keeper = 0
tooShort = 0
internalStop = 0
lib.log.info(
"Validating gene models (renaming, checking translations, filtering, etc)")
for k, v in list(sortedGenes.items()):
GoodModel = True
# check if gene model completely contained inside another one on same strand
if alt_transcripts == '1':
loc = sorted([v['location'][0], v['location'][1]])
if loc in gene_inter[v['contig']]:
for hit in list(gene_inter[v['contig']].find(loc)):
if hit[3] != k and hit[2] == v['strand']: # same strand but diff gene
sortedhit = sorted([hit[0], hit[1]])
# then this gene is fully contained, skip it
if loc[0] >= sortedhit[0] and loc[1] <= sortedhit[1]:
# if two gene models have exact same start stop they will both be removed, not really what I want, so run check
# exact same, then choose which has higher TPM
if loc[0] == sortedhit[0] and loc[1] == sortedhit[1]:
if k in ExpressionValues and hit[3] in ExpressionValues:
currExp = ExpressionValues.get(k)
oldExp = ExpressionValues.get(hit[3])
if currExp < oldExp:
GoodModel = False
else:
skipList.append(hit[3])
else:
GoodModel = False
if not GoodModel:
dropped += 1
continue
# rename gene locus here
keeper += 1
# renaming scheme, leave if startswith locustag
if k.startswith('novel_gene') or k.startswith('temp_gene') or k.startswith('split_gene'):
genenumber += 1
locusTag = prefix+str(genenumber).zfill(justify)
elif k.startswith(prefix) and '_'+prefix in k: # means models were merged
locusTag = k.split('_'+prefix)[0]
else:
locusTag = k
# translate to protein space, drop if less than minimum
# translate to protein sequence, construct cDNA Seq object, translate
# if passes then add to final output dictionary
for i in range(0, len(v['ids'])):
protSeq = None
if v['type'] == 'mRNA': # get transcript for valid models
cdsSeq = lib.getSeqRegions(
SeqRecords, v['contig'], v['CDS'][i])
protSeq = lib.translate(
cdsSeq, v['strand'], v['codon_start'][i]-1)
v['protein'].append(protSeq)
if protSeq and len(protSeq) - 1 < 50:
tooShort += 1
continue
if protSeq and '*' in protSeq[:-1]:
internalStop += 1
continue
if protSeq:
if protSeq.endswith('*'):
v['partialStop'][i] = False
else: # try to extend the CDS up to 20 codons to see if you can find valid stop codon
v['partialStop'][i] = True
if v['codon_start'][i] == 1 and v['protein'][i].startswith('M'):
v['partialStart'][i] = False
else:
v['partialStart'][i] = True
if not locusTag in renamedGenes:
renamedGenes[locusTag] = v
if not v['contig'] in scaff2genes:
scaff2genes[v['contig']] = [locusTag]
else:
scaff2genes[v['contig']].append(locusTag)
lib.log.info('Writing {:,} loci to TBL format: dropped {:,} overlapping, {:,} too short, and {:,} frameshift gene models'.format(
len(renamedGenes), dropped, tooShort, internalStop))
lib.dicts2tbl(renamedGenes, scaff2genes, scaffLen,
SeqCenter, SeqRefNum, skipList, tblout)
def gbk2interlap(input):
'''
function to parse GBK file, construct scaffold/gene interlap dictionary and funannotate standard annotation dictionary
'''
inter = defaultdict(InterLap)
Genes = {}
with open(input, 'r') as filein:
for record in SeqIO.parse(filein, 'genbank'):
for f in record.features:
if f.type == 'gene':
locusTag, ID, Parent = lib.getID(f, f.type)
start = int(f.location.nofuzzy_start)
end = int(f.location.nofuzzy_end)
inter[record.id].add((start, end, locusTag))
lib.gb_feature_add2dict(f, record, Genes)
return inter, Genes
def gff2interlap(input, fasta):
'''
function to parse GFF3 file, construct scaffold/gene interlap dictionary and funannotate standard annotation dictionary
'''
inter = defaultdict(InterLap)
Genes = {}
Genes = lib.gff2dict(input, fasta, Genes)
for k, v in natsorted(list(Genes.items())):
inter[v['contig']].add((v['location'][0], v['location'][1], k))
return inter, Genes
def merge_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
def message(loc1, loc2, cdsAED, mrnaAED, protMatches, UTRs, no_change, UTR_added, yardSale, exonChange):
msg = []
if not cdsAED or cdsAED == '':
cds = 0
else:
cds = float(cdsAED)
mrna = float(mrnaAED)
pos = loc1 == loc2
# structured message, coordinates, 5prime, 3prime, exon, cds, pident
if not pos: # coordinates changed
msg.append('gene coordinates updated')
for u in UTRs:
if u[0]:
if not any('5prime' in x for x in msg):
msg.append('5prime UTR added')
if u[1]:
if not any('3prime' in x for x in msg):
msg.append('3prime UTR added')
if mrna > 0:
msg.append('mRNA updated')
if cds > 0:
pidentmsg = []
for x in protMatches:
pidentmsg.append('{0:.0f}%'.format(x))
msg.append('CDS update [translation pident: %s]' %
', '.join(pidentmsg))
# now work on the counter
if len(msg) < 1:
msg = ['no change']
no_change += 1
elif any('UTR' in x for x in msg):
UTR_added += 1
elif any('mRNA' in x for x in msg):
exonChange += 1
else:
yardSale += 1
final_message = ';'.join(msg)
return final_message, no_change, UTR_added, yardSale, exonChange
def pairwiseAlign(query, ref):
from Bio import pairwise2
'''
do global alignment and return pident
'''
if query == ref:
return 100.0
align = pairwise2.align.globalxx(query, ref)
length = max(len(query), len(ref))
pident = (align[0][2] / float(length)) * 100
return pident
def compareAnnotations2(old, new, output, args={}):
'''
function takes two GenBank annotated genomes and compares gene models
output is a tsv file for each locus and a description of what is different
can handle multiple transcripts per locus
'''
result = {}
global no_change, UTR_added, yardSale, exonChange, modelChangeNotProt, dropped, added, total_transcripts, total_genes
no_change, UTR_added, yardSale, exonChange, modelChangeNotProt, dropped, added, total_transcripts, total_genes = (
0,)*9
lib.log.info("Parsing GenBank files...comparing annotation")
if args.gff and args.fasta:
oldInter, oldGenes = gff2interlap(old, args.fasta)
else:
oldInter, oldGenes = gbk2interlap(old)
newInter, newGenes = gbk2interlap(new)
# do the simple stuff first, find models that were deleted
for contig in oldInter:
for gene in oldInter[contig]:
if not gene in newInter[contig]: # these models are removed
dropped += 1
if not gene[2] in oldGenes:
continue
# populate output dictionary with results
if not gene[2] in result:
# dropped model has AED of 1.000
cdsAED = '1.000'
exonAED = '1.000'
result[gene[2]] = {'contig': oldGenes[gene[2]]['contig'], 'old_num_transcripts': len(oldGenes[gene[2]]['ids']),
'old_location': oldGenes[gene[2]]['location'], 'num_transcripts': len(oldGenes[gene[2]]['ids']), 'strand': oldGenes[gene[2]]['strand'],
'mRNA': oldGenes[gene[2]]['mRNA'], 'location': oldGenes[gene[2]]['location'], 'CDS': oldGenes[gene[2]]['CDS'], 'message': 'gene model removed',
'cdsAED': cdsAED, 'exonAED': exonAED, 'transcript_id': oldGenes[gene[2]]['ids'], 'pident': [],
'protein_id': oldGenes[gene[2]]['ids'], 'seq': oldGenes[gene[2]]['protein']}
# now go through the updated annotation, comparing to old annot
for contig in newInter:
for gene in newInter[contig]:
# means this is a new model, so add it
if not gene in oldInter[contig]:
added += 1
total_genes += 1
if not gene[2] in newGenes:
continue
total_transcripts += len(newGenes[gene[2]]['ids'])
if not gene[2] in result:
result[gene[2]] = {'contig': newGenes[gene[2]]['contig'], 'old_num_transcripts': 0,
'old_location': newGenes[gene[2]]['location'], 'num_transcripts': len(newGenes[gene[2]]['ids']), 'strand': newGenes[gene[2]]['strand'],
'mRNA': newGenes[gene[2]]['mRNA'], 'location': newGenes[gene[2]]['location'], 'CDS': newGenes[gene[2]]['CDS'], 'message': 'new gene model',
'cdsAED': '0.000', 'exonAED': '0.000', 'transcript_id': newGenes[gene[2]]['ids'],
'protein_id': newGenes[gene[2]]['ids'], 'seq': newGenes[gene[2]]['protein'], 'pident': []}
else: # means this is existing model, and need to do some comparisons
hitList = list(oldInter[contig].find(gene))
# there might be some overlapping transcripts, so enforce locus name
hit = None
for z in hitList:
if gene[2] == z[2]:
hit = z
if not hit:
# there is no real hit, so this a new gene
total_transcripts += len(newGenes[gene[2]]['ids'])
added += 1
total_genes += 1
if not gene[2] in result:
result[gene[2]] = {'contig': newGenes[gene[2]]['contig'], 'old_num_transcripts': 0,
'old_location': newGenes[gene[2]]['location'], 'num_transcripts': len(newGenes[gene[2]]['ids']), 'strand': newGenes[gene[2]]['strand'],
'mRNA': newGenes[gene[2]]['mRNA'], 'location': newGenes[gene[2]]['location'], 'CDS': newGenes[gene[2]]['CDS'], 'message': 'new gene model',
'cdsAED': '0.000', 'exonAED': '0.000', 'transcript_id': newGenes[gene[2]]['ids'],
'protein_id': newGenes[gene[2]]['ids'], 'seq': newGenes[gene[2]]['protein'], 'pident': []}
else:
# since we may have multiple transcripts from hit as well as new annotation we need to be aware of that
# also, tRNA annotations do not exist in Proteins dictionary, so process them differently
# get the reference hits, pull out CDS and mRNA for pairwiseAED calculation
total_genes += 1
total_transcripts += len(newGenes[gene[2]]['ids'])
# get the old annotation
hitInfo = oldGenes.get(gene[2])
# calculate AED
exonAED = pairwiseAED(
newGenes[gene[2]]['mRNA'], hitInfo['mRNA'])
if newGenes[gene[2]]['type'] == 'mRNA' and hitInfo['type'] == 'mRNA':
cdsAED = pairwiseAED(
newGenes[gene[2]]['CDS'], hitInfo['CDS'])
else:
cdsAED = '0.000'
# check translation, to deal with multiple transcripts, lets loop through new
protMatches = []
if newGenes[gene[2]]['type'] == 'mRNA' and hitInfo['type'] == 'mRNA':
for i in range(0, len(newGenes[gene[2]]['ids'])):
protMatch = None
for y in range(0, len(oldGenes[gene[2]]['ids'])):
pident = pairwiseAlign(
newGenes[gene[2]]['protein'][i], oldGenes[gene[2]]['protein'][y])
if not protMatch:
protMatch = pident
else:
if pident > protMatch:
protMatch = pident
protMatches.append(protMatch)
# summarize UTRs
UTRs = findUTRs(
newGenes[gene[2]]['CDS'], newGenes[gene[2]]['mRNA'], newGenes[gene[2]]['strand'])
# structured comments/counts for gene models
msg, no_change, UTR_added, yardSale, exonChange = message(
newGenes[gene[2]]['location'], oldGenes[gene[2]]['location'], cdsAED, exonAED, protMatches, UTRs, no_change, UTR_added, yardSale, exonChange)
if not gene[2] in result:
result[gene[2]] = {'contig': newGenes[gene[2]]['contig'], 'old_num_transcripts': len(oldGenes[gene[2]]['ids']),
'old_location': oldGenes[gene[2]]['location'], 'num_transcripts': len(newGenes[gene[2]]['ids']), 'strand': newGenes[gene[2]]['strand'],
'mRNA': newGenes[gene[2]]['mRNA'], 'location': newGenes[gene[2]]['location'], 'CDS': newGenes[gene[2]]['CDS'], 'message': msg,
'cdsAED': cdsAED, 'exonAED': exonAED, 'transcript_id': newGenes[gene[2]]['ids'],
'protein_id': newGenes[gene[2]]['ids'], 'seq': newGenes[gene[2]]['protein'], 'pident': protMatches}
total_cdsAED = []
total_exonAED = []
with open(output, 'w') as out:
out.write('Locus_tag\tOrig_Location\tOrig_Num_Transcripts\tContig:start-end\tStrand\tGene_Length\tNum_Transcripts\tmRNA_AED\tCDS_AED\tDescription\n')
for k, v in natsorted(list(result.items())):
start = str(v['location'][0])
end = str(v['location'][1])
GeneLength = int(end) - int(start)
total_cdsAED.append(float(v['cdsAED']))
total_exonAED.append(float(v['exonAED']))
out.write('{:}\t{:}:{:}-{:}\t{:}\t{:}:{:}-{:}\t{:}\t{:}\t{:}\t{:}\t{:}\t{:}\n'.format(k, v['contig'], v['old_location'][0], v['old_location'][
1], v['old_num_transcripts'], v['contig'], start, end, v['strand'], GeneLength, v['num_transcripts'], v['exonAED'], v['cdsAED'], v['message']))
Avg_cdsAED = sum(total_cdsAED) / float(len(total_cdsAED))
Avg_exonAED = sum(total_exonAED) / float(len(total_exonAED))
# output some simple stats to cmd line
lib.log.info("Updated annotation complete:\n\
-------------------------------------------------------\n\
Total Gene Models:\t{:,}\n\
Total transcripts:\t{:,}\n\
New Gene Models:\t{:,}\n\
No Change:\t\t{:,}\n\
Update UTRs:\t\t{:,}\n\
Exons Changed:\t\t{:,}\n\
Exons/CDS Changed:\t{:,}\n\
Dropped Models:\t\t{:,}\n\
CDS AED:\t\t{:.3f}\n\
mRNA AED:\t\t{:.3f}\n\
-------------------------------------------------------".format(total_genes, total_transcripts, added, no_change, UTR_added, exonChange, yardSale, dropped, Avg_cdsAED, Avg_exonAED))
def findUTRs(cds, mrna, strand):
'''
take list of list of CDS coordiantes and compare to list of list of mRNA coordinates to
determine if 5 prime or 3 prime UTR exist
'''
# supporting multiple transcripts, however, they are already matched up and sorted
UTRs = []
for i in range(0, len(cds)):
Fiveprime = False
Threeprime = False
refInterlap = InterLap(mrna[i])
if strand == '+': # look at first CDS for 5 prime and last CDS for 3 prime
# means it overlaps with mrNA (which it obviously should)
if cds[i][0] in refInterlap:
hit = list(refInterlap.find(cds[i][0]))[0]
# if first exon, then compare, if not first then there is 5prime UTR
loc = mrna[i].index(hit)
if loc == 0:
# will return array of exon minus hit at each pos
diff = np.subtract(cds[i][0], hit)
if diff[0] > 0:
Fiveprime = True
else:
Fiveprime = True
# check for 3 prime UTR
if cds[i][-1] in refInterlap:
hit = list(refInterlap.find(cds[i][-1]))[0]
loc = mrna[i].index(hit)
if len(mrna[i]) == loc+1:
# will return array of exon minus hit at each pos
diff = np.subtract(cds[i][-1], hit)
if diff[1] < 0:
Threeprime = True
else:
Threeprime = True
else:
# means it overlaps with mrNA (which it obviously should)
if cds[i][0] in refInterlap:
hit = list(refInterlap.find(cds[i][0]))[0]
# if first exon, then compare, if not first then there is 5prime UTR
loc = mrna[i].index(hit)
if loc == 0:
# will return array of exon minus hit at each pos
diff = np.subtract(cds[i][0], hit)
if diff[1] < 0:
Fiveprime = True
else:
Fiveprime = True
# check for 3 prime UTR
if cds[i][-1] in refInterlap:
hit = list(refInterlap.find(cds[i][-1]))[0]
loc = mrna[i].index(hit)
if len(mrna[i]) == loc+1:
# will return array of exon minus hit at each pos
diff = np.subtract(cds[i][-1], hit)
if diff[0] > 0:
Threeprime = True
else:
Threeprime = True
UTRs.append((Fiveprime, Threeprime))
return UTRs
def pairwiseAED(query, reference):
'''
takes a multiple transcripts and sums AED from lowest pairwise comparison and then calculates
the average based on number of transcripts in the query
'''
AEDsum = []
pAED = [float(getAED(a, b))
for a, b in itertools.product(query, reference)]
# split into parts to get lowest AED
splitAED = [pAED[i:i+len(query)] for i in range(0, len(pAED), len(query))]
for pair in splitAED:
AEDsum.append(min(pair))
AEDavg = sum(AEDsum) / len(query)
return '{:.3f}'.format(AEDavg)
def getAED(query, reference):
'''
function to calcuate annotation edit distance between two mRNA transcript coordinates
AED = 1 - (SN + SP / 2)
SN = fraction of ref predicted
SP = fraction prediction overlapping the ref
'''
def _length(listTup):
len = 0
for i in listTup:
l = abs(i[0] - i[1])
len += l
return len
# check if identical
if query == reference:
return '0.000'
# make sure sorted
rLen = _length(reference)
refInterlap = InterLap(reference)
QueryOverlap = 0
qLen = 0
for exon in query:
qLen += abs(exon[0] - exon[1])
if exon in refInterlap: # exon overlaps at least partially with reference
hit = list(refInterlap.find(exon))
for h in hit:
# will return array of exon minus hit at each pos
diff = np.subtract(exon, h)
if diff[0] <= 0 and diff[1] >= 0: # then query exon covers ref exon
cov = abs(h[0] - h[1])
QueryOverlap += cov
elif diff[0] <= 0 and diff[1] < 0: # means query partial covers ref
cov = abs(h[0] - exon[1])
QueryOverlap += cov
elif diff[0] > 0 and diff[1] >= 0: # means query partial covers ref
cov = abs(exon[0] - h[1])
QueryOverlap += cov
elif diff[0] > 0 and diff[1] < 1:
cov = abs(exon[0] - exon[1])
QueryOverlap += cov
# calculate AED
SP = QueryOverlap / float(qLen)
SN = QueryOverlap / float(rLen)
AED = 1 - ((SN + SP) / 2)
return '{:.3f}'.format(AED)
def main(args):
# setup menu with argparse
class MyFormatter(argparse.ArgumentDefaultsHelpFormatter):
def __init__(self, prog):
super(MyFormatter, self).__init__(prog, max_help_position=48)
parser = argparse.ArgumentParser(prog='funannotate-update.py', usage="%(prog)s [options] -i genome.gbk -l left.fq.gz -r right.fg.gz",
description='''Script is a wrapper for automated Trinity/PASA reannotation.''',
epilog="""Written by <NAME> (2017) <EMAIL>""",
formatter_class=MyFormatter)
parser.add_argument('-i', '--input',
help='Genome in GBK format or funannotate folder')
parser.add_argument('-g', '--gff', help='Genome annotation in GFF3 format')
parser.add_argument('-f', '--fasta',
help='Genome sequence in FASTA format')
parser.add_argument('-l', '--left', nargs='+',
help='Left (R1) FASTQ Reads')
parser.add_argument('--left_norm', help='Left (R1) FASTQ Reads')
parser.add_argument('--right_norm', help='Right (R2) normalized FASTQ Reads')
parser.add_argument('--single_norm', help='single normalized FASTQ Reads')
parser.add_argument('-r', '--right', nargs='+',
help='Right (R2) FASTQ Reads')
parser.add_argument('-s', '--single', nargs='+',
help='Single ended FASTQ Reads')
parser.add_argument('--pacbio_isoseq', help='PacBio Iso-seq data')
parser.add_argument('--nanopore_cdna', help='Nanopore 2d cDNA data')
parser.add_argument('--nanopore_mrna', help='Nanopore direct mRNA data')
parser.add_argument('-o', '--out', help='Basename of output files')
parser.add_argument('--species',
help='Species name (e.g. "Aspergillus fumigatus") use quotes if there is a space')
parser.add_argument('-c', '--coverage', default=50,
type=int, help='Depth to normalize reads to')
parser.add_argument('-m', '--min_coverage', default=5, type=int,
help='Minimum depth to pass to Trinity during normalization')
parser.add_argument('--isolate', help='Isolate name (e.g. Af293)')
parser.add_argument('--strain', help='Strain name (e.g. CEA10)')
parser.add_argument('--trinity',
help='Trinity genome guided FASTA results')
parser.add_argument('--pasa_gff', help='PASA GFF')
parser.add_argument('--pasa_alignment_overlap', default='30.0',
help='PASA --stringent_alingment_overlap')
parser.add_argument('--pasa_min_pct_aligned', default='90',
help='PASA --MIN_PERCENT_ALIGNED')
parser.add_argument('--pasa_min_avg_per_id', default='95',
help='PASA --MIN_AVG_PER_ID')
parser.add_argument('--pasa_num_bp_splice', default='3',
help='PASA --NUM_BP_PERFECT_SPLICE_BOUNDARY')
parser.add_argument('--pasa_config',
help='PASA assembly configuration file')
parser.add_argument('--pasa_db', default='sqlite',
choices=['mysql', 'sqlite'], help='PASA SQL database to use')
parser.add_argument('--memory', default='50G',
help='RAM to use for Jellyfish/Trinity')
parser.add_argument('--no_normalize_reads',
action='store_true', help='skip normalization')
parser.add_argument('--no_trimmomatic', action='store_true',
help='skip quality trimming via trimmomatic')
parser.add_argument('--jaccard_clip', action='store_true',
help='Turn on jaccard_clip for dense genomes')
parser.add_argument('--kallisto', help='Kallisto abundances table')
parser.add_argument('--name',
help='Shortname for genes, perhaps assigned by NCBI, eg. VC83_')
parser.add_argument('--max_intronlen', default=3000,
help='Maximum intron length for gene models')
parser.add_argument('--min_protlen', default=50, type=int,
help='Minimum amino acid length for valid gene model')
parser.add_argument('--stranded', default='no',
choices=['RF', 'FR', 'F', 'R', 'no'], help='RNA seq strandedness')
parser.add_argument('--cpus', default=2, type=int,
help='Number of CPUs to use')
parser.add_argument('-t', '--tbl2asn', default='-l paired-ends',
help='Parameters for tbl2asn, linkage and gap info')
parser.add_argument('--sbt', default='SBT',
help='Basename of output files')
parser.add_argument('--p2g', help='NCBI p2g file from previous annotation')
parser.add_argument('--aligners', default=['minimap2', 'blat'], nargs='+', choices=[
'minimap2', 'gmap', 'blat'], help='transcript alignment programs')
parser.add_argument('--PASAHOME',
help='Path to PASA home directory, $PASAHOME')
parser.add_argument('--TRINITYHOME',
help='Path to Trinity config directory, $TRINITYHOME')
parser.add_argument('--SeqCenter', default='CFMR',
help='Sequencing center for GenBank tbl file')
parser.add_argument('--SeqAccession', default='12345',
help='Sequencing accession number')
parser.add_argument('--alt_transcripts', default='0.10',
help='Threshold to keep alt-transcripts, percent highest expression')
args = parser.parse_args(args)
global FNULL
FNULL = open(os.devnull, 'w')
# create folder structure
if args.input:
if os.path.isdir(args.input): # then funannoate folder is passed
args.out = args.input
if not args.out:
lib.log.error("No output folder specified, -o, --out.")
sys.exit(1)
if not os.path.isdir(args.out):
os.makedirs(args.out)
os.makedirs(os.path.join(args.out, 'update_misc'))
os.makedirs(os.path.join(args.out, 'update_results'))
os.makedirs(os.path.join(args.out, 'logfiles'))
else:
# make sure subdirectories exist
dirs = [os.path.join(args.out, 'update_misc'), os.path.join(
args.out, 'logfiles'), os.path.join(args.out, 'update_results')]
for d in dirs:
if not os.path.isdir(d):
os.makedirs(d)
# assign temp directory
global tmpdir, PASA, LAUNCHPASA, PASAVERSION, TRINITY, PBiso, nanocdna, nanomrna, parentdir
parentdir = os.path.join(os.path.dirname(__file__))
tmpdir = os.path.join(args.out, 'update_misc')
# create log file
log_name = os.path.join(args.out, 'logfiles', 'funannotate-update.log')
if os.path.isfile(log_name):
os.remove(log_name)
# initialize script, log system info and cmd issue at runtime
lib.setupLogging(log_name)
cmd_args = " ".join(sys.argv)+'\n'
lib.log.debug(cmd_args)
print("-------------------------------------------------------")
lib.SystemInfo()
# get version of funannotate
version = lib.get_version()
lib.log.info("Running %s" % version)
# do some checks and balances
if not args.PASAHOME:
try:
PASA = os.environ["PASAHOME"].strip()
except KeyError:
lib.log.error(
"$PASAHOME environmental variable not found, PASA is not properly configured. You can use the --PASAHOME argument to specifiy a path at runtime")
sys.exit(1)
else:
PASA = args.PASAHOME.strip()
# try to autodetect different PASA distributions
if os.path.isfile(os.path.join(PASA, 'Launch_PASA_pipeline.pl')): # then v2.3.0 or newer
LAUNCHPASA = os.path.join(PASA, 'Launch_PASA_pipeline.pl')
PASAVERSION = '2.3.0'
elif os.path.isfile(os.path.join(PASA, 'scripts', 'Launch_PASA_pipeline.pl')): # older version
LAUNCHPASA = os.path.join(PASA, 'scripts', 'Launch_PASA_pipeline.pl')
args.pasa_db = 'mysql' # sqlite not available
PASAVERSION = '2.2.0'
if not args.TRINITYHOME:
try:
TRINITY = os.environ["TRINITYHOME"].strip()
except KeyError:
try:
TRINITY = os.environ["TRINITY_HOME"].strip()
except KeyError:
lib.log.error(
"$TRINITYHOME nor $TRINITY_HOME environmental variable not found, TRINITY is not properly configured. You can use the --TRINITYHOME argument to specify a path at runtime.")
sys.exit(1)
else:
TRINITY = args.TRINITYHOME.strip()
programs = ['fasta', 'minimap2', 'tbl2asn', 'hisat2', 'hisat2-build', 'kallisto',
'Trinity', 'bedtools', 'java', LAUNCHPASA, os.path.join(PASA, 'bin', 'seqclean')]
if not args.no_trimmomatic:
programs.append('trimmomatic')
programs += args.aligners
lib.CheckDependencies(programs)
# take care of some preliminary checks
if args.sbt == 'SBT':
SBT = os.path.join(parentdir, 'config', 'test.sbt')
lib.log.info(
"No NCBI SBT file given, will use default, for NCBI submissions pass one here '--sbt'")
else:
SBT = args.sbt
# setup output files
gffout = os.path.join(tmpdir, 'genome.gff3')
proteinsout = os.path.join(tmpdir, 'genome.proteins.fa')
trnaout = os.path.join(tmpdir, 'genome.trna.gff3')
fastaout = os.path.join(tmpdir, 'genome.fa')
spliceout = os.path.join(tmpdir, 'genome.ss')
exonout = os.path.join(tmpdir, 'genome.exons')
# check input, allow for passing the output directory of funannotate, otherwise must be gbk or gbff files
# set read inputs to None, populate as you go
existingStats = False
s_reads, l_reads, r_reads, trim_left, trim_right, trim_single, left_norm, right_norm, single_norm, all_reads, trim_reads, norm_reads, GBK, trinity_results, pasaConfigFile, PBiso, nanocdna, nanomrna, long_clean, pb_iso, nano_cdna, nano_mrna, stringtieGTF, longReadClean, shortBAM = (
None,)*25
if args.input:
if os.path.isdir(args.input):
if os.path.isdir(os.path.join(args.input, 'predict_results')):
for file in os.listdir(os.path.join(args.input, 'predict_results')):
if file.endswith('.gbk'):
GBK = os.path.join(args.input, 'predict_results', file)
if file.endswith('.stats.json'):
existingStats = os.path.join(args.input, 'predict_results', file)
# now lets also check if training folder/files are present, as then can pull all the data you need for update directly
# then funannotate train has been run, try to get reads, trinity, PASA
if os.path.isdir(os.path.join(args.input, 'training')):
inputDir = os.path.join(args.input, 'training')
if lib.checkannotations(os.path.join(inputDir, 'left.fq.gz')):
l_reads = os.path.join(inputDir, 'left.fq.gz')
if lib.checkannotations(os.path.join(inputDir, 'right.fq.gz')):
r_reads = os.path.join(inputDir, 'right.fq.gz')
if lib.checkannotations(os.path.join(inputDir, 'single.fq.gz')):
s_reads = os.path.join(inputDir, 'single.fq.gz')
if lib.checkannotations(os.path.join(inputDir, 'trimmomatic', 'trimmed_left.fastq.gz')):
trim_left = os.path.join(
inputDir, 'trimmomatic', 'trimmed_left.fastq.gz')
if lib.checkannotations(os.path.join(inputDir, 'trimmomatic', 'trimmed_right.fastq.gz')):
trim_right = os.path.join(
inputDir, 'trimmomatic', 'trimmed_right.fastq.gz')
if lib.checkannotations(os.path.join(inputDir, 'trimmomatic', 'trimmed_single.fastq.gz')):
trim_single = os.path.join(
inputDir, 'trimmomatic', 'trimmed_single.fastq.gz')
if lib.checkannotations(os.path.join(inputDir, 'normalize', 'left.norm.fq')):
left_norm = os.path.join(
inputDir, 'normalize', 'left.norm.fq')
if lib.checkannotations(os.path.join(inputDir, 'normalize', 'right.norm.fq')):
right_norm = os.path.join(
inputDir, 'normalize', 'right.norm.fq')
if lib.checkannotations(os.path.join(inputDir, 'normalize', 'single.norm.fq')):
single_norm = os.path.join(
inputDir, 'normalize', 'single.norm.fq')
if lib.checkannotations(os.path.join(inputDir, 'nano-mrna.fasta')):
nanomrna = os.path.join(inputDir, 'nano-mrna.fasta')
if lib.checkannotations(os.path.join(inputDir, 'nano-cdna.fasta')):
nanocdna = os.path.join(inputDir, 'nano-cdna.fasta')
if lib.checkannotations(os.path.join(inputDir, 'iso-seq.fasta')):
PBiso = os.path.join(inputDir, 'iso-seq.fasta')
long_clean = (PBiso, nanocdna, nanomrna)
if l_reads or s_reads:
all_reads = (l_reads, r_reads, s_reads)
if trim_left or trim_single:
trim_reads = (trim_left, trim_right, trim_single)
if left_norm or single_norm:
norm_reads = (left_norm, right_norm, single_norm)
if lib.checkannotations(os.path.join(inputDir, 'funannotate_train.stringtie.gtf')):
stringtieGTF = os.path.join(
inputDir, 'funannotate_train.stringtie.gtf')
if lib.checkannotations(os.path.join(inputDir, 'funannotate_long-reads.fasta')):
longReadClean = os.path.join(
inputDir, 'funannotate_long-reads.fasta')
if lib.checkannotations(os.path.join(inputDir, 'funannotate_train.trinity-GG.fasta')):
trinity_results = os.path.join(
inputDir, 'funannotate_train.trinity-GG.fasta')
if lib.checkannotations(os.path.join(inputDir, 'funannotate_train.coordSorted.bam')):
shortBAM = os.path.join(
inputDir, 'funannotate_train.coordSorted.bam')
if args.pasa_config:
pasaConfigFile = args.pasa_config
elif os.path.isfile(os.path.join(inputDir, 'pasa', 'alignAssembly.txt')):
pasaConfigFile = os.path.join(
inputDir, 'pasa', 'alignAssembly.txt')
# let user know which files are being re-used
look4files = [s_reads, l_reads, r_reads, trim_left, trim_right, trim_single, left_norm,
right_norm, single_norm, trinity_results, longReadClean, pasaConfigFile, shortBAM, stringtieGTF]
look4files_names = ['Single reads', 'Forward reads', 'Reverse reads', 'Forward Q-trimmed reads', 'Reverse Q-trimmed reads', 'Single Q-trimmed reads', 'Forward normalized reads',
'Reverse normalized reads', 'Single normalized reads', 'Trinity results', 'Long-read results', 'PASA config file', 'BAM alignments', 'StringTie GTF']
files_used = []
for i, x in enumerate(look4files):
if x is not None:
files_used.append('\t'+look4files_names[i]+': '+x)
if len(files_used) > 0:
lib.log.info('Found relevant files in %s, will re-use them:\n%s' %
(inputDir, '\n'.join(files_used)))
else:
GBK = args.input
# check if RefSeq --> NCBI does not want you to reannotate RefSeq genomes
if GBK is None:
print("No GBK file found")
sys.exit(1)
elif lib.checkRefSeq(GBK):
lib.log.error(
'%s is a NCBI RefSeq genome, to reannotate please use original submission.' % GBK)
sys.exit(1)
# split GenBank into parts
locustag, genenumber, justify = gbk2pasaNEW(
GBK, gffout, trnaout, fastaout, spliceout, exonout, proteinsout)
organism, strain, isolate, accession, WGS_accession, gb_gi, version = lib.getGBKinfo(
GBK)
lib.log.info("Reannotating %s, NCBI accession: %s" %
(organism, WGS_accession))
else:
if args.gff and args.fasta:
if not args.species:
lib.log.error(
"Input error: please enter a name for -s,--species")
sys.exit(1)
shutil.copyfile(args.fasta, fastaout)
locustag, genenumber, justify = gff2pasa(
args.gff, fastaout, gffout, trnaout, spliceout, exonout)
organism, strain, isolate, accession, WGS_accession, gb_gi, version = (
None,)*7
else:
lib.log.error(
"Error in input: pass either funannotate directory or GenBank file to -i,--input; or GFF3 to -g,--gff and genome FASTA to -f,--fasta.")
sys.exit(1)
lib.log.info("Previous annotation consists of: {:,} protein coding gene models and {:,} non-coding gene models".format(
lib.countGFFgenes(gffout), lib.countGFFgenes(trnaout)))
# check if organism/species/isolate passed at command line, if so, overwrite what you detected.
if args.species:
organism = args.species
if args.strain:
strain = args.strain
if args.isolate:
isolate = args.isolate
if strain:
organism_name = organism+'_'+strain
elif isolate:
organism_name = organism+'_'+isolate
else:
organism_name = organism
organism_name = organism_name.replace(' ', '_')
# check input reads
# get absolute paths for reads and concate if there are multiple
if not all_reads:
if not lib.checkannotations(os.path.join(tmpdir, 'single.fq.gz')):
if args.single:
single_reads = []
for y in args.single:
single_reads.append(os.path.abspath(y))
if single_reads[0].endswith('.gz'):
ending = '.fq.gz'
else:
ending = '.fq'
s_reads = os.path.join(tmpdir, 'single'+ending)
if len(single_reads) > 1:
lib.log.info(
"Multiple inputs for --single detected, concatenating SE reads")
lib.concatenateReads(single_reads, s_reads)
else:
s_reads = single_reads[0]
if s_reads.endswith('.fq'):
lib.Fzip_inplace(s_reads, args.cpus)
s_reads = s_reads+'.gz'
if not lib.checkannotations(os.path.join(tmpdir, 'single.fq.gz')):
if os.path.dirname(os.path.abspath(tmpdir)) != os.path.dirname(os.path.abspath(s_reads)):
lib.SafeRemove(os.path.join(tmpdir, 'single.fq.gz'))
os.symlink(os.path.realpath(s_reads),
os.path.join(tmpdir, 'single.fq.gz'))
else:
s_reads = os.path.join(tmpdir, 'single.fq.gz')
if not lib.checkannotations(os.path.join(tmpdir, 'left.fq.gz')) or not lib.checkannotations(os.path.join(tmpdir, 'right.fq.gz')):
if args.left and args.right:
left_reads = []
for i in args.left:
left_reads.append(os.path.abspath(i))
right_reads = []
for x in args.right:
right_reads.append(os.path.abspath(x))
# since I can't get the comma separated input to work through subprocess, lets concatenate reads
if left_reads[0].endswith('.gz'):
ending = '.fq.gz'
else:
ending = '.fq'
l_reads = os.path.join(tmpdir, 'left'+ending)
r_reads = os.path.join(tmpdir, 'right'+ending)
if len(left_reads) > 1:
lib.log.info(
"Multiple inputs for --left and --right detected, concatenating PE reads")
lib.concatenateReads(left_reads, l_reads)
lib.concatenateReads(right_reads, r_reads)
else:
l_reads = left_reads[0]
r_reads = right_reads[0]
if l_reads.endswith('.fq'):
lib.Fzip_inplace(l_reads, args.cpus)
l_reads = l_reads+'.gz'
if r_reads.endswith('.fq'):
lib.Fzip_inplace(r_reads, args.cpus)
r_reads = r_reads+'.gz'
if not lib.checkannotations(os.path.join(tmpdir, 'left.fq.gz')):
if os.path.dirname(os.path.abspath(tmpdir)) != os.path.dirname(os.path.abspath(l_reads)):
lib.SafeRemove(os.path.join(tmpdir, 'left.fq.gz'))
os.symlink(os.path.realpath(l_reads),
os.path.join(tmpdir, 'left.fq.gz'))
if not lib.checkannotations(os.path.join(tmpdir, 'right.fq.gz')):
if os.path.dirname(os.path.abspath(tmpdir)) != os.path.dirname(os.path.abspath(r_reads)):
lib.SafeRemove(os.path.join(tmpdir, 'right.fq.gz'))
os.symlink(os.path.realpath(r_reads),
os.path.join(tmpdir, 'right.fq.gz'))
else:
l_reads = os.path.join(tmpdir, 'left.fq.gz')
r_reads = os.path.join(tmpdir, 'right.fq.gz')
# get tuple of input reads so you can parse them in downstream tools
all_reads = (l_reads, r_reads, s_reads)
lib.log.debug('Input reads: {:}'.format(all_reads))
# trimmomatic on reads, first run PE
if not trim_reads:
if args.no_trimmomatic or args.trinity or left_norm or single_norm or args.left_norm or args.single_norm:
lib.log.info("Trimmomatic will be skipped")
trim_left = l_reads
trim_right = r_reads
trim_single = s_reads
else:
# check if they exist already in folder
if not os.path.isfile(os.path.join(tmpdir, 'trimmomatic', 'trimmed_left.fastq.gz')) or not os.path.isfile(os.path.join(tmpdir, 'trimmomatic', 'trimmed_right.fastq.gz')):
if all_reads[0] and all_reads[1]:
trim_left, trim_right = runTrimmomaticPE(
l_reads, r_reads, cpus=args.cpus)
else:
trim_left, trim_right = (None,)*2
else:
trim_left, trim_right = os.path.join(tmpdir, 'trimmomatic', 'trimmed_left.fastq.gz'), os.path.join(
tmpdir, 'trimmomatic', 'trimmed_right.fastq.gz')
if not os.path.isfile(os.path.join(tmpdir, 'trimmomatic', 'trimmed_single.fastq.gz')) and s_reads:
if all_reads[2]:
trim_single = runTrimmomaticSE(s_reads, cpus=args.cpus)
else:
trim_single = None
else:
if s_reads:
trim_single = os.path.join(
tmpdir, 'trimmomatic', 'trimmed_single.fastq.gz')
else:
trim_single = None
# get tuple of trimmed reads
trim_reads = (trim_left, trim_right, trim_single)
lib.log.debug('Quality trimmed reads: {:}'.format(trim_reads))
# check that reads are present and make sure they follow trinity naming conventions, i.e. either illumina default or /1 and /2 to PE reads
for read in trim_reads:
if read:
if not os.path.isfile(read):
lib.log.error("Trimmomatic failed, %s does not exist." % read)
sys.exit(1)
# PE reads are passed, lets make sure they have proper naming
if trim_reads[0] and trim_reads[1]:
# if needed to fix they will be fixed in place
lib.CheckFASTQandFix(trim_reads[0], trim_reads[1])
# normalize reads
if not norm_reads:
if args.no_normalize_reads or args.trinity or args.left_norm or args.single_norm:
lib.log.info("Read normalization will be skipped")
if args.left_norm:
left_norm = args.left_norm
right_norm = args.right_norm
else:
left_norm = trim_left
right_norm = trim_right
if args.single_norm:
single_norm = args.single_norm
else:
single_norm = trim_single
else:
# check if exists
if trim_left and trim_right:
if not os.path.islink(os.path.join(tmpdir, 'normalize', 'left.norm.fq')) or not os.path.islink(os.path.join(tmpdir, 'normalize', 'right.norm.fq')):
if not all(v is None for v in trim_reads):
left_norm, right_norm, single_norm = runNormalization(trim_reads, args.memory, cpus=args.cpus,
stranded=args.stranded, min_coverage=args.min_coverage, coverage=args.coverage)
else:
left_norm, right_norm = os.path.join(tmpdir, 'normalize', 'left.norm.fq'), os.path.join(
tmpdir, 'normalize', 'right.norm.fq')
if os.path.islink(os.path.join(tmpdir, 'normalize', 'single.norm.fq')):
single_norm = os.path.join(
tmpdir, 'normalize', 'single.norm.fq')
if trim_single:
if not os.path.islink(os.path.join(tmpdir, 'normalize', 'single.norm.fq')) and not trim_left and not trim_right and trim_single:
if not all(v is None for v in trim_reads):
left_norm, right_norm, single_norm = runNormalization(trim_reads, args.memory, cpus=args.cpus,
stranded=args.stranded, min_coverage=args.min_coverage, coverage=args.coverage)
else:
if os.path.islink(os.path.join(tmpdir, 'normalize', 'single.norm.fq')):
single_norm = os.path.join(
tmpdir, 'normalize', 'single.norm.fq')
else:
single_norm = None
norm_reads = (left_norm, right_norm, single_norm)
lib.log.debug('Normalized reads: {:}'.format(norm_reads))
# check if long reads are passed, get full path
if args.pacbio_isoseq:
pb_iso = os.path.abspath(args.pacbio_isoseq)
if args.nanopore_cdna:
nano_cdna = os.path.abspath(args.nanopore_cdna)
if args.nanopore_mrna:
nano_mrna = os.path.abspath(args.nanopore_mrna)
long_reads = (pb_iso, nano_cdna, nano_mrna)
lib.log.debug('Long reads: {:}'.format(long_reads))
if not trinity_results and all(v is None for v in norm_reads) and all(v is None for v in long_reads):
lib.log.error('No reads to generate transcriptome assemblies, exiting')
sys.exit(1)
if trinity_results and all(v is None for v in norm_reads) and all(v is None for v in long_reads):
lib.log.error(
'Trinity results detected, but no RNA-seq reads detected, exiting')
sys.exit(1)
if not long_clean:
long_clean = (None, None, None)
if not longReadClean:
if not all(v is None for v in long_reads):
# get long read FASTA file
longReadFA = os.path.join(tmpdir, 'long-reads.fasta')
longReadClean = os.path.join(tmpdir, 'long-reads.fasta.clean')
PBiso = os.path.join(tmpdir, 'iso-seq.fasta')
nanocdna = os.path.join(tmpdir, 'nano-cdna.fasta')
nanomrna = os.path.join(tmpdir, 'nano-mrna.fasta')
if not all(v is None for v in long_reads):
if not lib.checkannotations(longReadFA):
long_readsFA, long_clean = long2fasta(long_reads, args.cpus, tmpdir, os.path.abspath(
longReadFA), os.path.abspath(longReadClean))
else:
found_clean = []
for x in [PBiso, nanocdna, nanomrna]:
if lib.checkannotations(x):
found_clean.append(x)
else:
found_clean.append(None)
long_clean = tuple(found_clean)
if not lib.checkannotations(longReadFA):
longReadFA = None
lib.log.debug('Long reads FASTA format: {:}'.format(long_reads))
lib.log.debug('Long SeqCleaned reads: {:}'.format(long_clean))
trinity_transcripts = os.path.join(tmpdir, 'trinity.fasta')
if not trinity_results:
# now run Trinity with trimmomatic and read normalization
shortBAM = os.path.join(tmpdir, 'hisat2.coordSorted.bam')
if not lib.checkannotations(trinity_transcripts):
if args.trinity:
lib.log.info(
"Parsing assembled trinity data: {:}".format(args.trinity))
shutil.copyfile(os.path.abspath(
args.trinity), trinity_transcripts)
else:
if not all(v is None for v in norm_reads):
# run trinity genome guided
# runTrinityGG(genome, norm_reads, longReadClean, shortBAM, trinity_transcripts)
cmd = [sys.executable, os.path.join(parentdir, 'aux_scripts', 'trinity.py'),
'-f', fastaout, '-o', trinity_transcripts, '-b', shortBAM, '-t', tmpdir,
'--stranded', args.stranded, '--max_intronlen', str(
args.max_intronlen),
'--cpus', str(args.cpus), '--TRINITYHOME', TRINITY, '--memory', args.memory,
'--logfile', os.path.join(args.out, 'logfiles', 'funannotate-trinity.log')]
if args.jaccard_clip:
cmd.append('--jaccard_clip')
if norm_reads[2]: # single
cmd += ['-s', norm_reads[2]]
else:
cmd += ['-l', norm_reads[0], '-r', norm_reads[1]]
if lib.checkannotations(longReadClean):
cmd += ['--long', longReadClean]
# run trinity
subprocess.call(cmd)
if not lib.checkannotations(trinity_transcripts):
lib.log.info('ERROR: Trinity de novo assembly failed')
sys.exit(1)
else:
lib.log.info("Existing Trinity results found: {:}".format(
trinity_transcripts))
else:
shutil.copyfile(trinity_results, trinity_transcripts)
if not stringtieGTF:
# if stringtie installed, run on shortBAM incorporate into PASA later on
stringtieGTF = os.path.join(tmpdir, 'funannotate_train.stringtie.gtf')
if not lib.checkannotations(stringtieGTF):
if lib.which('stringtie') and lib.checkannotations(shortBAM):
lib.log.info(
'StringTie installed, running StringTie on Hisat2 coordsorted BAM')
cmd = ['stringtie', '-p', str(args.cpus)]
if args.stranded != 'no':
if args.stranded.startswith('R'):
cmd = cmd + ['--rf']
else:
cmd = cmd + ['--fr']
cmd = cmd + [shortBAM]
lib.runSubprocess8(cmd, '.', lib.log, stringtieGTF)
# run SeqClean to clip polyA tails and remove low quality seqs.
cleanTranscripts = trinity_transcripts+'.clean'
if not lib.checkannotations(cleanTranscripts) and lib.checkannotations(trinity_transcripts):
runSeqClean(trinity_transcripts, tmpdir, cpus=args.cpus)
# map long reads and Trinity transcripts to genome for PASA
allBAM = os.path.join(tmpdir, 'transcript.alignments.bam')
trinityBAM = os.path.join(tmpdir, 'trinity.alignments.bam')
if not lib.checkannotations(allBAM):
trinity_transcripts, cleanTranscripts = mapTranscripts(
fastaout, long_clean, cleanTranscripts, tmpdir, trinityBAM, allBAM, cpus=args.cpus, max_intronlen=args.max_intronlen)
else:
if lib.checkannotations(trinityBAM):
lib.log.info("Existing BAM alignments found: {:}, {:}".format(
trinityBAM, allBAM))
else:
lib.log.info("Existing BAM alignments found: {:}".format(allBAM))
# convert BAM to GFF3
allGFF3 = os.path.join(tmpdir, 'transcript.alignments.gff3')
trinityGFF3 = os.path.join(tmpdir, 'trinity.alignments.gff3')
if not lib.checkannotations(allGFF3) and lib.checkannotations(allBAM):
lib.log.info('Converting transcript alignments to GFF3 format')
lib.bam2gff3(allBAM, allGFF3)
if not lib.checkannotations(trinityGFF3) and lib.checkannotations(trinityBAM):
lib.log.info('Converting Trinity transcript alignments to GFF3 format')
lib.bam2gff3(trinityBAM, trinityGFF3)
# now run PASA steps
PASA_gff = os.path.join(tmpdir, 'pasa_final.gff3')
if not pasaConfigFile:
if args.pasa_gff:
lib.log.info(
"You passed a --pasa_gff file; are you sure this is a good idea?")
shutil.copyfile(args.pasa_gff, PASA_gff)
if not lib.checkannotations(PASA_gff):
if lib.checkannotations(trinityBAM):
runPASA(fastaout, trinity_transcripts, cleanTranscripts, os.path.abspath(trinityGFF3),
stringtieGTF, args.stranded, args.max_intronlen, args.cpus, gffout, organism_name,
PASA_gff, args.pasa_config, pasa_db=args.pasa_db, pasa_alignment_overlap=args.pasa_alignment_overlap,
aligners=args.aligners)
else:
runPASA(fastaout, os.path.abspath(longReadFA), os.path.abspath(longReadClean),
os.path.abspath(allGFF3), stringtieGTF, args.stranded, args.max_intronlen, args.cpus,
gffout, organism_name, PASA_gff, args.pasa_config, pasa_db=args.pasa_db,
pasa_alignment_overlap=args.pasa_alignment_overlap, aligners=args.aligners)
else:
if not lib.checkannotations(PASA_gff):
if lib.checkannotations(trinityBAM):
runPASA(fastaout, trinity_transcripts, cleanTranscripts, os.path.abspath(trinityGFF3),
stringtieGTF, args.stranded, args.max_intronlen, args.cpus, gffout, organism_name,
PASA_gff, pasaConfigFile, pasa_db=args.pasa_db, pasa_alignment_overlap=args.pasa_alignment_overlap,
aligners=args.aligners)
else:
runPASA(fastaout, os.path.abspath(longReadFA), os.path.abspath(longReadClean),
os.path.abspath(allGFF3), stringtieGTF, args.stranded, args.max_intronlen,
args.cpus, gffout, organism_name, PASA_gff, pasaConfigFile, pasa_db=args.pasa_db,
pasa_alignment_overlap=args.pasa_alignment_overlap, aligners=args.aligners)
else:
lib.log.info('Skipping PASA, found existing output: %s' % PASA_gff)
# now run Kallisto steps, if mixed PE and SE reads, only PE reads will be used for Kallisto as there isn't a reasonable way to combine them
KallistoAbundance = os.path.join(tmpdir, 'kallisto.tsv')
if args.kallisto:
lib.log.info("You passed a --kallisto file; are you sure this is a good idea?")
shutil.copyfile(args.kallisto, KallistoAbundance)
if all(v is None for v in trim_reads):
kallistoreads = norm_reads
else:
kallistoreads = trim_reads
if all(v is None for v in kallistoreads) and lib.checkannotations(longReadClean):
# use minimap to count reads
lib.log.info(
'Generating relative expression values to PASA transcripts')
PASAtranscripts = os.path.join(tmpdir, 'transcripts.fa')
cmd = [os.path.join(
PASA, 'misc_utilities', 'gff3_file_to_proteins.pl'), PASA_gff, fastaout, 'cDNA']
if not lib.checkannotations(PASAtranscripts):
lib.runSubprocess2(cmd, '.', lib.log, PASAtranscripts)
PASAdict = pasa_transcript2gene(PASAtranscripts)
minimapBAM = os.path.join(tmpdir, 'long-reads_transcripts.bam')
minimap2_cmd = ['minimap2', '-ax' 'map-ont', '-t',
str(args.cpus), '--secondary=no', PASAtranscripts, longReadClean]
samtools_cmd = ['samtools', 'sort', '--reference', PASAtranscripts,
'-@', '2', '-o', minimapBAM, '-']
if not lib.checkannotations(minimapBAM):
lib.log.debug('{} | {}'.format(' '.join(minimap2_cmd), ' '. join(samtools_cmd)))
p1 = subprocess.Popen(minimap2_cmd, stdout=subprocess.PIPE, stderr=FNULL)
p2 = subprocess.Popen(samtools_cmd, stdout=subprocess.PIPE, stderr=FNULL, stdin=p1.stdout)
p1.stdout.close()
p2.communicate()
if not lib.checkannotations(KallistoAbundance):
lib.mapCount(minimapBAM, PASAdict, KallistoAbundance)
else:
if not lib.checkannotations(KallistoAbundance):
runKallisto(PASA_gff, fastaout, kallistoreads,
args.stranded, args.cpus, KallistoAbundance)
else:
lib.log.info(
"Existing Kallisto output found: {:}".format(KallistoAbundance))
# parse Kallisto results with PASA GFF
global ExpressionValues
ExpressionValues = {}
BestModelGFF = os.path.join(tmpdir, 'bestmodels.gff3')
getBestModels(PASA_gff, fastaout, KallistoAbundance,
args.alt_transcripts, BestModelGFF)
# make sure tRNA models don't overlap new gene models
cleanTRNA = os.path.join(tmpdir, 'trna.no-overlaps.gff')
lib.validate_tRNA(trnaout, BestModelGFF, False, cleanTRNA)
# generate tbl file
gagdir = os.path.join(tmpdir, 'tbl2asn')
TBLFile = os.path.join(gagdir, 'genome.tbl')
if os.path.isdir(gagdir):
shutil.rmtree(gagdir)
os.makedirs(gagdir)
GFF2tblCombinedNEW(BestModelGFF, fastaout, cleanTRNA, locustag, genenumber,
justify, args.SeqCenter, args.SeqAccession, TBLFile,
alt_transcripts=args.alt_transcripts)
# need a function here to clean up the ncbi tbl file if this is a reannotation
# a reannotation would have a WGS_accession, if none, then it is a first pass and not from genbank
if WGS_accession:
os.rename(os.path.join(tmpdir, 'tbl2asn', 'genome.tbl'),
os.path.join(tmpdir, 'tbl2asn', 'genome.tbl.bak'))
p2g = {}
if args.p2g: # load into dictionary
shutil.copyfile(args.p2g, os.path.join(
args.out, 'update_results', 'ncbi.p2g'))
with open(args.p2g, 'r') as input:
for line in input:
cols = line.split('\t')
if not cols[0] in p2g:
p2g[cols[0]] = cols[1]
with open(os.path.join(tmpdir, 'tbl2asn', 'genome.tbl'), 'w') as outfile:
with open(os.path.join(tmpdir, 'tbl2asn', 'genome.tbl.bak'), 'r') as infile:
for line in infile:
line = line.replace('\n', '')
if line.startswith('\t\t\tprotein_id') or line.startswith('\t\t\ttranscript_id'):
ID = line.rsplit('|', 1)[-1].replace('_mrna', '')
type = 'prot'
if 'transcript_id' in line:
type = 'transcript'
if not ID in p2g:
if type == 'prot':
outfile.write(
'\t\t\tprotein_id\tgnl|%s|%s\n' % (WGS_accession, ID))
elif type == 'transcript':
outfile.write(
'\t\t\ttranscript_id\tgnl|%s|%s_mrna\n' % (WGS_accession, ID))
else:
p2gID = p2g.get(ID)
if type == 'prot':
outfile.write('\t\t\tprotein_id\tgnl|%s|%s|gb|%s\n' % (
WGS_accession, ID, p2gID))
elif type == 'transcript':
outfile.write(
'\t\t\ttranscript_id\tgnl|%s|%s_mrna\n' % (WGS_accession, ID))
else:
outfile.write('%s\n' % line)
# run tbl2asn in new directory directory
lib.log.info("Converting to Genbank format")
discrep = os.path.join(args.out, 'update_results',
organism_name + '.discrepency.report.txt')
# this would mean it is a GenBank reannotation, so update accordingly. else it is just 1st version.
if version and WGS_accession:
rev_version = int(version) + 1
else:
rev_version = 1
# have to run as subprocess because of multiprocessing issues
cmd = [sys.executable, os.path.join(parentdir, 'aux_scripts', 'tbl2asn_parallel.py'),
'-i', TBLFile, '-f', fastaout, '-o', gagdir, '--sbt', SBT, '-d', discrep,
'-s', organism, '-t', args.tbl2asn, '-v', str(rev_version), '-c', str(args.cpus)]
if isolate:
cmd += ['--isolate', isolate]
if strain:
cmd += ['--strain', strain]
lib.log.debug(' '.join(cmd))
subprocess.call(cmd)
# grab results, populate results output directory
final_fasta = os.path.join(
args.out, 'update_results', organism_name + '.scaffolds.fa')
final_gff = os.path.join(
args.out, 'update_results', organism_name + '.gff3')
final_gbk = os.path.join(
args.out, 'update_results', organism_name + '.gbk')
final_tbl = os.path.join(
args.out, 'update_results', organism_name + '.tbl')
final_proteins = os.path.join(
args.out, 'update_results', organism_name + '.proteins.fa')
final_transcripts = os.path.join(
args.out, 'update_results', organism_name + '.mrna-transcripts.fa')
final_cds_transcripts = os.path.join(
args.out, 'update_results', organism_name + '.cds-transcripts.fa')
final_validation = os.path.join(
args.out, 'update_results', organism_name+'.validation.txt')
final_error = os.path.join(
args.out, 'update_results', organism_name+'.error.summary.txt')
final_fixes = os.path.join(
args.out, 'update_results', organism_name+'.models-need-fixing.txt')
final_stats = os.path.join(args.out, 'update_results', organism_name+'.stats.json')
# retrieve files/reorganize
shutil.copyfile(os.path.join(gagdir, 'genome.gbf'), final_gbk)
shutil.copyfile(os.path.join(gagdir, 'genome.tbl'), final_tbl)
shutil.copyfile(os.path.join(gagdir, 'genome.val'), final_validation)
shutil.copyfile(os.path.join(gagdir, 'errorsummary.val'), final_error)
lib.log.info("Collecting final annotation files")
lib.tbl2allout(final_tbl, fastaout, final_gff, final_proteins,
final_transcripts, final_cds_transcripts, final_fasta)
lib.annotation_summary(fastaout, final_stats, tbl=final_tbl,
transcripts=allGFF3, previous=existingStats)
# since no place to write the WGS accession to, output to a file for reading by funannotate annotate
with open(os.path.join(args.out, 'update_results', 'WGS_accession.txt'), 'w') as out:
out.write('%s\n' % WGS_accession)
# last step will be to compare old gene models versus updated ones, outputting a tsv file describing the changes
Changes = os.path.join(args.out, 'update_results',
organism_name + '.pasa-reannotation.changes.txt')
if args.gff and args.fasta:
compareAnnotations2(args.gff, final_gbk, Changes, args=args)
else:
compareAnnotations2(GBK, final_gbk, Changes, args=args)
lib.log.info(
"Funannotate update is finished, output files are in the %s/update_results folder" % (args.out))
errors = lib.ncbiCheckErrors(
final_error, final_validation, locustag, final_fixes)
if errors > 0:
print('-------------------------------------------------------')
lib.log.info("Manually edit the tbl file %s, then run:\n\nfunannotate fix -i %s -t %s\n" %
(final_tbl, final_gbk, final_tbl))
lib.log.info(
"After the problematic gene models are fixed, you can proceed with functional annotation.")
lib.log.info("Your next step might be functional annotation, suggested commands:\n\
-------------------------------------------------------\n\
Run InterProScan (Docker required): \nfunannotate iprscan -i {:} -m docker -c {:}\n\n\
Run antiSMASH: \nfunannotate remote -i {:} -m antismash -e youremail@server.edu\n\n\
Annotate Genome: \nfunannotate annotate -i {:} --cpus {:} --sbt yourSBTfile.txt\n\
-------------------------------------------------------\n\
".format(args.out,
args.cpus,
args.out,
args.out,
args.cpus))
if __name__ == "__main__":
main(sys.argv[1:])
| [
"funannotate.library.ncbiCheckErrors",
"os.remove",
"funannotate.library.get_version",
"funannotate.library.runSubprocess2",
"argparse.ArgumentParser",
"funannotate.library.runSubprocess8",
"funannotate.library.runSubprocess",
"funannotate.library.getSeqRegions",
"funannotate.interlap.InterLap",
"... | [((11881, 11915), 'funannotate.library.gff2dict', 'lib.gff2dict', (['gff_in', 'fasta', 'genes'], {}), '(gff_in, fasta, genes)\n', (11893, 11915), True, 'import funannotate.library as lib\n'), ((18236, 18253), 'funannotate.library.which', 'lib.which', (['"""pigz"""'], {}), "('pigz')\n", (18245, 18253), True, 'import funannotate.library as lib\n'), ((18680, 18697), 'funannotate.library.which', 'lib.which', (['"""pigz"""'], {}), "('pigz')\n", (18689, 18697), True, 'import funannotate.library as lib\n'), ((19117, 19152), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""'], {}), "(tmpdir, 'trimmomatic')\n", (19129, 19152), False, 'import os\n'), ((19219, 19289), 'funannotate.library.log.info', 'lib.log.info', (['"""Adapter and Quality trimming PE reads with Trimmomatic"""'], {}), "('Adapter and Quality trimming PE reads with Trimmomatic')\n", (19231, 19289), True, 'import funannotate.library as lib\n'), ((19308, 19350), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_left.fastq"""'], {}), "(folder, 'trimmed_left.fastq')\n", (19320, 19350), False, 'import os\n'), ((19369, 19420), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_left.unpaired.fastq"""'], {}), "(folder, 'trimmed_left.unpaired.fastq')\n", (19381, 19420), False, 'import os\n'), ((19440, 19483), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_right.fastq"""'], {}), "(folder, 'trimmed_right.fastq')\n", (19452, 19483), False, 'import os\n'), ((19503, 19555), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_right.unpaired.fastq"""'], {}), "(folder, 'trimmed_right.unpaired.fastq')\n", (19515, 19555), False, 'import os\n'), ((19880, 19916), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', '"""."""', 'lib.log'], {}), "(cmd, '.', lib.log)\n", (19897, 19916), True, 'import funannotate.library as lib\n'), ((20036, 20081), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_left.fastq.gz"""'], {}), "(folder, 'trimmed_left.fastq.gz')\n", (20048, 20081), False, 'import os\n'), ((20099, 20145), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_right.fastq.gz"""'], {}), "(folder, 'trimmed_right.fastq.gz')\n", (20111, 20145), False, 'import os\n'), ((20315, 20350), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""'], {}), "(tmpdir, 'trimmomatic')\n", (20327, 20350), False, 'import os\n'), ((20417, 20487), 'funannotate.library.log.info', 'lib.log.info', (['"""Adapter and Quality trimming SE reads with Trimmomatic"""'], {}), "('Adapter and Quality trimming SE reads with Trimmomatic')\n", (20429, 20487), True, 'import funannotate.library as lib\n'), ((20501, 20545), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_single.fastq"""'], {}), "(folder, 'trimmed_single.fastq')\n", (20513, 20545), False, 'import os\n'), ((20807, 20843), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', '"""."""', 'lib.log'], {}), "(cmd, '.', lib.log)\n", (20824, 20843), True, 'import funannotate.library as lib\n'), ((20848, 20878), 'funannotate.library.Fzip_inplace', 'lib.Fzip_inplace', (['output', 'cpus'], {}), '(output, cpus)\n', (20864, 20878), True, 'import funannotate.library as lib\n'), ((20897, 20944), 'os.path.join', 'os.path.join', (['folder', '"""trimmed_single.fastq.gz"""'], {}), "(folder, 'trimmed_single.fastq.gz')\n", (20909, 20944), False, 'import os\n'), ((21265, 21317), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity_normalization.SE.log"""'], {}), "(tmpdir, 'trinity_normalization.SE.log')\n", (21277, 21317), False, 'import os\n'), ((21336, 21388), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity_normalization.PE.log"""'], {}), "(tmpdir, 'trinity_normalization.PE.log')\n", (21348, 21388), False, 'import os\n'), ((21393, 21448), 'funannotate.library.log.info', 'lib.log.info', (['"""Running read normalization with Trinity"""'], {}), "('Running read normalization with Trinity')\n", (21405, 21448), True, 'import funannotate.library as lib\n'), ((23199, 23244), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'output'], {}), "(cmd, '.', lib.log, output)\n", (23217, 23244), True, 'import funannotate.library as lib\n'), ((23630, 23673), 'os.path.join', 'os.path.join', (['PASA', '"""pasa_conf"""', '"""conf.txt"""'], {}), "(PASA, 'pasa_conf', 'conf.txt')\n", (23642, 23673), False, 'import os\n'), ((23681, 23707), 'os.environ.get', 'os.environ.get', (['"""PASACONF"""'], {}), "('PASACONF')\n", (23695, 23707), False, 'import os\n'), ((24203, 24245), 'os.path.join', 'os.path.join', (['folder', '"""existing_pasa.gff3"""'], {}), "(folder, 'existing_pasa.gff3')\n", (24215, 24245), False, 'import os\n'), ((24392, 24449), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', 'folder', 'lib.log', 'pasaExistingGFF'], {}), '(cmd, folder, lib.log, pasaExistingGFF)\n', (24410, 24449), True, 'import funannotate.library as lib\n'), ((26131, 26159), 'os.path.join', 'os.path.join', (['tmpdir', '"""pasa"""'], {}), "(tmpdir, 'pasa')\n", (26143, 26159), False, 'import os\n'), ((26236, 26277), 'os.path.join', 'os.path.join', (['folder', '"""pasa-assembly.log"""'], {}), "(folder, 'pasa-assembly.log')\n", (26248, 26277), False, 'import os\n'), ((26293, 26337), 'os.path.join', 'os.path.join', (['folder', '"""pasa-comparison1.log"""'], {}), "(folder, 'pasa-comparison1.log')\n", (26305, 26337), False, 'import os\n'), ((26353, 26397), 'os.path.join', 'os.path.join', (['folder', '"""pasa-comparison2.log"""'], {}), "(folder, 'pasa-comparison2.log')\n", (26365, 26397), False, 'import os\n'), ((26449, 26490), 'os.path.join', 'os.path.join', (['folder', '"""alignAssembly.txt"""'], {}), "(folder, 'alignAssembly.txt')\n", (26461, 26490), False, 'import os\n'), ((26509, 26549), 'os.path.join', 'os.path.join', (['folder', '"""annotCompare.txt"""'], {}), "(folder, 'annotCompare.txt')\n", (26521, 26549), False, 'import os\n'), ((31718, 31775), 'funannotate.library.log.info', 'lib.log.info', (['"""Running PASA annotation comparison step 1"""'], {}), "('Running PASA annotation comparison step 1')\n", (31730, 31775), True, 'import funannotate.library as lib\n'), ((31984, 32022), 'funannotate.library.versionCheck', 'lib.versionCheck', (['PASAVERSION', '"""2.3.0"""'], {}), "(PASAVERSION, '2.3.0')\n", (32000, 32022), True, 'import funannotate.library as lib\n'), ((32169, 32219), 'funannotate.library.runSubprocess6', 'lib.runSubprocess6', (['cmd', 'folder', 'lib.log', 'pasaLOG1'], {}), '(cmd, folder, lib.log, pasaLOG1)\n', (32187, 32219), True, 'import funannotate.library as lib\n'), ((32257, 32275), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (32267, 32275), False, 'import os\n'), ((32576, 32633), 'funannotate.library.log.info', 'lib.log.info', (['"""Running PASA annotation comparison step 2"""'], {}), "('Running PASA annotation comparison step 2')\n", (32588, 32633), True, 'import funannotate.library as lib\n'), ((32842, 32880), 'funannotate.library.versionCheck', 'lib.versionCheck', (['PASAVERSION', '"""2.3.0"""'], {}), "(PASAVERSION, '2.3.0')\n", (32858, 32880), True, 'import funannotate.library as lib\n'), ((33023, 33073), 'funannotate.library.runSubprocess6', 'lib.runSubprocess6', (['cmd', 'folder', 'lib.log', 'pasaLOG2'], {}), '(cmd, folder, lib.log, pasaLOG2)\n', (33041, 33073), True, 'import funannotate.library as lib\n'), ((33111, 33129), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (33121, 33129), False, 'import os\n'), ((33470, 33536), 'funannotate.library.log.debug', 'lib.log.debug', (["('copying final PASA GFF3 to output: %s' % round2GFF)"], {}), "('copying final PASA GFF3 to output: %s' % round2GFF)\n", (33483, 33536), True, 'import funannotate.library as lib\n'), ((33565, 33599), 'shutil.copyfile', 'shutil.copyfile', (['round2GFF', 'output'], {}), '(round2GFF, output)\n', (33580, 33599), False, 'import shutil\n'), ((37955, 37987), 'os.path.isfile', 'os.path.isfile', (["(input + '.clean')"], {}), "(input + '.clean')\n", (37969, 37987), False, 'import os\n'), ((38291, 38309), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (38301, 38309), False, 'import os\n'), ((38599, 38644), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'tmpout'], {}), "(cmd, '.', lib.log, tmpout)\n", (38617, 38644), True, 'import funannotate.library as lib\n'), ((38939, 38956), 'os.remove', 'os.remove', (['tmpout'], {}), '(tmpout)\n', (38948, 38956), False, 'import os\n'), ((39106, 39151), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'tmpout'], {}), "(cmd, '.', lib.log, tmpout)\n", (39124, 39151), True, 'import funannotate.library as lib\n'), ((39446, 39463), 'os.remove', 'os.remove', (['tmpout'], {}), '(tmpout)\n', (39455, 39463), False, 'import os\n'), ((39675, 39721), 'os.path.join', 'os.path.join', (['tmpdir', '"""isoseq.coordSorted.bam"""'], {}), "(tmpdir, 'isoseq.coordSorted.bam')\n", (39687, 39721), False, 'import os\n'), ((39736, 39784), 'os.path.join', 'os.path.join', (['tmpdir', '"""isoseq.coordSorted.fasta"""'], {}), "(tmpdir, 'isoseq.coordSorted.fasta')\n", (39748, 39784), False, 'import os\n'), ((39804, 39853), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano_cDNA.coordSorted.bam"""'], {}), "(tmpdir, 'nano_cDNA.coordSorted.bam')\n", (39816, 39853), False, 'import os\n'), ((39874, 39925), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano_cDNA.coordSorted.fasta"""'], {}), "(tmpdir, 'nano_cDNA.coordSorted.fasta')\n", (39886, 39925), False, 'import os\n'), ((39945, 39994), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano_mRNA.coordSorted.bam"""'], {}), "(tmpdir, 'nano_mRNA.coordSorted.bam')\n", (39957, 39994), False, 'import os\n'), ((40015, 40066), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano_mRNA.coordSorted.fasta"""'], {}), "(tmpdir, 'nano_mRNA.coordSorted.fasta')\n", (40027, 40066), False, 'import os\n'), ((40104, 40151), 'os.path.join', 'os.path.join', (['tmpdir', '"""long-reads.mapped.fasta"""'], {}), "(tmpdir, 'long-reads.mapped.fasta')\n", (40116, 40151), False, 'import os\n'), ((41337, 41368), 'funannotate.library.checkannotations', 'lib.checkannotations', (['assembled'], {}), '(assembled)\n', (41357, 41368), True, 'import funannotate.library as lib\n'), ((44485, 44594), 'funannotate.library.log.info', 'lib.log.info', (['"""Using Kallisto TPM data to determine which PASA gene models to select at each locus"""'], {}), "(\n 'Using Kallisto TPM data to determine which PASA gene models to select at each locus'\n )\n", (44497, 44594), True, 'import funannotate.library as lib\n'), ((44640, 44676), 'os.path.join', 'os.path.join', (['tmpdir', '"""getBestModel"""'], {}), "(tmpdir, 'getBestModel')\n", (44652, 44676), False, 'import os\n'), ((44681, 44700), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (44692, 44700), False, 'import os\n'), ((44723, 44761), 'os.path.join', 'os.path.join', (['folder', '"""transcripts.fa"""'], {}), "(folder, 'transcripts.fa')\n", (44735, 44761), False, 'import os\n'), ((44889, 44928), 'funannotate.library.log.info', 'lib.log.info', (['"""Building Kallisto index"""'], {}), "('Building Kallisto index')\n", (44901, 44928), True, 'import funannotate.library as lib\n'), ((44933, 44987), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'PASAtranscripts'], {}), "(cmd, '.', lib.log, PASAtranscripts)\n", (44951, 44987), True, 'import funannotate.library as lib\n'), ((45123, 45159), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', '"""."""', 'lib.log'], {}), "(cmd, '.', lib.log)\n", (45140, 45159), True, 'import funannotate.library as lib\n'), ((46011, 46074), 'funannotate.library.log.info', 'lib.log.info', (['"""Mapping reads using pseudoalignment in Kallisto"""'], {}), "('Mapping reads using pseudoalignment in Kallisto')\n", (46023, 46074), True, 'import funannotate.library as lib\n'), ((46079, 46115), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', '"""."""', 'lib.log'], {}), "(cmd, '.', lib.log)\n", (46096, 46115), True, 'import funannotate.library as lib\n'), ((53176, 53197), 'collections.defaultdict', 'defaultdict', (['InterLap'], {}), '(InterLap)\n', (53187, 53197), False, 'from collections import defaultdict\n'), ((53237, 53289), 'funannotate.library.gff2interlapDict', 'lib.gff2interlapDict', (['evm', 'genome', 'gene_inter', 'Genes'], {}), '(evm, genome, gene_inter, Genes)\n', (53257, 53289), True, 'import funannotate.library as lib\n'), ((53355, 53412), 'funannotate.library.gff2interlapDict', 'lib.gff2interlapDict', (['trnascan', 'genome', 'gene_inter', 'Genes'], {}), '(trnascan, genome, gene_inter, Genes)\n', (53375, 53412), True, 'import funannotate.library as lib\n'), ((53566, 53585), 'collections.OrderedDict', 'OrderedDict', (['sGenes'], {}), '(sGenes)\n', (53577, 53585), False, 'from collections import OrderedDict\n'), ((53781, 53874), 'funannotate.library.log.info', 'lib.log.info', (['"""Validating gene models (renaming, checking translations, filtering, etc)"""'], {}), "(\n 'Validating gene models (renaming, checking translations, filtering, etc)')\n", (53793, 53874), True, 'import funannotate.library as lib\n'), ((57637, 57731), 'funannotate.library.dicts2tbl', 'lib.dicts2tbl', (['renamedGenes', 'scaff2genes', 'scaffLen', 'SeqCenter', 'SeqRefNum', 'skipList', 'tblout'], {}), '(renamedGenes, scaff2genes, scaffLen, SeqCenter, SeqRefNum,\n skipList, tblout)\n', (57650, 57731), True, 'import funannotate.library as lib\n'), ((57924, 57945), 'collections.defaultdict', 'defaultdict', (['InterLap'], {}), '(InterLap)\n', (57935, 57945), False, 'from collections import defaultdict\n'), ((58636, 58657), 'collections.defaultdict', 'defaultdict', (['InterLap'], {}), '(InterLap)\n', (58647, 58657), False, 'from collections import defaultdict\n'), ((58685, 58718), 'funannotate.library.gff2dict', 'lib.gff2dict', (['input', 'fasta', 'Genes'], {}), '(input, fasta, Genes)\n', (58697, 58718), True, 'import funannotate.library as lib\n'), ((60513, 60549), 'Bio.pairwise2.align.globalxx', 'pairwise2.align.globalxx', (['query', 'ref'], {}), '(query, ref)\n', (60537, 60549), False, 'from Bio import pairwise2\n'), ((61200, 61260), 'funannotate.library.log.info', 'lib.log.info', (['"""Parsing GenBank files...comparing annotation"""'], {}), "('Parsing GenBank files...comparing annotation')\n", (61212, 61260), True, 'import funannotate.library as lib\n'), ((73830, 73849), 'funannotate.interlap.InterLap', 'InterLap', (['reference'], {}), '(reference)\n', (73838, 73849), False, 'from funannotate.interlap import InterLap\n'), ((75248, 75539), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""funannotate-update.py"""', 'usage': '"""%(prog)s [options] -i genome.gbk -l left.fq.gz -r right.fg.gz"""', 'description': '"""Script is a wrapper for automated Trinity/PASA reannotation."""', 'epilog': '"""Written by <NAME> (2017) <EMAIL>"""', 'formatter_class': 'MyFormatter'}), "(prog='funannotate-update.py', usage=\n '%(prog)s [options] -i genome.gbk -l left.fq.gz -r right.fg.gz',\n description=\n 'Script is a wrapper for automated Trinity/PASA reannotation.', epilog=\n 'Written by <NAME> (2017) <EMAIL>', formatter_class=MyFormatter)\n", (75271, 75539), False, 'import argparse\n'), ((81702, 81739), 'os.path.join', 'os.path.join', (['args.out', '"""update_misc"""'], {}), "(args.out, 'update_misc')\n", (81714, 81739), False, 'import os\n'), ((81778, 81838), 'os.path.join', 'os.path.join', (['args.out', '"""logfiles"""', '"""funannotate-update.log"""'], {}), "(args.out, 'logfiles', 'funannotate-update.log')\n", (81790, 81838), False, 'import os\n'), ((81846, 81870), 'os.path.isfile', 'os.path.isfile', (['log_name'], {}), '(log_name)\n', (81860, 81870), False, 'import os\n'), ((81971, 81997), 'funannotate.library.setupLogging', 'lib.setupLogging', (['log_name'], {}), '(log_name)\n', (81987, 81997), True, 'import funannotate.library as lib\n'), ((82041, 82064), 'funannotate.library.log.debug', 'lib.log.debug', (['cmd_args'], {}), '(cmd_args)\n', (82054, 82064), True, 'import funannotate.library as lib\n'), ((82138, 82154), 'funannotate.library.SystemInfo', 'lib.SystemInfo', ([], {}), '()\n', (82152, 82154), True, 'import funannotate.library as lib\n'), ((82203, 82220), 'funannotate.library.get_version', 'lib.get_version', ([], {}), '()\n', (82218, 82220), True, 'import funannotate.library as lib\n'), ((82225, 82261), 'funannotate.library.log.info', 'lib.log.info', (["('Running %s' % version)"], {}), "('Running %s' % version)\n", (82237, 82261), True, 'import funannotate.library as lib\n'), ((84006, 84037), 'funannotate.library.CheckDependencies', 'lib.CheckDependencies', (['programs'], {}), '(programs)\n', (84027, 84037), True, 'import funannotate.library as lib\n'), ((84362, 84397), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.gff3"""'], {}), "(tmpdir, 'genome.gff3')\n", (84374, 84397), False, 'import os\n'), ((84416, 84458), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.proteins.fa"""'], {}), "(tmpdir, 'genome.proteins.fa')\n", (84428, 84458), False, 'import os\n'), ((84473, 84513), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.trna.gff3"""'], {}), "(tmpdir, 'genome.trna.gff3')\n", (84485, 84513), False, 'import os\n'), ((84529, 84562), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.fa"""'], {}), "(tmpdir, 'genome.fa')\n", (84541, 84562), False, 'import os\n'), ((84579, 84612), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.ss"""'], {}), "(tmpdir, 'genome.ss')\n", (84591, 84612), False, 'import os\n'), ((84627, 84663), 'os.path.join', 'os.path.join', (['tmpdir', '"""genome.exons"""'], {}), "(tmpdir, 'genome.exons')\n", (84639, 84663), False, 'import os\n'), ((104013, 104050), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity.fasta"""'], {}), "(tmpdir, 'trinity.fasta')\n", (104025, 104050), False, 'import os\n'), ((107310, 107359), 'os.path.join', 'os.path.join', (['tmpdir', '"""transcript.alignments.bam"""'], {}), "(tmpdir, 'transcript.alignments.bam')\n", (107322, 107359), False, 'import os\n'), ((107377, 107423), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity.alignments.bam"""'], {}), "(tmpdir, 'trinity.alignments.bam')\n", (107389, 107423), False, 'import os\n'), ((107959, 108009), 'os.path.join', 'os.path.join', (['tmpdir', '"""transcript.alignments.gff3"""'], {}), "(tmpdir, 'transcript.alignments.gff3')\n", (107971, 108009), False, 'import os\n'), ((108028, 108075), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity.alignments.gff3"""'], {}), "(tmpdir, 'trinity.alignments.gff3')\n", (108040, 108075), False, 'import os\n'), ((108511, 108550), 'os.path.join', 'os.path.join', (['tmpdir', '"""pasa_final.gff3"""'], {}), "(tmpdir, 'pasa_final.gff3')\n", (108523, 108550), False, 'import os\n'), ((110835, 110871), 'os.path.join', 'os.path.join', (['tmpdir', '"""kallisto.tsv"""'], {}), "(tmpdir, 'kallisto.tsv')\n", (110847, 110871), False, 'import os\n'), ((113046, 113085), 'os.path.join', 'os.path.join', (['tmpdir', '"""bestmodels.gff3"""'], {}), "(tmpdir, 'bestmodels.gff3')\n", (113058, 113085), False, 'import os\n'), ((113272, 113316), 'os.path.join', 'os.path.join', (['tmpdir', '"""trna.no-overlaps.gff"""'], {}), "(tmpdir, 'trna.no-overlaps.gff')\n", (113284, 113316), False, 'import os\n'), ((113321, 113379), 'funannotate.library.validate_tRNA', 'lib.validate_tRNA', (['trnaout', 'BestModelGFF', '(False)', 'cleanTRNA'], {}), '(trnaout, BestModelGFF, False, cleanTRNA)\n', (113338, 113379), True, 'import funannotate.library as lib\n'), ((113418, 113449), 'os.path.join', 'os.path.join', (['tmpdir', '"""tbl2asn"""'], {}), "(tmpdir, 'tbl2asn')\n", (113430, 113449), False, 'import os\n'), ((113464, 113498), 'os.path.join', 'os.path.join', (['gagdir', '"""genome.tbl"""'], {}), "(gagdir, 'genome.tbl')\n", (113476, 113498), False, 'import os\n'), ((113506, 113527), 'os.path.isdir', 'os.path.isdir', (['gagdir'], {}), '(gagdir)\n', (113519, 113527), False, 'import os\n'), ((113563, 113582), 'os.makedirs', 'os.makedirs', (['gagdir'], {}), '(gagdir)\n', (113574, 113582), False, 'import os\n'), ((116135, 116179), 'funannotate.library.log.info', 'lib.log.info', (['"""Converting to Genbank format"""'], {}), "('Converting to Genbank format')\n", (116147, 116179), True, 'import funannotate.library as lib\n'), ((116194, 116281), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.discrepency.report.txt')"], {}), "(args.out, 'update_results', organism_name +\n '.discrepency.report.txt')\n", (116206, 116281), False, 'import os\n'), ((116993, 117013), 'subprocess.call', 'subprocess.call', (['cmd'], {}), '(cmd)\n', (117008, 117013), False, 'import subprocess\n'), ((117087, 117160), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.scaffolds.fa')"], {}), "(args.out, 'update_results', organism_name + '.scaffolds.fa')\n", (117099, 117160), False, 'import os\n'), ((117186, 117251), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.gff3')"], {}), "(args.out, 'update_results', organism_name + '.gff3')\n", (117198, 117251), False, 'import os\n'), ((117277, 117341), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.gbk')"], {}), "(args.out, 'update_results', organism_name + '.gbk')\n", (117289, 117341), False, 'import os\n'), ((117367, 117431), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.tbl')"], {}), "(args.out, 'update_results', organism_name + '.tbl')\n", (117379, 117431), False, 'import os\n'), ((117462, 117534), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.proteins.fa')"], {}), "(args.out, 'update_results', organism_name + '.proteins.fa')\n", (117474, 117534), False, 'import os\n'), ((117568, 117653), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.mrna-transcripts.fa')"], {}), "(args.out, 'update_results', organism_name + '.mrna-transcripts.fa'\n )\n", (117580, 117653), False, 'import os\n'), ((117686, 117765), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.cds-transcripts.fa')"], {}), "(args.out, 'update_results', organism_name + '.cds-transcripts.fa')\n", (117698, 117765), False, 'import os\n'), ((117798, 117873), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.validation.txt')"], {}), "(args.out, 'update_results', organism_name + '.validation.txt')\n", (117810, 117873), False, 'import os\n'), ((117899, 117977), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.error.summary.txt')"], {}), "(args.out, 'update_results', organism_name + '.error.summary.txt')\n", (117911, 117977), False, 'import os\n'), ((118003, 118090), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.models-need-fixing.txt')"], {}), "(args.out, 'update_results', organism_name +\n '.models-need-fixing.txt')\n", (118015, 118090), False, 'import os\n'), ((118112, 118183), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.stats.json')"], {}), "(args.out, 'update_results', organism_name + '.stats.json')\n", (118124, 118183), False, 'import os\n'), ((118503, 118552), 'funannotate.library.log.info', 'lib.log.info', (['"""Collecting final annotation files"""'], {}), "('Collecting final annotation files')\n", (118515, 118552), True, 'import funannotate.library as lib\n'), ((118557, 118678), 'funannotate.library.tbl2allout', 'lib.tbl2allout', (['final_tbl', 'fastaout', 'final_gff', 'final_proteins', 'final_transcripts', 'final_cds_transcripts', 'final_fasta'], {}), '(final_tbl, fastaout, final_gff, final_proteins,\n final_transcripts, final_cds_transcripts, final_fasta)\n', (118571, 118678), True, 'import funannotate.library as lib\n'), ((118698, 118808), 'funannotate.library.annotation_summary', 'lib.annotation_summary', (['fastaout', 'final_stats'], {'tbl': 'final_tbl', 'transcripts': 'allGFF3', 'previous': 'existingStats'}), '(fastaout, final_stats, tbl=final_tbl, transcripts=\n allGFF3, previous=existingStats)\n', (118720, 118808), True, 'import funannotate.library as lib\n'), ((119200, 119294), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', "(organism_name + '.pasa-reannotation.changes.txt')"], {}), "(args.out, 'update_results', organism_name +\n '.pasa-reannotation.changes.txt')\n", (119212, 119294), False, 'import os\n'), ((119498, 119615), 'funannotate.library.log.info', 'lib.log.info', (["('Funannotate update is finished, output files are in the %s/update_results folder'\n % args.out)"], {}), "(\n 'Funannotate update is finished, output files are in the %s/update_results folder'\n % args.out)\n", (119510, 119615), True, 'import funannotate.library as lib\n'), ((119630, 119703), 'funannotate.library.ncbiCheckErrors', 'lib.ncbiCheckErrors', (['final_error', 'final_validation', 'locustag', 'final_fixes'], {}), '(final_error, final_validation, locustag, final_fixes)\n', (119649, 119703), True, 'import funannotate.library as lib\n'), ((3361, 3456), 'funannotate.library.log.debug', 'lib.log.debug', (["('%s CDS/mRNA features out of phase, trying to fix. %s' % (gene, mRNA_order))"], {}), "('%s CDS/mRNA features out of phase, trying to fix. %s' % (\n gene, mRNA_order))\n", (3374, 3456), True, 'import funannotate.library as lib\n'), ((4963, 5199), 'funannotate.library.log.info', 'lib.log.info', (['"""GenBank file has multiple transcripts per locus, I tried my hardest to match them up but can\'t gaurantee there aren\'t errors. You can blame NCBI. You may want to try to pass a GFF3 + FASTA files instead of GBK."""'], {}), '(\n "GenBank file has multiple transcripts per locus, I tried my hardest to match them up but can\'t gaurantee there aren\'t errors. You can blame NCBI. You may want to try to pass a GFF3 + FASTA files instead of GBK."\n )\n', (4975, 5199), True, 'import funannotate.library as lib\n'), ((11191, 11211), 'natsort.natsorted', 'natsorted', (['LocusTags'], {}), '(LocusTags)\n', (11200, 11211), False, 'from natsort import natsorted\n'), ((17600, 17620), 'natsort.natsorted', 'natsorted', (['LocusTags'], {}), '(LocusTags)\n', (17609, 17620), False, 'from natsort import natsorted\n'), ((18403, 18448), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'output'], {}), "(cmd, '.', lib.log, output)\n", (18421, 18448), True, 'import funannotate.library as lib\n'), ((18815, 18860), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'output'], {}), "(cmd, '.', lib.log, output)\n", (18833, 18860), True, 'import funannotate.library as lib\n'), ((19164, 19185), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (19177, 19185), False, 'import os\n'), ((19195, 19214), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (19206, 19214), False, 'import os\n'), ((19994, 20019), 'funannotate.library.Fzip_inplace', 'lib.Fzip_inplace', (['x', 'cpus'], {}), '(x, cpus)\n', (20010, 20019), True, 'import funannotate.library as lib\n'), ((20362, 20383), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (20375, 20383), False, 'import os\n'), ((20393, 20412), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (20404, 20412), False, 'import os\n'), ((22312, 22362), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'SENormalLog'], {}), "(cmd, '.', lib.log, SENormalLog)\n", (22330, 22362), True, 'import funannotate.library as lib\n'), ((22385, 22436), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (22397, 22436), False, 'import os\n'), ((22606, 22655), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""left.norm.fq"""'], {}), "(tmpdir, 'normalize', 'left.norm.fq')\n", (22618, 22655), False, 'import os\n'), ((22677, 22727), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""right.norm.fq"""'], {}), "(tmpdir, 'normalize', 'right.norm.fq')\n", (22689, 22727), False, 'import os\n'), ((22736, 22786), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'PENormalLog'], {}), "(cmd, '.', lib.log, PENormalLog)\n", (22754, 22786), True, 'import funannotate.library as lib\n'), ((24257, 24318), 'os.path.join', 'os.path.join', (['PASA', '"""scripts"""', '"""pasa_asmbl_genes_to_GFF3.dbi"""'], {}), "(PASA, 'scripts', 'pasa_asmbl_genes_to_GFF3.dbi')\n", (24269, 24318), False, 'import os\n'), ((24461, 24498), 'funannotate.library.checkannotations', 'lib.checkannotations', (['pasaExistingGFF'], {}), '(pasaExistingGFF)\n', (24481, 24498), True, 'import funannotate.library as lib\n'), ((26171, 26192), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (26184, 26192), False, 'import os\n'), ((26202, 26221), 'os.makedirs', 'os.makedirs', (['folder'], {}), '(folder)\n', (26213, 26221), False, 'import os\n'), ((27119, 27159), 'shutil.copyfile', 'shutil.copyfile', (['configFile', 'alignConfig'], {}), '(configFile, alignConfig)\n', (27134, 27159), False, 'import shutil\n'), ((28862, 28888), 'funannotate.library.which_path', 'lib.which_path', (['"""cdbfasta"""'], {}), "('cdbfasta')\n", (28876, 28888), True, 'import funannotate.library as lib\n'), ((29016, 29052), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', '"""."""', 'lib.log'], {}), "(cmd, '.', lib.log)\n", (29033, 29052), True, 'import funannotate.library as lib\n'), ((31126, 31161), 'funannotate.library.checkannotations', 'lib.checkannotations', (['stringtie_gtf'], {}), '(stringtie_gtf)\n', (31146, 31161), True, 'import funannotate.library as lib\n'), ((31226, 31275), 'funannotate.library.runSubprocess6', 'lib.runSubprocess6', (['cmd', 'folder', 'lib.log', 'pasaLOG'], {}), '(cmd, folder, lib.log, pasaLOG)\n', (31244, 31275), True, 'import funannotate.library as lib\n'), ((31805, 31833), 'os.path.abspath', 'os.path.abspath', (['annotConfig'], {}), '(annotConfig)\n', (31820, 31833), False, 'import os\n'), ((31852, 31875), 'os.path.abspath', 'os.path.abspath', (['genome'], {}), '(genome)\n', (31867, 31875), False, 'import os\n'), ((31894, 31927), 'os.path.abspath', 'os.path.abspath', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (31909, 31927), False, 'import os\n'), ((32474, 32522), 'funannotate.library.log.error', 'lib.log.error', (['"""PASA failed, check log, exiting"""'], {}), "('PASA failed, check log, exiting')\n", (32487, 32522), True, 'import funannotate.library as lib\n'), ((32531, 32542), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (32539, 32542), False, 'import sys\n'), ((32663, 32691), 'os.path.abspath', 'os.path.abspath', (['annotConfig'], {}), '(annotConfig)\n', (32678, 32691), False, 'import os\n'), ((32710, 32733), 'os.path.abspath', 'os.path.abspath', (['genome'], {}), '(genome)\n', (32725, 32733), False, 'import os\n'), ((32752, 32785), 'os.path.abspath', 'os.path.abspath', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (32767, 32785), False, 'import os\n'), ((33397, 33445), 'funannotate.library.log.error', 'lib.log.error', (['"""PASA failed, check log, exiting"""'], {}), "('PASA failed, check log, exiting')\n", (33410, 33445), True, 'import funannotate.library as lib\n'), ((33454, 33465), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (33462, 33465), False, 'import sys\n'), ((35619, 35643), 'os.path.islink', 'os.path.islink', (['combined'], {}), '(combined)\n', (35633, 35643), False, 'import os\n'), ((35647, 35671), 'os.path.isfile', 'os.path.isfile', (['combined'], {}), '(combined)\n', (35661, 35671), False, 'import os\n'), ((36082, 36161), 'funannotate.library.log.info', 'lib.log.info', (['"""Processing long reads: converting to fasta and running SeqClean"""'], {}), "('Processing long reads: converting to fasta and running SeqClean')\n", (36094, 36161), True, 'import funannotate.library as lib\n'), ((38238, 38277), 'funannotate.library.runSubprocess', 'lib.runSubprocess', (['cmd', 'folder', 'lib.log'], {}), '(cmd, folder, lib.log)\n', (38255, 38277), True, 'import funannotate.library as lib\n'), ((40294, 40353), 'funannotate.library.log.info', 'lib.log.info', (['"""Aligning long reads to genome with minimap2"""'], {}), "('Aligning long reads to genome with minimap2')\n", (40306, 40353), True, 'import funannotate.library as lib\n'), ((41517, 41566), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity.vs.long-reads.bam"""'], {}), "(tmpdir, 'trinity.vs.long-reads.bam')\n", (41529, 41566), False, 'import os\n'), ((41590, 41645), 'os.path.join', 'os.path.join', (['tmpdir', '"""long-reads.trinity.unique.fasta"""'], {}), "(tmpdir, 'long-reads.trinity.unique.fasta')\n", (41602, 41645), False, 'import os\n'), ((41657, 41689), 'funannotate.library.checkannotations', 'lib.checkannotations', (['mappedLong'], {}), '(mappedLong)\n', (41677, 41689), True, 'import funannotate.library as lib\n'), ((42751, 42785), 'funannotate.library.checkannotations', 'lib.checkannotations', (['unmappedLong'], {}), '(unmappedLong)\n', (42771, 42785), True, 'import funannotate.library as lib\n'), ((43230, 43315), 'funannotate.library.minimap2Align', 'lib.minimap2Align', (['trinityCombinedClean', 'genome', 'cpus', 'max_intronlen', 'trinityBAM'], {}), '(trinityCombinedClean, genome, cpus, max_intronlen, trinityBAM\n )\n', (43247, 43315), True, 'import funannotate.library as lib\n'), ((43621, 43644), 'funannotate.library.checkannotations', 'lib.checkannotations', (['r'], {}), '(r)\n', (43641, 43644), True, 'import funannotate.library as lib\n'), ((43798, 43852), 'funannotate.library.mergeBAMs', 'lib.mergeBAMs', (['*foundResults'], {'cpus': 'cpus', 'output': 'allBAM'}), '(*foundResults, cpus=cpus, output=allBAM)\n', (43811, 43852), True, 'import funannotate.library as lib\n'), ((44773, 44837), 'os.path.join', 'os.path.join', (['PASA', '"""misc_utilities"""', '"""gff3_file_to_proteins.pl"""'], {}), "(PASA, 'misc_utilities', 'gff3_file_to_proteins.pl')\n", (44785, 44837), False, 'import os\n'), ((45067, 45100), 'os.path.join', 'os.path.join', (['folder', '"""bestModel"""'], {}), "(folder, 'bestModel')\n", (45079, 45100), False, 'import os\n'), ((45258, 45291), 'os.path.join', 'os.path.join', (['folder', '"""bestModel"""'], {}), "(folder, 'bestModel')\n", (45270, 45291), False, 'import os\n'), ((45299, 45331), 'os.path.join', 'os.path.join', (['folder', '"""kallisto"""'], {}), "(folder, 'kallisto')\n", (45311, 45331), False, 'import os\n'), ((47771, 47874), 'funannotate.library.log.info', 'lib.log.info', (['"""Parsing Kallisto results. Keeping all alt-splicing transcripts at each locus."""'], {}), "(\n 'Parsing Kallisto results. Keeping all alt-splicing transcripts at each locus.'\n )\n", (47783, 47874), True, 'import funannotate.library as lib\n'), ((52937, 52966), 'Bio.SeqIO.parse', 'SeqIO.parse', (['fastain', '"""fasta"""'], {}), "(fastain, 'fasta')\n", (52948, 52966), False, 'from Bio import SeqIO\n'), ((53660, 53688), 'Bio.SeqIO.parse', 'SeqIO.parse', (['genome', '"""fasta"""'], {}), "(genome, 'fasta')\n", (53671, 53688), False, 'from Bio import SeqIO\n'), ((58020, 58050), 'Bio.SeqIO.parse', 'SeqIO.parse', (['filein', '"""genbank"""'], {}), "(filein, 'genbank')\n", (58031, 58050), False, 'from Bio import SeqIO\n'), ((70402, 70419), 'funannotate.interlap.InterLap', 'InterLap', (['mrna[i]'], {}), '(mrna[i])\n', (70410, 70419), False, 'from funannotate.interlap import InterLap\n'), ((80773, 80798), 'os.path.isdir', 'os.path.isdir', (['args.input'], {}), '(args.input)\n', (80786, 80798), False, 'import os\n'), ((80900, 80955), 'funannotate.library.log.error', 'lib.log.error', (['"""No output folder specified, -o, --out."""'], {}), "('No output folder specified, -o, --out.')\n", (80913, 80955), True, 'import funannotate.library as lib\n'), ((80964, 80975), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (80972, 80975), False, 'import sys\n'), ((80987, 81010), 'os.path.isdir', 'os.path.isdir', (['args.out'], {}), '(args.out)\n', (81000, 81010), False, 'import os\n'), ((81020, 81041), 'os.makedirs', 'os.makedirs', (['args.out'], {}), '(args.out)\n', (81031, 81041), False, 'import os\n'), ((81662, 81687), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (81677, 81687), False, 'import os\n'), ((81880, 81899), 'os.remove', 'os.remove', (['log_name'], {}), '(log_name)\n', (81889, 81899), False, 'import os\n'), ((82748, 82793), 'os.path.join', 'os.path.join', (['PASA', '"""Launch_PASA_pipeline.pl"""'], {}), "(PASA, 'Launch_PASA_pipeline.pl')\n", (82760, 82793), False, 'import os\n'), ((82841, 82886), 'os.path.join', 'os.path.join', (['PASA', '"""Launch_PASA_pipeline.pl"""'], {}), "(PASA, 'Launch_PASA_pipeline.pl')\n", (82853, 82886), False, 'import os\n'), ((83862, 83899), 'os.path.join', 'os.path.join', (['PASA', '"""bin"""', '"""seqclean"""'], {}), "(PASA, 'bin', 'seqclean')\n", (83874, 83899), False, 'import os\n'), ((84122, 84167), 'os.path.join', 'os.path.join', (['parentdir', '"""config"""', '"""test.sbt"""'], {}), "(parentdir, 'config', 'test.sbt')\n", (84134, 84167), False, 'import os\n'), ((84176, 84286), 'funannotate.library.log.info', 'lib.log.info', (['"""No NCBI SBT file given, will use default, for NCBI submissions pass one here \'--sbt\'"""'], {}), '(\n "No NCBI SBT file given, will use default, for NCBI submissions pass one here \'--sbt\'"\n )\n', (84188, 84286), True, 'import funannotate.library as lib\n'), ((85186, 85211), 'os.path.isdir', 'os.path.isdir', (['args.input'], {}), '(args.input)\n', (85199, 85211), False, 'import os\n'), ((91411, 91430), 'funannotate.library.getGBKinfo', 'lib.getGBKinfo', (['GBK'], {}), '(GBK)\n', (91425, 91430), True, 'import funannotate.library as lib\n'), ((91452, 91531), 'funannotate.library.log.info', 'lib.log.info', (["('Reannotating %s, NCBI accession: %s' % (organism, WGS_accession))"], {}), "('Reannotating %s, NCBI accession: %s' % (organism, WGS_accession))\n", (91464, 91531), True, 'import funannotate.library as lib\n'), ((99248, 99298), 'funannotate.library.CheckFASTQandFix', 'lib.CheckFASTQandFix', (['trim_reads[0]', 'trim_reads[1]'], {}), '(trim_reads[0], trim_reads[1])\n', (99268, 99298), True, 'import funannotate.library as lib\n'), ((101879, 101914), 'os.path.abspath', 'os.path.abspath', (['args.pacbio_isoseq'], {}), '(args.pacbio_isoseq)\n', (101894, 101914), False, 'import os\n'), ((101962, 101997), 'os.path.abspath', 'os.path.abspath', (['args.nanopore_cdna'], {}), '(args.nanopore_cdna)\n', (101977, 101997), False, 'import os\n'), ((102045, 102080), 'os.path.abspath', 'os.path.abspath', (['args.nanopore_mrna'], {}), '(args.nanopore_mrna)\n', (102060, 102080), False, 'import os\n'), ((102300, 102371), 'funannotate.library.log.error', 'lib.log.error', (['"""No reads to generate transcriptome assemblies, exiting"""'], {}), "('No reads to generate transcriptome assemblies, exiting')\n", (102313, 102371), True, 'import funannotate.library as lib\n'), ((102380, 102391), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (102388, 102391), False, 'import sys\n'), ((102502, 102588), 'funannotate.library.log.error', 'lib.log.error', (['"""Trinity results detected, but no RNA-seq reads detected, exiting"""'], {}), "(\n 'Trinity results detected, but no RNA-seq reads detected, exiting')\n", (102515, 102588), True, 'import funannotate.library as lib\n'), ((102605, 102616), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (102613, 102616), False, 'import sys\n'), ((104164, 104210), 'os.path.join', 'os.path.join', (['tmpdir', '"""hisat2.coordSorted.bam"""'], {}), "(tmpdir, 'hisat2.coordSorted.bam')\n", (104176, 104210), False, 'import os\n'), ((106089, 106142), 'shutil.copyfile', 'shutil.copyfile', (['trinity_results', 'trinity_transcripts'], {}), '(trinity_results, trinity_transcripts)\n', (106104, 106142), False, 'import shutil\n'), ((106273, 106328), 'os.path.join', 'os.path.join', (['tmpdir', '"""funannotate_train.stringtie.gtf"""'], {}), "(tmpdir, 'funannotate_train.stringtie.gtf')\n", (106285, 106328), False, 'import os\n'), ((107124, 107165), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinity_transcripts'], {}), '(trinity_transcripts)\n', (107144, 107165), True, 'import funannotate.library as lib\n'), ((107435, 107463), 'funannotate.library.checkannotations', 'lib.checkannotations', (['allBAM'], {}), '(allBAM)\n', (107455, 107463), True, 'import funannotate.library as lib\n'), ((107680, 107712), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinityBAM'], {}), '(trinityBAM)\n', (107700, 107712), True, 'import funannotate.library as lib\n'), ((108121, 108149), 'funannotate.library.checkannotations', 'lib.checkannotations', (['allBAM'], {}), '(allBAM)\n', (108141, 108149), True, 'import funannotate.library as lib\n'), ((108159, 108222), 'funannotate.library.log.info', 'lib.log.info', (['"""Converting transcript alignments to GFF3 format"""'], {}), "('Converting transcript alignments to GFF3 format')\n", (108171, 108222), True, 'import funannotate.library as lib\n'), ((108231, 108260), 'funannotate.library.bam2gff3', 'lib.bam2gff3', (['allBAM', 'allGFF3'], {}), '(allBAM, allGFF3)\n', (108243, 108260), True, 'import funannotate.library as lib\n'), ((108310, 108342), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinityBAM'], {}), '(trinityBAM)\n', (108330, 108342), True, 'import funannotate.library as lib\n'), ((108352, 108423), 'funannotate.library.log.info', 'lib.log.info', (['"""Converting Trinity transcript alignments to GFF3 format"""'], {}), "('Converting Trinity transcript alignments to GFF3 format')\n", (108364, 108423), True, 'import funannotate.library as lib\n'), ((108432, 108469), 'funannotate.library.bam2gff3', 'lib.bam2gff3', (['trinityBAM', 'trinityGFF3'], {}), '(trinityBAM, trinityGFF3)\n', (108444, 108469), True, 'import funannotate.library as lib\n'), ((110902, 110981), 'funannotate.library.log.info', 'lib.log.info', (['"""You passed a --kallisto file; are you sure this is a good idea?"""'], {}), "('You passed a --kallisto file; are you sure this is a good idea?')\n", (110914, 110981), True, 'import funannotate.library as lib\n'), ((110990, 111039), 'shutil.copyfile', 'shutil.copyfile', (['args.kallisto', 'KallistoAbundance'], {}), '(args.kallisto, KallistoAbundance)\n', (111005, 111039), False, 'import shutil\n'), ((111213, 111248), 'funannotate.library.checkannotations', 'lib.checkannotations', (['longReadClean'], {}), '(longReadClean)\n', (111233, 111248), True, 'import funannotate.library as lib\n'), ((111295, 111368), 'funannotate.library.log.info', 'lib.log.info', (['"""Generating relative expression values to PASA transcripts"""'], {}), "('Generating relative expression values to PASA transcripts')\n", (111307, 111368), True, 'import funannotate.library as lib\n'), ((111408, 111446), 'os.path.join', 'os.path.join', (['tmpdir', '"""transcripts.fa"""'], {}), "(tmpdir, 'transcripts.fa')\n", (111420, 111446), False, 'import os\n'), ((111768, 111818), 'os.path.join', 'os.path.join', (['tmpdir', '"""long-reads_transcripts.bam"""'], {}), "(tmpdir, 'long-reads_transcripts.bam')\n", (111780, 111818), False, 'import os\n'), ((113537, 113558), 'shutil.rmtree', 'shutil.rmtree', (['gagdir'], {}), '(gagdir)\n', (113550, 113558), False, 'import shutil\n'), ((116610, 116671), 'os.path.join', 'os.path.join', (['parentdir', '"""aux_scripts"""', '"""tbl2asn_parallel.py"""'], {}), "(parentdir, 'aux_scripts', 'tbl2asn_parallel.py')\n", (116622, 116671), False, 'import os\n'), ((118235, 118269), 'os.path.join', 'os.path.join', (['gagdir', '"""genome.gbf"""'], {}), "(gagdir, 'genome.gbf')\n", (118247, 118269), False, 'import os\n'), ((118302, 118336), 'os.path.join', 'os.path.join', (['gagdir', '"""genome.tbl"""'], {}), "(gagdir, 'genome.tbl')\n", (118314, 118336), False, 'import os\n'), ((118369, 118403), 'os.path.join', 'os.path.join', (['gagdir', '"""genome.val"""'], {}), "(gagdir, 'genome.val')\n", (118381, 118403), False, 'import os\n'), ((118443, 118483), 'os.path.join', 'os.path.join', (['gagdir', '"""errorsummary.val"""'], {}), "(gagdir, 'errorsummary.val')\n", (118455, 118483), False, 'import os\n'), ((119813, 119949), 'funannotate.library.log.info', 'lib.log.info', (['("""Manually edit the tbl file %s, then run:\n\nfunannotate fix -i %s -t %s\n""" %\n (final_tbl, final_gbk, final_tbl))'], {}), '(\n """Manually edit the tbl file %s, then run:\n\nfunannotate fix -i %s -t %s\n"""\n % (final_tbl, final_gbk, final_tbl))\n', (119825, 119949), True, 'import funannotate.library as lib\n'), ((119968, 120082), 'funannotate.library.log.info', 'lib.log.info', (['"""After the problematic gene models are fixed, you can proceed with functional annotation."""'], {}), "(\n 'After the problematic gene models are fixed, you can proceed with functional annotation.'\n )\n", (119980, 120082), True, 'import funannotate.library as lib\n'), ((1566, 1583), 'funannotate.interlap.InterLap', 'InterLap', (['mrna[x]'], {}), '(mrna[x])\n', (1574, 1583), False, 'from funannotate.interlap import InterLap\n'), ((4241, 4268), 'Bio.SeqIO.parse', 'SeqIO.parse', (['gbk', '"""genbank"""'], {}), "(gbk, 'genbank')\n", (4252, 4268), False, 'from Bio import SeqIO\n'), ((21489, 21552), 'os.path.join', 'os.path.join', (['TRINITY', '"""util"""', '"""insilico_read_normalization.pl"""'], {}), "(TRINITY, 'util', 'insilico_read_normalization.pl')\n", (21501, 21552), False, 'import os\n'), ((21731, 21764), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""'], {}), "(tmpdir, 'normalize')\n", (21743, 21764), False, 'import os\n'), ((21873, 21936), 'os.path.join', 'os.path.join', (['TRINITY', '"""util"""', '"""insilico_read_normalization.pl"""'], {}), "(TRINITY, 'util', 'insilico_read_normalization.pl')\n", (21885, 21936), False, 'import os\n'), ((22115, 22148), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""'], {}), "(tmpdir, 'normalize')\n", (22127, 22148), False, 'import os\n'), ((26797, 26831), 'os.path.join', 'os.path.join', (['folder', 'DataBaseName'], {}), '(folder, DataBaseName)\n', (26809, 26831), False, 'import os\n'), ((28937, 28974), 'os.path.join', 'os.path.join', (['PASA', '"""bin"""', '"""cdbfasta"""'], {}), "(PASA, 'bin', 'cdbfasta')\n", (28949, 28974), False, 'import os\n'), ((30376, 30404), 'os.path.abspath', 'os.path.abspath', (['alignConfig'], {}), '(alignConfig)\n', (30391, 30404), False, 'import os\n'), ((30445, 30468), 'os.path.abspath', 'os.path.abspath', (['genome'], {}), '(genome)\n', (30460, 30468), False, 'import os\n'), ((30559, 30592), 'os.path.abspath', 'os.path.abspath', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (30574, 30592), False, 'import os\n'), ((30615, 30643), 'os.path.abspath', 'os.path.abspath', (['transcripts'], {}), '(transcripts)\n', (30630, 30643), False, 'import os\n'), ((32417, 32443), 'os.path.join', 'os.path.join', (['folder', 'file'], {}), '(folder, file)\n', (32429, 32443), False, 'import os\n'), ((33210, 33237), 'os.path.basename', 'os.path.basename', (['round1GFF'], {}), '(round1GFF)\n', (33226, 33237), False, 'import os\n'), ((33340, 33366), 'os.path.join', 'os.path.join', (['folder', 'file'], {}), '(folder, file)\n', (33352, 33366), False, 'import os\n'), ((35593, 35610), 'funannotate.library.SafeRemove', 'lib.SafeRemove', (['x'], {}), '(x)\n', (35607, 35610), True, 'import funannotate.library as lib\n'), ((35805, 35828), 'funannotate.library.checkannotations', 'lib.checkannotations', (['i'], {}), '(i)\n', (35825, 35828), True, 'import funannotate.library as lib\n'), ((36806, 36829), 'funannotate.library.checkannotations', 'lib.checkannotations', (['i'], {}), '(i)\n', (36826, 36829), True, 'import funannotate.library as lib\n'), ((37203, 37252), 'funannotate.library.catFiles', 'lib.catFiles', (['*validResults'], {'output': 'combinedClean'}), '(*validResults, output=combinedClean)\n', (37215, 37252), True, 'import funannotate.library as lib\n'), ((37265, 37310), 'funannotate.library.catFiles', 'lib.catFiles', (['*validOriginal'], {'output': 'combined'}), '(*validOriginal, output=combined)\n', (37277, 37310), True, 'import funannotate.library as lib\n'), ((37323, 37361), 'funannotate.library.catFiles', 'lib.catFiles', (['*validCln'], {'output': 'ClnOut'}), '(*validCln, output=ClnOut)\n', (37335, 37361), True, 'import funannotate.library as lib\n'), ((38134, 38171), 'os.path.join', 'os.path.join', (['PASA', '"""bin"""', '"""seqclean"""'], {}), "(PASA, 'bin', 'seqclean')\n", (38146, 38171), False, 'import os\n'), ((38188, 38211), 'os.path.basename', 'os.path.basename', (['input'], {}), '(input)\n', (38204, 38211), False, 'import os\n'), ((38336, 38359), 'os.path.join', 'os.path.join', (['folder', 'f'], {}), '(folder, f)\n', (38348, 38359), False, 'import os\n'), ((38792, 38817), 'Bio.SeqIO.FastaIO.SimpleFastaParser', 'SimpleFastaParser', (['infile'], {}), '(infile)\n', (38809, 38817), False, 'from Bio.SeqIO.FastaIO import SimpleFastaParser\n'), ((39299, 39324), 'Bio.SeqIO.FastaIO.SimpleFastaParser', 'SimpleFastaParser', (['infile'], {}), '(infile)\n', (39316, 39324), False, 'from Bio.SeqIO.FastaIO import SimpleFastaParser\n'), ((40413, 40484), 'funannotate.library.iso_seq_minimap2', 'lib.iso_seq_minimap2', (['longTuple[0]', 'genome', 'cpus', 'max_intronlen', 'isoBAM'], {}), '(longTuple[0], genome, cpus, max_intronlen, isoBAM)\n', (40433, 40484), True, 'import funannotate.library as lib\n'), ((40606, 40693), 'funannotate.library.nanopore_cDNA_minimap2', 'lib.nanopore_cDNA_minimap2', (['longTuple[1]', 'genome', 'cpus', 'max_intronlen', 'nano_cdnaBAM'], {}), '(longTuple[1], genome, cpus, max_intronlen,\n nano_cdnaBAM)\n', (40632, 40693), True, 'import funannotate.library as lib\n'), ((40823, 40910), 'funannotate.library.nanopore_mRNA_minimap2', 'lib.nanopore_mRNA_minimap2', (['longTuple[2]', 'genome', 'cpus', 'max_intronlen', 'nano_mrnaBAM'], {}), '(longTuple[2], genome, cpus, max_intronlen,\n nano_mrnaBAM)\n', (40849, 40910), True, 'import funannotate.library as lib\n'), ((41059, 41082), 'funannotate.library.checkannotations', 'lib.checkannotations', (['x'], {}), '(x)\n', (41079, 41082), True, 'import funannotate.library as lib\n'), ((41165, 41209), 'funannotate.library.catFiles', 'lib.catFiles', (['*mappedSeqs'], {'output': 'mappedLong'}), '(*mappedSeqs, output=mappedLong)\n', (41177, 41209), True, 'import funannotate.library as lib\n'), ((41222, 41245), 'funannotate.library.SafeRemove', 'lib.SafeRemove', (['isoSeqs'], {}), '(isoSeqs)\n', (41236, 41245), True, 'import funannotate.library as lib\n'), ((41258, 41287), 'funannotate.library.SafeRemove', 'lib.SafeRemove', (['nano_cdnaSeqs'], {}), '(nano_cdnaSeqs)\n', (41272, 41287), True, 'import funannotate.library as lib\n'), ((41300, 41329), 'funannotate.library.SafeRemove', 'lib.SafeRemove', (['nano_mrnaSeqs'], {}), '(nano_mrnaSeqs)\n', (41314, 41329), True, 'import funannotate.library as lib\n'), ((41703, 41775), 'funannotate.library.log.info', 'lib.log.info', (['"""Finding long-reads not represented in Trinity assemblies"""'], {}), "('Finding long-reads not represented in Trinity assemblies')\n", (41715, 41775), True, 'import funannotate.library as lib\n'), ((42710, 42739), 'funannotate.library.SafeRemove', 'lib.SafeRemove', (['crosscheckBAM'], {}), '(crosscheckBAM)\n', (42724, 42739), True, 'import funannotate.library as lib\n'), ((42817, 42865), 'os.path.join', 'os.path.join', (['tmpdir', '"""trinity.long-reads.fasta"""'], {}), "(tmpdir, 'trinity.long-reads.fasta')\n", (42829, 42865), False, 'import os\n'), ((42938, 43002), 'funannotate.library.catFiles', 'lib.catFiles', (['*[assembled, unmappedLong]'], {'output': 'trinityCombined'}), '(*[assembled, unmappedLong], output=trinityCombined)\n', (42950, 43002), True, 'import funannotate.library as lib\n'), ((43894, 43966), 'funannotate.library.log.error', 'lib.log.error', (['"""Alignment failed, BAM files empty. Please check logfile"""'], {}), "('Alignment failed, BAM files empty. Please check logfile')\n", (43907, 43966), True, 'import funannotate.library as lib\n'), ((43988, 43999), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (43996, 43999), False, 'import sys\n'), ((48128, 48213), 'funannotate.library.log.info', 'lib.log.info', (['"""Parsing Kallisto results. Keeping best transcript at each locus."""'], {}), "('Parsing Kallisto results. Keeping best transcript at each locus.'\n )\n", (48140, 48213), True, 'import funannotate.library as lib\n'), ((73004, 73039), 'itertools.product', 'itertools.product', (['query', 'reference'], {}), '(query, reference)\n', (73021, 73039), False, 'import itertools\n'), ((81062, 81099), 'os.path.join', 'os.path.join', (['args.out', '"""update_misc"""'], {}), "(args.out, 'update_misc')\n", (81074, 81099), False, 'import os\n'), ((81121, 81161), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""'], {}), "(args.out, 'update_results')\n", (81133, 81161), False, 'import os\n'), ((81183, 81217), 'os.path.join', 'os.path.join', (['args.out', '"""logfiles"""'], {}), "(args.out, 'logfiles')\n", (81195, 81217), False, 'import os\n'), ((81286, 81323), 'os.path.join', 'os.path.join', (['args.out', '"""update_misc"""'], {}), "(args.out, 'update_misc')\n", (81298, 81323), False, 'import os\n'), ((81325, 81359), 'os.path.join', 'os.path.join', (['args.out', '"""logfiles"""'], {}), "(args.out, 'logfiles')\n", (81337, 81359), False, 'import os\n'), ((81374, 81414), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""'], {}), "(args.out, 'update_results')\n", (81386, 81414), False, 'import os\n'), ((82941, 82997), 'os.path.join', 'os.path.join', (['PASA', '"""scripts"""', '"""Launch_PASA_pipeline.pl"""'], {}), "(PASA, 'scripts', 'Launch_PASA_pipeline.pl')\n", (82953, 82997), False, 'import os\n'), ((83038, 83094), 'os.path.join', 'os.path.join', (['PASA', '"""scripts"""', '"""Launch_PASA_pipeline.pl"""'], {}), "(PASA, 'scripts', 'Launch_PASA_pipeline.pl')\n", (83050, 83094), False, 'import os\n'), ((90971, 90982), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (90979, 90982), False, 'import sys\n'), ((90996, 91016), 'funannotate.library.checkRefSeq', 'lib.checkRefSeq', (['GBK'], {}), '(GBK)\n', (91011, 91016), True, 'import funannotate.library as lib\n'), ((91776, 91813), 'shutil.copyfile', 'shutil.copyfile', (['args.fasta', 'fastaout'], {}), '(args.fasta, fastaout)\n', (91791, 91813), False, 'import shutil\n'), ((92076, 92235), 'funannotate.library.log.error', 'lib.log.error', (['"""Error in input: pass either funannotate directory or GenBank file to -i,--input; or GFF3 to -g,--gff and genome FASTA to -f,--fasta."""'], {}), "(\n 'Error in input: pass either funannotate directory or GenBank file to -i,--input; or GFF3 to -g,--gff and genome FASTA to -f,--fasta.'\n )\n", (92089, 92235), True, 'import funannotate.library as lib\n'), ((92255, 92266), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (92263, 92266), False, 'import sys\n'), ((92400, 92425), 'funannotate.library.countGFFgenes', 'lib.countGFFgenes', (['gffout'], {}), '(gffout)\n', (92417, 92425), True, 'import funannotate.library as lib\n'), ((92427, 92453), 'funannotate.library.countGFFgenes', 'lib.countGFFgenes', (['trnaout'], {}), '(trnaout)\n', (92444, 92453), True, 'import funannotate.library as lib\n'), ((94373, 94409), 'os.path.join', 'os.path.join', (['tmpdir', '"""single.fq.gz"""'], {}), "(tmpdir, 'single.fq.gz')\n", (94385, 94409), False, 'import os\n'), ((96764, 96798), 'os.path.join', 'os.path.join', (['tmpdir', '"""left.fq.gz"""'], {}), "(tmpdir, 'left.fq.gz')\n", (96776, 96798), False, 'import os\n'), ((96821, 96856), 'os.path.join', 'os.path.join', (['tmpdir', '"""right.fq.gz"""'], {}), "(tmpdir, 'right.fq.gz')\n", (96833, 96856), False, 'import os\n'), ((97230, 97273), 'funannotate.library.log.info', 'lib.log.info', (['"""Trimmomatic will be skipped"""'], {}), "('Trimmomatic will be skipped')\n", (97242, 97273), True, 'import funannotate.library as lib\n'), ((99447, 99497), 'funannotate.library.log.info', 'lib.log.info', (['"""Read normalization will be skipped"""'], {}), "('Read normalization will be skipped')\n", (99459, 99497), True, 'import funannotate.library as lib\n'), ((102821, 102861), 'os.path.join', 'os.path.join', (['tmpdir', '"""long-reads.fasta"""'], {}), "(tmpdir, 'long-reads.fasta')\n", (102833, 102861), False, 'import os\n'), ((102890, 102936), 'os.path.join', 'os.path.join', (['tmpdir', '"""long-reads.fasta.clean"""'], {}), "(tmpdir, 'long-reads.fasta.clean')\n", (102902, 102936), False, 'import os\n'), ((102957, 102994), 'os.path.join', 'os.path.join', (['tmpdir', '"""iso-seq.fasta"""'], {}), "(tmpdir, 'iso-seq.fasta')\n", (102969, 102994), False, 'import os\n'), ((103018, 103057), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano-cdna.fasta"""'], {}), "(tmpdir, 'nano-cdna.fasta')\n", (103030, 103057), False, 'import os\n'), ((103081, 103120), 'os.path.join', 'os.path.join', (['tmpdir', '"""nano-mrna.fasta"""'], {}), "(tmpdir, 'nano-mrna.fasta')\n", (103093, 103120), False, 'import os\n'), ((104226, 104267), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinity_transcripts'], {}), '(trinity_transcripts)\n', (104246, 104267), True, 'import funannotate.library as lib\n'), ((106344, 106378), 'funannotate.library.checkannotations', 'lib.checkannotations', (['stringtieGTF'], {}), '(stringtieGTF)\n', (106364, 106378), True, 'import funannotate.library as lib\n'), ((107081, 107119), 'funannotate.library.checkannotations', 'lib.checkannotations', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (107101, 107119), True, 'import funannotate.library as lib\n'), ((108087, 108116), 'funannotate.library.checkannotations', 'lib.checkannotations', (['allGFF3'], {}), '(allGFF3)\n', (108107, 108116), True, 'import funannotate.library as lib\n'), ((108272, 108305), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinityGFF3'], {}), '(trinityGFF3)\n', (108292, 108305), True, 'import funannotate.library as lib\n'), ((108616, 108695), 'funannotate.library.log.info', 'lib.log.info', (['"""You passed a --pasa_gff file; are you sure this is a good idea?"""'], {}), "('You passed a --pasa_gff file; are you sure this is a good idea?')\n", (108628, 108695), True, 'import funannotate.library as lib\n'), ((108725, 108765), 'shutil.copyfile', 'shutil.copyfile', (['args.pasa_gff', 'PASA_gff'], {}), '(args.pasa_gff, PASA_gff)\n', (108740, 108765), False, 'import shutil\n'), ((108781, 108811), 'funannotate.library.checkannotations', 'lib.checkannotations', (['PASA_gff'], {}), '(PASA_gff)\n', (108801, 108811), True, 'import funannotate.library as lib\n'), ((108828, 108860), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinityBAM'], {}), '(trinityBAM)\n', (108848, 108860), True, 'import funannotate.library as lib\n'), ((109691, 109721), 'funannotate.library.checkannotations', 'lib.checkannotations', (['PASA_gff'], {}), '(PASA_gff)\n', (109711, 109721), True, 'import funannotate.library as lib\n'), ((109738, 109770), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinityBAM'], {}), '(trinityBAM)\n', (109758, 109770), True, 'import funannotate.library as lib\n'), ((110598, 110665), 'funannotate.library.log.info', 'lib.log.info', (["('Skipping PASA, found existing output: %s' % PASA_gff)"], {}), "('Skipping PASA, found existing output: %s' % PASA_gff)\n", (110610, 110665), True, 'import funannotate.library as lib\n'), ((111462, 111526), 'os.path.join', 'os.path.join', (['PASA', '"""misc_utilities"""', '"""gff3_file_to_proteins.pl"""'], {}), "(PASA, 'misc_utilities', 'gff3_file_to_proteins.pl')\n", (111474, 111526), False, 'import os\n'), ((111584, 111621), 'funannotate.library.checkannotations', 'lib.checkannotations', (['PASAtranscripts'], {}), '(PASAtranscripts)\n', (111604, 111621), True, 'import funannotate.library as lib\n'), ((111635, 111689), 'funannotate.library.runSubprocess2', 'lib.runSubprocess2', (['cmd', '"""."""', 'lib.log', 'PASAtranscripts'], {}), "(cmd, '.', lib.log, PASAtranscripts)\n", (111653, 111689), True, 'import funannotate.library as lib\n'), ((112117, 112149), 'funannotate.library.checkannotations', 'lib.checkannotations', (['minimapBAM'], {}), '(minimapBAM)\n', (112137, 112149), True, 'import funannotate.library as lib\n'), ((112261, 112329), 'subprocess.Popen', 'subprocess.Popen', (['minimap2_cmd'], {'stdout': 'subprocess.PIPE', 'stderr': 'FNULL'}), '(minimap2_cmd, stdout=subprocess.PIPE, stderr=FNULL)\n', (112277, 112329), False, 'import subprocess\n'), ((112347, 112437), 'subprocess.Popen', 'subprocess.Popen', (['samtools_cmd'], {'stdout': 'subprocess.PIPE', 'stderr': 'FNULL', 'stdin': 'p1.stdout'}), '(samtools_cmd, stdout=subprocess.PIPE, stderr=FNULL, stdin=\n p1.stdout)\n', (112363, 112437), False, 'import subprocess\n'), ((112507, 112546), 'funannotate.library.checkannotations', 'lib.checkannotations', (['KallistoAbundance'], {}), '(KallistoAbundance)\n', (112527, 112546), True, 'import funannotate.library as lib\n'), ((112560, 112613), 'funannotate.library.mapCount', 'lib.mapCount', (['minimapBAM', 'PASAdict', 'KallistoAbundance'], {}), '(minimapBAM, PASAdict, KallistoAbundance)\n', (112572, 112613), True, 'import funannotate.library as lib\n'), ((112639, 112678), 'funannotate.library.checkannotations', 'lib.checkannotations', (['KallistoAbundance'], {}), '(KallistoAbundance)\n', (112659, 112678), True, 'import funannotate.library as lib\n'), ((114027, 114072), 'os.path.join', 'os.path.join', (['tmpdir', '"""tbl2asn"""', '"""genome.tbl"""'], {}), "(tmpdir, 'tbl2asn', 'genome.tbl')\n", (114039, 114072), False, 'import os\n'), ((114092, 114141), 'os.path.join', 'os.path.join', (['tmpdir', '"""tbl2asn"""', '"""genome.tbl.bak"""'], {}), "(tmpdir, 'tbl2asn', 'genome.tbl.bak')\n", (114104, 114141), False, 'import os\n'), ((118950, 119011), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', '"""WGS_accession.txt"""'], {}), "(args.out, 'update_results', 'WGS_accession.txt')\n", (118962, 119011), False, 'import os\n'), ((18526, 18562), 'subprocess.call', 'subprocess.call', (['cmd'], {'stdout': 'outfile'}), '(cmd, stdout=outfile)\n', (18541, 18562), False, 'import subprocess\n'), ((18938, 18974), 'subprocess.call', 'subprocess.call', (['cmd'], {'stdout': 'outfile'}), '(cmd, stdout=outfile)\n', (18953, 18974), False, 'import subprocess\n'), ((19741, 19791), 'os.path.join', 'os.path.join', (['parentdir', '"""config"""', '"""TruSeq3-PE.fa"""'], {}), "(parentdir, 'config', 'TruSeq3-PE.fa')\n", (19753, 19791), False, 'import os\n'), ((20668, 20718), 'os.path.join', 'os.path.join', (['parentdir', '"""config"""', '"""TruSeq3-SE.fa"""'], {}), "(parentdir, 'config', 'TruSeq3-SE.fa')\n", (20680, 20718), False, 'import os\n'), ((23733, 23759), 'os.environ.get', 'os.environ.get', (['"""PASACONF"""'], {}), "('PASACONF')\n", (23747, 23759), False, 'import os\n'), ((27326, 27435), 'funannotate.library.log.error', 'lib.log.error', (['"""MySQL database not found or headers in PASA database, do not match those in FASTA."""'], {}), "(\n 'MySQL database not found or headers in PASA database, do not match those in FASTA.'\n )\n", (27339, 27435), True, 'import funannotate.library as lib\n'), ((28504, 28539), 'funannotate.library.checkannotations', 'lib.checkannotations', (['stringtie_gtf'], {}), '(stringtie_gtf)\n', (28524, 28539), True, 'import funannotate.library as lib\n'), ((28620, 28669), 'funannotate.library.runSubprocess6', 'lib.runSubprocess6', (['cmd', 'folder', 'lib.log', 'pasaLOG'], {}), '(cmd, folder, lib.log, pasaLOG)\n', (28638, 28669), True, 'import funannotate.library as lib\n'), ((31379, 31449), 'os.path.join', 'os.path.join', (['PASA', '"""pasa_conf"""', '"""pasa.annotationCompare.Template.txt"""'], {}), "(PASA, 'pasa_conf', 'pasa.annotationCompare.Template.txt')\n", (31391, 31449), False, 'import os\n'), ((32057, 32085), 'os.path.abspath', 'os.path.abspath', (['previousGFF'], {}), '(previousGFF)\n', (32072, 32085), False, 'import os\n'), ((32135, 32163), 'os.path.abspath', 'os.path.abspath', (['previousGFF'], {}), '(previousGFF)\n', (32150, 32163), False, 'import os\n'), ((32915, 32941), 'os.path.abspath', 'os.path.abspath', (['round1GFF'], {}), '(round1GFF)\n', (32930, 32941), False, 'import os\n'), ((32991, 33017), 'os.path.abspath', 'os.path.abspath', (['round1GFF'], {}), '(round1GFF)\n', (33006, 33017), False, 'import os\n'), ((34736, 34767), 'funannotate.library.Funzip', 'lib.Funzip', (['file', 'newfile', 'cpus'], {}), '(file, newfile, cpus)\n', (34746, 34767), True, 'import funannotate.library as lib\n'), ((36228, 36266), 'funannotate.library.checkannotations', 'lib.checkannotations', (["(PBiso + '.clean')"], {}), "(PBiso + '.clean')\n", (36248, 36266), True, 'import funannotate.library as lib\n'), ((36396, 36437), 'funannotate.library.checkannotations', 'lib.checkannotations', (["(nanocdna + '.clean')"], {}), "(nanocdna + '.clean')\n", (36416, 36437), True, 'import funannotate.library as lib\n'), ((36573, 36614), 'funannotate.library.checkannotations', 'lib.checkannotations', (["(nanomrna + '.clean')"], {}), "(nanomrna + '.clean')\n", (36593, 36614), True, 'import funannotate.library as lib\n'), ((37395, 37430), 'funannotate.library.checkannotations', 'lib.checkannotations', (['combinedClean'], {}), '(combinedClean)\n', (37415, 37430), True, 'import funannotate.library as lib\n'), ((37527, 37557), 'funannotate.library.checkannotations', 'lib.checkannotations', (['combined'], {}), '(combined)\n', (37547, 37557), True, 'import funannotate.library as lib\n'), ((37650, 37678), 'funannotate.library.checkannotations', 'lib.checkannotations', (['ClnOut'], {}), '(ClnOut)\n', (37670, 37678), True, 'import funannotate.library as lib\n'), ((38068, 38106), 'os.path.join', 'os.path.join', (['folder', "(input + '.clean')"], {}), "(folder, input + '.clean')\n", (38080, 38106), False, 'import os\n'), ((42095, 42130), 'funannotate.library.checkannotations', 'lib.checkannotations', (['crosscheckBAM'], {}), '(crosscheckBAM)\n', (42115, 42130), True, 'import funannotate.library as lib\n'), ((42250, 42318), 'subprocess.Popen', 'subprocess.Popen', (['minimap2_cmd'], {'stdout': 'subprocess.PIPE', 'stderr': 'FNULL'}), '(minimap2_cmd, stdout=subprocess.PIPE, stderr=FNULL)\n', (42266, 42318), False, 'import subprocess\n'), ((42340, 42430), 'subprocess.Popen', 'subprocess.Popen', (['samtools_cmd'], {'stdout': 'subprocess.PIPE', 'stderr': 'FNULL', 'stdin': 'p1.stdout'}), '(samtools_cmd, stdout=subprocess.PIPE, stderr=FNULL, stdin=\n p1.stdout)\n', (42356, 42430), False, 'import subprocess\n'), ((44029, 44061), 'os.path.abspath', 'os.path.abspath', (['foundResults[0]'], {}), '(foundResults[0])\n', (44044, 44061), False, 'import os\n'), ((44063, 44086), 'os.path.abspath', 'os.path.abspath', (['allBAM'], {}), '(allBAM)\n', (44078, 44086), False, 'import os\n'), ((46946, 46995), 'os.path.join', 'os.path.join', (['folder', '"""kallisto"""', '"""abundance.tsv"""'], {}), "(folder, 'kallisto', 'abundance.tsv')\n", (46958, 46995), False, 'import os\n'), ((56278, 56333), 'funannotate.library.getSeqRegions', 'lib.getSeqRegions', (['SeqRecords', "v['contig']", "v['CDS'][i]"], {}), "(SeqRecords, v['contig'], v['CDS'][i])\n", (56295, 56333), True, 'import funannotate.library as lib\n'), ((56381, 56440), 'funannotate.library.translate', 'lib.translate', (['cdsSeq', "v['strand']", "(v['codon_start'][i] - 1)"], {}), "(cdsSeq, v['strand'], v['codon_start'][i] - 1)\n", (56394, 56440), True, 'import funannotate.library as lib\n'), ((58384, 58425), 'funannotate.library.gb_feature_add2dict', 'lib.gb_feature_add2dict', (['f', 'record', 'Genes'], {}), '(f, record, Genes)\n', (58407, 58425), True, 'import funannotate.library as lib\n'), ((74191, 74211), 'numpy.subtract', 'np.subtract', (['exon', 'h'], {}), '(exon, h)\n', (74202, 74211), True, 'import numpy as np\n'), ((81458, 81474), 'os.path.isdir', 'os.path.isdir', (['d'], {}), '(d)\n', (81471, 81474), False, 'import os\n'), ((81492, 81506), 'os.makedirs', 'os.makedirs', (['d'], {}), '(d)\n', (81503, 81506), False, 'import os\n'), ((82423, 82593), 'funannotate.library.log.error', 'lib.log.error', (['"""$PASAHOME environmental variable not found, PASA is not properly configured. You can use the --PASAHOME argument to specifiy a path at runtime"""'], {}), "(\n '$PASAHOME environmental variable not found, PASA is not properly configured. You can use the --PASAHOME argument to specifiy a path at runtime'\n )\n", (82436, 82593), True, 'import funannotate.library as lib\n'), ((82613, 82624), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (82621, 82624), False, 'import sys\n'), ((85242, 85285), 'os.path.join', 'os.path.join', (['args.input', '"""predict_results"""'], {}), "(args.input, 'predict_results')\n", (85254, 85285), False, 'import os\n'), ((85885, 85921), 'os.path.join', 'os.path.join', (['args.input', '"""training"""'], {}), "(args.input, 'training')\n", (85897, 85921), False, 'import os\n'), ((85951, 85987), 'os.path.join', 'os.path.join', (['args.input', '"""training"""'], {}), "(args.input, 'training')\n", (85963, 85987), False, 'import os\n'), ((91030, 91136), 'funannotate.library.log.error', 'lib.log.error', (["('%s is a NCBI RefSeq genome, to reannotate please use original submission.' %\n GBK)"], {}), "(\n '%s is a NCBI RefSeq genome, to reannotate please use original submission.'\n % GBK)\n", (91043, 91136), True, 'import funannotate.library as lib\n'), ((91156, 91167), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (91164, 91167), False, 'import sys\n'), ((91648, 91714), 'funannotate.library.log.error', 'lib.log.error', (['"""Input error: please enter a name for -s,--species"""'], {}), "('Input error: please enter a name for -s,--species')\n", (91661, 91714), True, 'import funannotate.library as lib\n'), ((91752, 91763), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (91760, 91763), False, 'import sys\n'), ((93080, 93116), 'os.path.join', 'os.path.join', (['tmpdir', '"""single.fq.gz"""'], {}), "(tmpdir, 'single.fq.gz')\n", (93092, 93116), False, 'import os\n'), ((93452, 93491), 'os.path.join', 'os.path.join', (['tmpdir', "('single' + ending)"], {}), "(tmpdir, 'single' + ending)\n", (93464, 93491), False, 'import os\n'), ((95129, 95166), 'os.path.join', 'os.path.join', (['tmpdir', "('left' + ending)"], {}), "(tmpdir, 'left' + ending)\n", (95141, 95166), False, 'import os\n'), ((95191, 95229), 'os.path.join', 'os.path.join', (['tmpdir', "('right' + ending)"], {}), "(tmpdir, 'right' + ending)\n", (95203, 95229), False, 'import os\n'), ((98950, 98970), 'os.path.isfile', 'os.path.isfile', (['read'], {}), '(read)\n', (98964, 98970), False, 'import os\n'), ((98988, 99050), 'funannotate.library.log.error', 'lib.log.error', (["('Trimmomatic failed, %s does not exist.' % read)"], {}), "('Trimmomatic failed, %s does not exist.' % read)\n", (99001, 99050), True, 'import funannotate.library as lib\n'), ((99067, 99078), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (99075, 99078), False, 'import sys\n'), ((103781, 103813), 'funannotate.library.checkannotations', 'lib.checkannotations', (['longReadFA'], {}), '(longReadFA)\n', (103801, 103813), True, 'import funannotate.library as lib\n'), ((106395, 106417), 'funannotate.library.which', 'lib.which', (['"""stringtie"""'], {}), "('stringtie')\n", (106404, 106417), True, 'import funannotate.library as lib\n'), ((106422, 106452), 'funannotate.library.checkannotations', 'lib.checkannotations', (['shortBAM'], {}), '(shortBAM)\n', (106442, 106452), True, 'import funannotate.library as lib\n'), ((106470, 106555), 'funannotate.library.log.info', 'lib.log.info', (['"""StringTie installed, running StringTie on Hisat2 coordsorted BAM"""'], {}), "('StringTie installed, running StringTie on Hisat2 coordsorted BAM'\n )\n", (106482, 106555), True, 'import funannotate.library as lib\n'), ((106897, 106948), 'funannotate.library.runSubprocess8', 'lib.runSubprocess8', (['cmd', '"""."""', 'lib.log', 'stringtieGTF'], {}), "(cmd, '.', lib.log, stringtieGTF)\n", (106915, 106948), True, 'import funannotate.library as lib\n'), ((114243, 114295), 'os.path.join', 'os.path.join', (['args.out', '"""update_results"""', '"""ncbi.p2g"""'], {}), "(args.out, 'update_results', 'ncbi.p2g')\n", (114255, 114295), False, 'import os\n'), ((114548, 114593), 'os.path.join', 'os.path.join', (['tmpdir', '"""tbl2asn"""', '"""genome.tbl"""'], {}), "(tmpdir, 'tbl2asn', 'genome.tbl')\n", (114560, 114593), False, 'import os\n'), ((1747, 1770), 'numpy.subtract', 'np.subtract', (['coord', 'hit'], {}), '(coord, hit)\n', (1758, 1770), True, 'import numpy as np\n'), ((4399, 4440), 'funannotate.library.gb_feature_add2dict', 'lib.gb_feature_add2dict', (['f', 'record', 'genes'], {}), '(f, record, genes)\n', (4422, 4440), True, 'import funannotate.library as lib\n'), ((27696, 27724), 'os.path.abspath', 'os.path.abspath', (['alignConfig'], {}), '(alignConfig)\n', (27711, 27724), False, 'import os\n'), ((27750, 27773), 'os.path.abspath', 'os.path.abspath', (['genome'], {}), '(genome)\n', (27765, 27773), False, 'import os\n'), ((27880, 27913), 'os.path.abspath', 'os.path.abspath', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (27895, 27913), False, 'import os\n'), ((27949, 27977), 'os.path.abspath', 'os.path.abspath', (['transcripts'], {}), '(transcripts)\n', (27964, 27977), False, 'import os\n'), ((29180, 29246), 'os.path.join', 'os.path.join', (['PASA', '"""pasa_conf"""', '"""pasa.alignAssembly.Template.txt"""'], {}), "(PASA, 'pasa_conf', 'pasa.alignAssembly.Template.txt')\n", (29192, 29246), False, 'import os\n'), ((34949, 34974), 'Bio.SeqIO.FastaIO.SimpleFastaParser', 'SimpleFastaParser', (['infile'], {}), '(infile)\n', (34966, 34974), False, 'from Bio.SeqIO.FastaIO import SimpleFastaParser\n'), ((37459, 37491), 'os.path.abspath', 'os.path.abspath', (['validResults[0]'], {}), '(validResults[0])\n', (37474, 37491), False, 'import os\n'), ((37586, 37619), 'os.path.abspath', 'os.path.abspath', (['validOriginal[0]'], {}), '(validOriginal[0])\n', (37601, 37619), False, 'import os\n'), ((37707, 37735), 'os.path.abspath', 'os.path.abspath', (['validCln[0]'], {}), '(validCln[0])\n', (37722, 37735), False, 'import os\n'), ((38434, 38457), 'os.path.join', 'os.path.join', (['folder', 'f'], {}), '(folder, f)\n', (38446, 38457), False, 'import os\n'), ((42667, 42695), 'funannotate.library.countfasta', 'lib.countfasta', (['unmappedLong'], {}), '(unmappedLong)\n', (42681, 42695), True, 'import funannotate.library as lib\n'), ((58170, 58190), 'funannotate.library.getID', 'lib.getID', (['f', 'f.type'], {}), '(f, f.type)\n', (58179, 58190), True, 'import funannotate.library as lib\n'), ((70926, 70953), 'numpy.subtract', 'np.subtract', (['cds[i][0]', 'hit'], {}), '(cds[i][0], hit)\n', (70937, 70953), True, 'import numpy as np\n'), ((71408, 71436), 'numpy.subtract', 'np.subtract', (['cds[i][-1]', 'hit'], {}), '(cds[i][-1], hit)\n', (71419, 71436), True, 'import numpy as np\n'), ((72011, 72038), 'numpy.subtract', 'np.subtract', (['cds[i][0]', 'hit'], {}), '(cds[i][0], hit)\n', (72022, 72038), True, 'import numpy as np\n'), ((72493, 72521), 'numpy.subtract', 'np.subtract', (['cds[i][-1]', 'hit'], {}), '(cds[i][-1], hit)\n', (72504, 72521), True, 'import numpy as np\n'), ((85327, 85370), 'os.path.join', 'os.path.join', (['args.input', '"""predict_results"""'], {}), "(args.input, 'predict_results')\n", (85339, 85370), False, 'import os\n'), ((86028, 86064), 'os.path.join', 'os.path.join', (['inputDir', '"""left.fq.gz"""'], {}), "(inputDir, 'left.fq.gz')\n", (86040, 86064), False, 'import os\n'), ((86097, 86133), 'os.path.join', 'os.path.join', (['inputDir', '"""left.fq.gz"""'], {}), "(inputDir, 'left.fq.gz')\n", (86109, 86133), False, 'import os\n'), ((86174, 86211), 'os.path.join', 'os.path.join', (['inputDir', '"""right.fq.gz"""'], {}), "(inputDir, 'right.fq.gz')\n", (86186, 86211), False, 'import os\n'), ((86244, 86281), 'os.path.join', 'os.path.join', (['inputDir', '"""right.fq.gz"""'], {}), "(inputDir, 'right.fq.gz')\n", (86256, 86281), False, 'import os\n'), ((86322, 86360), 'os.path.join', 'os.path.join', (['inputDir', '"""single.fq.gz"""'], {}), "(inputDir, 'single.fq.gz')\n", (86334, 86360), False, 'import os\n'), ((86393, 86431), 'os.path.join', 'os.path.join', (['inputDir', '"""single.fq.gz"""'], {}), "(inputDir, 'single.fq.gz')\n", (86405, 86431), False, 'import os\n'), ((86472, 86534), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_left.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_left.fastq.gz')\n", (86484, 86534), False, 'import os\n'), ((86569, 86631), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_left.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_left.fastq.gz')\n", (86581, 86631), False, 'import os\n'), ((86697, 86760), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_right.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_right.fastq.gz')\n", (86709, 86760), False, 'import os\n'), ((86796, 86859), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_right.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_right.fastq.gz')\n", (86808, 86859), False, 'import os\n'), ((86925, 86989), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_single.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_single.fastq.gz')\n", (86937, 86989), False, 'import os\n'), ((87026, 87090), 'os.path.join', 'os.path.join', (['inputDir', '"""trimmomatic"""', '"""trimmed_single.fastq.gz"""'], {}), "(inputDir, 'trimmomatic', 'trimmed_single.fastq.gz')\n", (87038, 87090), False, 'import os\n'), ((87156, 87207), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""left.norm.fq"""'], {}), "(inputDir, 'normalize', 'left.norm.fq')\n", (87168, 87207), False, 'import os\n'), ((87242, 87293), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""left.norm.fq"""'], {}), "(inputDir, 'normalize', 'left.norm.fq')\n", (87254, 87293), False, 'import os\n'), ((87359, 87411), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""right.norm.fq"""'], {}), "(inputDir, 'normalize', 'right.norm.fq')\n", (87371, 87411), False, 'import os\n'), ((87447, 87499), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""right.norm.fq"""'], {}), "(inputDir, 'normalize', 'right.norm.fq')\n", (87459, 87499), False, 'import os\n'), ((87565, 87618), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(inputDir, 'normalize', 'single.norm.fq')\n", (87577, 87618), False, 'import os\n'), ((87655, 87708), 'os.path.join', 'os.path.join', (['inputDir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(inputDir, 'normalize', 'single.norm.fq')\n", (87667, 87708), False, 'import os\n'), ((87774, 87815), 'os.path.join', 'os.path.join', (['inputDir', '"""nano-mrna.fasta"""'], {}), "(inputDir, 'nano-mrna.fasta')\n", (87786, 87815), False, 'import os\n'), ((87849, 87890), 'os.path.join', 'os.path.join', (['inputDir', '"""nano-mrna.fasta"""'], {}), "(inputDir, 'nano-mrna.fasta')\n", (87861, 87890), False, 'import os\n'), ((87931, 87972), 'os.path.join', 'os.path.join', (['inputDir', '"""nano-cdna.fasta"""'], {}), "(inputDir, 'nano-cdna.fasta')\n", (87943, 87972), False, 'import os\n'), ((88006, 88047), 'os.path.join', 'os.path.join', (['inputDir', '"""nano-cdna.fasta"""'], {}), "(inputDir, 'nano-cdna.fasta')\n", (88018, 88047), False, 'import os\n'), ((88088, 88127), 'os.path.join', 'os.path.join', (['inputDir', '"""iso-seq.fasta"""'], {}), "(inputDir, 'iso-seq.fasta')\n", (88100, 88127), False, 'import os\n'), ((88158, 88197), 'os.path.join', 'os.path.join', (['inputDir', '"""iso-seq.fasta"""'], {}), "(inputDir, 'iso-seq.fasta')\n", (88170, 88197), False, 'import os\n'), ((88624, 88681), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.stringtie.gtf"""'], {}), "(inputDir, 'funannotate_train.stringtie.gtf')\n", (88636, 88681), False, 'import os\n'), ((88719, 88776), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.stringtie.gtf"""'], {}), "(inputDir, 'funannotate_train.stringtie.gtf')\n", (88731, 88776), False, 'import os\n'), ((88842, 88896), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_long-reads.fasta"""'], {}), "(inputDir, 'funannotate_long-reads.fasta')\n", (88854, 88896), False, 'import os\n'), ((88935, 88989), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_long-reads.fasta"""'], {}), "(inputDir, 'funannotate_long-reads.fasta')\n", (88947, 88989), False, 'import os\n'), ((89055, 89115), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.trinity-GG.fasta"""'], {}), "(inputDir, 'funannotate_train.trinity-GG.fasta')\n", (89067, 89115), False, 'import os\n'), ((89156, 89216), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.trinity-GG.fasta"""'], {}), "(inputDir, 'funannotate_train.trinity-GG.fasta')\n", (89168, 89216), False, 'import os\n'), ((89282, 89341), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.coordSorted.bam"""'], {}), "(inputDir, 'funannotate_train.coordSorted.bam')\n", (89294, 89341), False, 'import os\n'), ((89375, 89434), 'os.path.join', 'os.path.join', (['inputDir', '"""funannotate_train.coordSorted.bam"""'], {}), "(inputDir, 'funannotate_train.coordSorted.bam')\n", (89387, 89434), False, 'import os\n'), ((93552, 93629), 'funannotate.library.log.info', 'lib.log.info', (['"""Multiple inputs for --single detected, concatenating SE reads"""'], {}), "('Multiple inputs for --single detected, concatenating SE reads')\n", (93564, 93629), True, 'import funannotate.library as lib\n'), ((93675, 93718), 'funannotate.library.concatenateReads', 'lib.concatenateReads', (['single_reads', 's_reads'], {}), '(single_reads, s_reads)\n', (93695, 93718), True, 'import funannotate.library as lib\n'), ((93851, 93887), 'funannotate.library.Fzip_inplace', 'lib.Fzip_inplace', (['s_reads', 'args.cpus'], {}), '(s_reads, args.cpus)\n', (93867, 93887), True, 'import funannotate.library as lib\n'), ((94447, 94481), 'os.path.join', 'os.path.join', (['tmpdir', '"""left.fq.gz"""'], {}), "(tmpdir, 'left.fq.gz')\n", (94459, 94481), False, 'import os\n'), ((94511, 94546), 'os.path.join', 'os.path.join', (['tmpdir', '"""right.fq.gz"""'], {}), "(tmpdir, 'right.fq.gz')\n", (94523, 94546), False, 'import os\n'), ((95288, 95380), 'funannotate.library.log.info', 'lib.log.info', (['"""Multiple inputs for --left and --right detected, concatenating PE reads"""'], {}), "(\n 'Multiple inputs for --left and --right detected, concatenating PE reads')\n", (95300, 95380), True, 'import funannotate.library as lib\n'), ((95421, 95462), 'funannotate.library.concatenateReads', 'lib.concatenateReads', (['left_reads', 'l_reads'], {}), '(left_reads, l_reads)\n', (95441, 95462), True, 'import funannotate.library as lib\n'), ((95483, 95525), 'funannotate.library.concatenateReads', 'lib.concatenateReads', (['right_reads', 'r_reads'], {}), '(right_reads, r_reads)\n', (95503, 95525), True, 'import funannotate.library as lib\n'), ((95701, 95737), 'funannotate.library.Fzip_inplace', 'lib.Fzip_inplace', (['l_reads', 'args.cpus'], {}), '(l_reads, args.cpus)\n', (95717, 95737), True, 'import funannotate.library as lib\n'), ((95846, 95882), 'funannotate.library.Fzip_inplace', 'lib.Fzip_inplace', (['r_reads', 'args.cpus'], {}), '(r_reads, args.cpus)\n', (95862, 95882), True, 'import funannotate.library as lib\n'), ((97925, 97985), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_left.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_left.fastq.gz')\n", (97937, 97985), False, 'import os\n'), ((97987, 98048), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_right.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_right.fastq.gz')\n", (97999, 98048), False, 'import os\n'), ((98431, 98493), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_single.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_single.fastq.gz')\n", (98443, 98493), False, 'import os\n'), ((103199, 103231), 'funannotate.library.checkannotations', 'lib.checkannotations', (['longReadFA'], {}), '(longReadFA)\n', (103219, 103231), True, 'import funannotate.library as lib\n'), ((104440, 104469), 'os.path.abspath', 'os.path.abspath', (['args.trinity'], {}), '(args.trinity)\n', (104455, 104469), False, 'import os\n'), ((105594, 105629), 'funannotate.library.checkannotations', 'lib.checkannotations', (['longReadClean'], {}), '(longReadClean)\n', (105614, 105629), True, 'import funannotate.library as lib\n'), ((105742, 105762), 'subprocess.call', 'subprocess.call', (['cmd'], {}), '(cmd)\n', (105757, 105762), False, 'import subprocess\n'), ((108935, 108963), 'os.path.abspath', 'os.path.abspath', (['trinityGFF3'], {}), '(trinityGFF3)\n', (108950, 108963), False, 'import os\n'), ((109298, 109325), 'os.path.abspath', 'os.path.abspath', (['longReadFA'], {}), '(longReadFA)\n', (109313, 109325), False, 'import os\n'), ((109327, 109357), 'os.path.abspath', 'os.path.abspath', (['longReadClean'], {}), '(longReadClean)\n', (109342, 109357), False, 'import os\n'), ((109383, 109407), 'os.path.abspath', 'os.path.abspath', (['allGFF3'], {}), '(allGFF3)\n', (109398, 109407), False, 'import os\n'), ((109845, 109873), 'os.path.abspath', 'os.path.abspath', (['trinityGFF3'], {}), '(trinityGFF3)\n', (109860, 109873), False, 'import os\n'), ((110206, 110233), 'os.path.abspath', 'os.path.abspath', (['longReadFA'], {}), '(longReadFA)\n', (110221, 110233), False, 'import os\n'), ((110235, 110265), 'os.path.abspath', 'os.path.abspath', (['longReadClean'], {}), '(longReadClean)\n', (110250, 110265), False, 'import os\n'), ((110291, 110315), 'os.path.abspath', 'os.path.abspath', (['allGFF3'], {}), '(allGFF3)\n', (110306, 110315), False, 'import os\n'), ((114634, 114683), 'os.path.join', 'os.path.join', (['tmpdir', '"""tbl2asn"""', '"""genome.tbl.bak"""'], {}), "(tmpdir, 'tbl2asn', 'genome.tbl.bak')\n", (114646, 114683), False, 'import os\n'), ((30293, 30325), 'funannotate.library.countfasta', 'lib.countfasta', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (30307, 30325), True, 'import funannotate.library as lib\n'), ((35321, 35349), 'Bio.SeqIO.QualityIO.FastqGeneralIterator', 'FastqGeneralIterator', (['infile'], {}), '(infile)\n', (35341, 35349), False, 'from Bio.SeqIO.QualityIO import FastqGeneralIterator\n'), ((83427, 83623), 'funannotate.library.log.error', 'lib.log.error', (['"""$TRINITYHOME nor $TRINITY_HOME environmental variable not found, TRINITY is not properly configured. You can use the --TRINITYHOME argument to specify a path at runtime."""'], {}), "(\n '$TRINITYHOME nor $TRINITY_HOME environmental variable not found, TRINITY is not properly configured. You can use the --TRINITYHOME argument to specify a path at runtime.'\n )\n", (83440, 83623), True, 'import funannotate.library as lib\n'), ((83651, 83662), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (83659, 83662), False, 'import sys\n'), ((85449, 85498), 'os.path.join', 'os.path.join', (['args.input', '"""predict_results"""', 'file'], {}), "(args.input, 'predict_results', file)\n", (85461, 85498), False, 'import os\n'), ((85592, 85641), 'os.path.join', 'os.path.join', (['args.input', '"""predict_results"""', 'file'], {}), "(args.input, 'predict_results', file)\n", (85604, 85641), False, 'import os\n'), ((89587, 89638), 'os.path.join', 'os.path.join', (['inputDir', '"""pasa"""', '"""alignAssembly.txt"""'], {}), "(inputDir, 'pasa', 'alignAssembly.txt')\n", (89599, 89638), False, 'import os\n'), ((89678, 89729), 'os.path.join', 'os.path.join', (['inputDir', '"""pasa"""', '"""alignAssembly.txt"""'], {}), "(inputDir, 'pasa', 'alignAssembly.txt')\n", (89690, 89729), False, 'import os\n'), ((93259, 93277), 'os.path.abspath', 'os.path.abspath', (['y'], {}), '(y)\n', (93274, 93277), False, 'import os\n'), ((93976, 94012), 'os.path.join', 'os.path.join', (['tmpdir', '"""single.fq.gz"""'], {}), "(tmpdir, 'single.fq.gz')\n", (93988, 94012), False, 'import os\n'), ((94696, 94714), 'os.path.abspath', 'os.path.abspath', (['i'], {}), '(i)\n', (94711, 94714), False, 'import os\n'), ((94825, 94843), 'os.path.abspath', 'os.path.abspath', (['x'], {}), '(x)\n', (94840, 94843), False, 'import os\n'), ((95971, 96005), 'os.path.join', 'os.path.join', (['tmpdir', '"""left.fq.gz"""'], {}), "(tmpdir, 'left.fq.gz')\n", (95983, 96005), False, 'import os\n'), ((96370, 96405), 'os.path.join', 'os.path.join', (['tmpdir', '"""right.fq.gz"""'], {}), "(tmpdir, 'right.fq.gz')\n", (96382, 96405), False, 'import os\n'), ((97473, 97533), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_left.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_left.fastq.gz')\n", (97485, 97533), False, 'import os\n'), ((97557, 97618), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_right.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_right.fastq.gz')\n", (97569, 97618), False, 'import os\n'), ((98104, 98166), 'os.path.join', 'os.path.join', (['tmpdir', '"""trimmomatic"""', '"""trimmed_single.fastq.gz"""'], {}), "(tmpdir, 'trimmomatic', 'trimmed_single.fastq.gz')\n", (98116, 98166), False, 'import os\n'), ((100508, 100557), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""left.norm.fq"""'], {}), "(tmpdir, 'normalize', 'left.norm.fq')\n", (100520, 100557), False, 'import os\n'), ((100559, 100609), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""right.norm.fq"""'], {}), "(tmpdir, 'normalize', 'right.norm.fq')\n", (100571, 100609), False, 'import os\n'), ((100673, 100724), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (100685, 100724), False, 'import os\n'), ((100765, 100816), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (100777, 100816), False, 'import os\n'), ((101419, 101470), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (101431, 101470), False, 'import os\n'), ((101511, 101562), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (101523, 101562), False, 'import os\n'), ((103322, 103349), 'os.path.abspath', 'os.path.abspath', (['longReadFA'], {}), '(longReadFA)\n', (103337, 103349), False, 'import os\n'), ((103376, 103406), 'os.path.abspath', 'os.path.abspath', (['longReadClean'], {}), '(longReadClean)\n', (103391, 103406), False, 'import os\n'), ((103552, 103575), 'funannotate.library.checkannotations', 'lib.checkannotations', (['x'], {}), '(x)\n', (103572, 103575), True, 'import funannotate.library as lib\n'), ((104782, 104834), 'os.path.join', 'os.path.join', (['parentdir', '"""aux_scripts"""', '"""trinity.py"""'], {}), "(parentdir, 'aux_scripts', 'trinity.py')\n", (104794, 104834), False, 'import os\n'), ((105212, 105273), 'os.path.join', 'os.path.join', (['args.out', '"""logfiles"""', '"""funannotate-trinity.log"""'], {}), "(args.out, 'logfiles', 'funannotate-trinity.log')\n", (105224, 105273), False, 'import os\n'), ((105790, 105831), 'funannotate.library.checkannotations', 'lib.checkannotations', (['trinity_transcripts'], {}), '(trinity_transcripts)\n', (105810, 105831), True, 'import funannotate.library as lib\n'), ((105857, 105911), 'funannotate.library.log.info', 'lib.log.info', (['"""ERROR: Trinity de novo assembly failed"""'], {}), "('ERROR: Trinity de novo assembly failed')\n", (105869, 105911), True, 'import funannotate.library as lib\n'), ((105936, 105947), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (105944, 105947), False, 'import sys\n'), ((38915, 38932), 'funannotate.library.softwrap', 'lib.softwrap', (['seq'], {}), '(seq)\n', (38927, 38932), True, 'import funannotate.library as lib\n'), ((39422, 39439), 'funannotate.library.softwrap', 'lib.softwrap', (['seq'], {}), '(seq)\n', (39434, 39439), True, 'import funannotate.library as lib\n'), ((94054, 94077), 'os.path.abspath', 'os.path.abspath', (['tmpdir'], {}), '(tmpdir)\n', (94069, 94077), False, 'import os\n'), ((94098, 94122), 'os.path.abspath', 'os.path.abspath', (['s_reads'], {}), '(s_reads)\n', (94113, 94122), False, 'import os\n'), ((94164, 94200), 'os.path.join', 'os.path.join', (['tmpdir', '"""single.fq.gz"""'], {}), "(tmpdir, 'single.fq.gz')\n", (94176, 94200), False, 'import os\n'), ((94237, 94262), 'os.path.realpath', 'os.path.realpath', (['s_reads'], {}), '(s_reads)\n', (94253, 94262), False, 'import os\n'), ((94299, 94335), 'os.path.join', 'os.path.join', (['tmpdir', '"""single.fq.gz"""'], {}), "(tmpdir, 'single.fq.gz')\n", (94311, 94335), False, 'import os\n'), ((96047, 96070), 'os.path.abspath', 'os.path.abspath', (['tmpdir'], {}), '(tmpdir)\n', (96062, 96070), False, 'import os\n'), ((96091, 96115), 'os.path.abspath', 'os.path.abspath', (['l_reads'], {}), '(l_reads)\n', (96106, 96115), False, 'import os\n'), ((96157, 96191), 'os.path.join', 'os.path.join', (['tmpdir', '"""left.fq.gz"""'], {}), "(tmpdir, 'left.fq.gz')\n", (96169, 96191), False, 'import os\n'), ((96228, 96253), 'os.path.realpath', 'os.path.realpath', (['l_reads'], {}), '(l_reads)\n', (96244, 96253), False, 'import os\n'), ((96290, 96324), 'os.path.join', 'os.path.join', (['tmpdir', '"""left.fq.gz"""'], {}), "(tmpdir, 'left.fq.gz')\n", (96302, 96324), False, 'import os\n'), ((96447, 96470), 'os.path.abspath', 'os.path.abspath', (['tmpdir'], {}), '(tmpdir)\n', (96462, 96470), False, 'import os\n'), ((96491, 96515), 'os.path.abspath', 'os.path.abspath', (['r_reads'], {}), '(r_reads)\n', (96506, 96515), False, 'import os\n'), ((96557, 96592), 'os.path.join', 'os.path.join', (['tmpdir', '"""right.fq.gz"""'], {}), "(tmpdir, 'right.fq.gz')\n", (96569, 96592), False, 'import os\n'), ((96629, 96654), 'os.path.realpath', 'os.path.realpath', (['r_reads'], {}), '(r_reads)\n', (96645, 96654), False, 'import os\n'), ((96691, 96726), 'os.path.join', 'os.path.join', (['tmpdir', '"""right.fq.gz"""'], {}), "(tmpdir, 'right.fq.gz')\n", (96703, 96726), False, 'import os\n'), ((99976, 100025), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""left.norm.fq"""'], {}), "(tmpdir, 'normalize', 'left.norm.fq')\n", (99988, 100025), False, 'import os\n'), ((100049, 100099), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""right.norm.fq"""'], {}), "(tmpdir, 'normalize', 'right.norm.fq')\n", (100061, 100099), False, 'import os\n'), ((100912, 100963), 'os.path.join', 'os.path.join', (['tmpdir', '"""normalize"""', '"""single.norm.fq"""'], {}), "(tmpdir, 'normalize', 'single.norm.fq')\n", (100924, 100963), False, 'import os\n'), ((27605, 27637), 'funannotate.library.countfasta', 'lib.countfasta', (['cleanTranscripts'], {}), '(cleanTranscripts)\n', (27619, 27637), True, 'import funannotate.library as lib\n'), ((35143, 35160), 'funannotate.library.softwrap', 'lib.softwrap', (['seq'], {}), '(seq)\n', (35155, 35160), True, 'import funannotate.library as lib\n'), ((35518, 35535), 'funannotate.library.softwrap', 'lib.softwrap', (['seq'], {}), '(seq)\n', (35530, 35535), True, 'import funannotate.library as lib\n')] |
from ctapipe.utils.rgbtohex import intensity_to_rgb, intensity_to_hex
import numpy as np
def test_rgb():
input_ = np.array([4])
min_ = 0
max_ = 10
output = intensity_to_rgb(input_, min_, max_)
assert (output == np.array([41, 120, 142, 255])).all()
def test_hex():
input_ = np.array([4])
min_ = 0
max_ = 10
output = intensity_to_hex(input_, min_, max_)
assert (output == np.array(["#29788eff"])).all()
def test_rgb_nan():
output = intensity_to_rgb(np.array([np.nan, 2]), 0, 3)
assert (output[0] == np.array([0, 0, 0, 0])).all()
def test_hex_nan():
output = intensity_to_hex(np.array([np.nan, 2]), 0, 3)
assert output[0] == "#00000000"
| [
"ctapipe.utils.rgbtohex.intensity_to_rgb",
"numpy.array",
"ctapipe.utils.rgbtohex.intensity_to_hex"
] | [((120, 133), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (128, 133), True, 'import numpy as np\n'), ((174, 210), 'ctapipe.utils.rgbtohex.intensity_to_rgb', 'intensity_to_rgb', (['input_', 'min_', 'max_'], {}), '(input_, min_, max_)\n', (190, 210), False, 'from ctapipe.utils.rgbtohex import intensity_to_rgb, intensity_to_hex\n'), ((302, 315), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (310, 315), True, 'import numpy as np\n'), ((356, 392), 'ctapipe.utils.rgbtohex.intensity_to_hex', 'intensity_to_hex', (['input_', 'min_', 'max_'], {}), '(input_, min_, max_)\n', (372, 392), False, 'from ctapipe.utils.rgbtohex import intensity_to_rgb, intensity_to_hex\n'), ((499, 520), 'numpy.array', 'np.array', (['[np.nan, 2]'], {}), '([np.nan, 2])\n', (507, 520), True, 'import numpy as np\n'), ((635, 656), 'numpy.array', 'np.array', (['[np.nan, 2]'], {}), '([np.nan, 2])\n', (643, 656), True, 'import numpy as np\n'), ((234, 263), 'numpy.array', 'np.array', (['[41, 120, 142, 255]'], {}), '([41, 120, 142, 255])\n', (242, 263), True, 'import numpy as np\n'), ((416, 439), 'numpy.array', 'np.array', (["['#29788eff']"], {}), "(['#29788eff'])\n", (424, 439), True, 'import numpy as np\n'), ((553, 575), 'numpy.array', 'np.array', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (561, 575), True, 'import numpy as np\n')] |
# Copyright 2022 DeepMind Technologies Limited. 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.
"""K-FAC related utility classes and functions."""
import abc
import dataclasses
import functools
import numbers
import operator
from typing import Any, Callable, Iterable, Iterator, Optional, Sequence, Tuple, Type, TypeVar, Union
import chex
import jax
from jax import core
from jax import lax
from jax import tree_util
import jax.numpy as jnp
from jax.scipy import linalg
import numpy as np
_CHEX_SCALAR_TYPES = (float, int)
# Types for annotation
T = TypeVar("T")
Params = Any
Batch = Any
FuncState = Any
FuncAux = Any
PyTreeDef = chex.PyTreeDef
PyTreeType = Any
PyTree = chex.ArrayTree
FuncArgs = Sequence[PyTree]
Func = Callable[..., Any]
ValueFunc = Callable[..., chex.Array]
ValueAndGradFunc = Callable[..., Tuple[chex.Array, Params]]
AssumedFuncOutput = Union[
chex.Array,
Tuple[chex.Array, FuncAux],
Tuple[chex.Array, Tuple[FuncState, FuncAux]],
]
# Special global state
# If true we use a special case formula for when a block has one or more zero
# factors.
_SPECIAL_CASE_ZERO_INV: bool = True
def set_special_case_zero_inv(value: bool):
"""Sets whether `pi_adjusted_inverse` handles zero and nan matrices."""
global _SPECIAL_CASE_ZERO_INV
_SPECIAL_CASE_ZERO_INV = value
def get_special_case_zero_inv() -> bool:
"""Returns whether `pi_adjusted_inverse` handles zero and nan matrices."""
global _SPECIAL_CASE_ZERO_INV
return _SPECIAL_CASE_ZERO_INV
def fake_element_from_iterator(
iterator: Iterator[PyTree],
) -> Tuple[PyTree, Iterator[PyTree]]:
"""Returns a zeroed-out initial element of the iterator "non-destructively".
This function mutates the input iterator, hence after calling this function
it will be advanced by one. An equivalent to the original iterator (e.g. not
advanced by one) is returned as the second element of the returned pair. The
advised usage of the function is:
`fake_element, iterator = fake_element_from_iterator(iterator)`
Args:
iterator: A PyTree iterator. Must yield at least one element.
Returns:
A pair `(element, output_iterator)` where `element` is a zeroed-out version
of the first element of the iterator, and `output_iterator` is an
equivalent iterator to the input one.
"""
init_element = next(iterator)
fake_element = jax.tree_map(np.zeros_like, init_element)
def equivalent_iterator() -> Iterator[PyTree]:
yield init_element
# For some reason unknown to us, "yield from" can fail in certain
# circumstances
while True:
yield next(iterator)
return fake_element, equivalent_iterator()
def loop_and_parallelize_average(
func: Callable[..., PyTree],
max_parallel_size: int,
) -> Callable[..., PyTree]:
"""Returns a function that computes the average of `func` over any arguments.
The returned function is mathematically equivalent to:
jnp.mean(jax.vmap(func)(*args), axis=0).
However, naively using the above code could lead to prohibitively large memory
usage, as it scales linearly with the leading axis size of `args`, because of
`jax.vmap`. To amortize the memory cost, if the leading axis has size larger
than `max_parallel_size`, we call multiple times `vmap` in a loop via `scan`
by splitting the arguments to multiple chunks. This allows to trade off memory
usage for the cost of compute time.
Args:
func: A function that computes a singleton output.
max_parallel_size: The maximum number of elements that are allowed to be
part of a single call to `jax.vmap`.
Returns:
A function that computes the averaged output of `func` over the leading
axis of its arguments.
"""
vmap_fn = jax.vmap(func)
@functools.wraps(func)
def average_func(*args) -> PyTree:
lead_axis_sizes = set(x.shape[0] for x in jax.tree_leaves(args))
if not lead_axis_sizes:
raise ValueError("You must pass in at least one argument with a PyTree "
"leaf node.")
elif len(lead_axis_sizes) != 1:
raise ValueError(f"Inconsistent leading axis sizes seen: "
f"{lead_axis_sizes!r}.")
leading_size = next(iter(lead_axis_sizes))
singleton_args = jax.tree_map(lambda _x: _x[0], args)
_, output_tree = jax.make_jaxpr(func, return_shape=True)(*singleton_args)
singleton_size = sum(x.size for x in jax.tree_leaves(output_tree))
output_size = singleton_size * leading_size
# Compute the loop size and any remainder size
if max_parallel_size is None or output_size <= max_parallel_size:
parallel_size = leading_size
else:
parallel_size = max(
min(max_parallel_size // singleton_size, leading_size), 1)
# The arguments have to be split into chunks along their leading axis,
# however since `jax.scan` does not support inputs with different size,
# if the leading axis is not divisible by the parallel_size, we need to
# separately compute the values for the last remaining arguments chunks.
num_parallel_chunks = leading_size // parallel_size
remainder_size = leading_size % parallel_size
all_chunks_size = leading_size - remainder_size
# Index to get the loop arguments
loop_args = jax.tree_map(lambda x: x[:all_chunks_size], args)
if num_parallel_chunks == 1:
averaged_value = jnp.mean(vmap_fn(*loop_args), axis=0)
else:
def scan_fn(accumulator, args_):
vmap_value = vmap_fn(*args_)
avg_value = jax.tree_map(lambda x: jnp.mean(x, axis=0), vmap_value)
return jax.tree_map(jnp.add, accumulator, avg_value), None
loop_shape = (num_parallel_chunks, parallel_size)
loop_args = jax.tree_map(
lambda x: x.reshape(loop_shape + x.shape[1:]),
loop_args)
summed_value, _ = jax.lax.scan(
scan_fn,
init=jax.tree_map(lambda x: jnp.zeros(x.shape), output_tree),
xs=loop_args)
averaged_value = scalar_div(summed_value, num_parallel_chunks)
if remainder_size == 0:
return averaged_value
# Index to get the remainder arguments
remainder_args = jax.tree_map(lambda x: x[all_chunks_size:], args)
remainder_value = jnp.mean(vmap_fn(*remainder_args), axis=0)
avg_weight = all_chunks_size / leading_size
remainder_weight = remainder_size / leading_size
return weighted_sum_of_objects(
[averaged_value, remainder_value], [avg_weight, remainder_weight])
return average_func
# _____ __ __ _____
# | __ \| \/ | /\ | __ \
# | |__) | \ / | / \ | |__) |
# | ___/| |\/| | / /\ \ | ___/
# | | | | | |/ ____ \| |
# |_| |_| |_/_/ \_\_|
#
def wrap_if_pmap(
p_func: Callable[[PyTree, str], PyTree],
) -> Callable[[PyTree, Optional[str]], PyTree]:
"""Wraps `p_func` to be executed only when inside a `jax.pmap` context."""
@functools.wraps(p_func)
def p_func_if_pmap(obj: PyTree, axis_name: Optional[str]) -> PyTree:
if axis_name is None:
return obj
try:
# The only way to know if we are under `jax.pmap` is to check if the
# function call below raises a `NameError` or not.
core.axis_frame(axis_name)
# In pmap
return p_func(obj, axis_name)
except NameError:
# Not in pmap
return obj
return p_func_if_pmap
pmean_if_pmap = wrap_if_pmap(lax.pmean)
psum_if_pmap = wrap_if_pmap(lax.psum)
compute_mean = jax.pmap(lambda x: lax.pmean(x, "i"), axis_name="i")
compute_sum = jax.pmap(lambda x: lax.psum(x, "i"), axis_name="i")
def index_if_not_scalar(value: chex.Numeric, index: int = 0) -> chex.Numeric:
"""Index `value` at axis 0 if it is not a scalar, otherwise return it."""
if isinstance(value, chex.Array):
if value.ndim > 0:
return value[index]
else:
return value
elif isinstance(value, _CHEX_SCALAR_TYPES):
return value
else:
raise ValueError("The input should be an instance of `chex.Numeric`.")
@jax.jit
def get_first(obj: PyTree) -> PyTree:
"""Index the PyTree leaves `x` of `obj` by `x[0]` if they are not scalars."""
return jax.tree_map(index_if_not_scalar, obj)
@jax.jit
def get_mean(obj: PyTree) -> PyTree:
"""Returns the average of `obj` over different devices."""
return get_first(compute_mean(obj))
@jax.jit
def get_sum(obj: PyTree) -> PyTree:
"""Returns the sum of `obj` over different devices."""
return get_first(compute_sum(obj))
broadcast_all_local_devices = jax.pmap(lambda x: x)
pmap_zeros_like = jax.pmap(lambda x: jax.tree_map(jnp.zeros_like, x))
jit_zeros_like = jax.jit(lambda x: jax.tree_map(jnp.zeros_like, x))
def replicate_all_local_devices(obj: PyTree) -> PyTree:
"""Replicates `obj` to all local Jax devices."""
n = jax.local_device_count()
obj_stacked = jax.tree_map(lambda x: jnp.stack([x] * n, axis=0), obj)
return broadcast_all_local_devices(obj_stacked)
def make_different_rng_key_on_all_devices(rng: chex.PRNGKey) -> chex.PRNGKey:
"""Makes a different PRNG for all Jax devices and processes."""
rng = jax.random.fold_in(rng, jax.process_index())
rng = jax.random.split(rng, jax.local_device_count())
return broadcast_all_local_devices(rng)
p_split = jax.pmap(lambda key: tuple(jax.random.split(key)))
p_split_num = jax.pmap(lambda key, num: tuple(jax.random.split(key, num)),
static_broadcasted_argnums=1)
def check_and_fix_format_for_pmap(obj: PyTree) -> PyTree:
"""Checks shape[0]==device_count and broadcasts scalars to [device_count]."""
device_count = jax.local_device_count()
def check_and_fix(x: chex.Numeric) -> chex.Array:
# broadcast any 0D scalars
if isinstance(x, numbers.Number) or not x.shape:
return jnp.stack([x] * device_count, axis=0)
# otherwise ensure that arrays have the right shape
assert x.shape[0] == device_count
return x
return jax.tree_map(check_and_fix, obj)
default_device_sync = None
def host_sync(
obj: PyTree,
sync_op: Callable[[PyTree, str], PyTree],
) -> PyTree:
"""Syncs `obj` across multiple hosts with the operation `sync_op`."""
# The implementation here is to use the pmap syncing mechanisms but with only
# the default device of each host. Technically we could do this with all
# the devices on each host, but that would possibly be wasteful.
if jax.process_count() > 1:
# We set default_device_sync here because calling jax.local_devices during
# the library import stage will break JAX.
global default_device_sync
if default_device_sync is None:
default_devices = [jax.local_devices(process_index=p_idx)[0]
for p_idx in range(jax.process_count())]
default_device_sync = jax.pmap(lambda x, sync_op: sync_op(x, "i"),
devices=default_devices,
axis_name="i",
static_broadcasted_argnums=1)
obj = jax.tree_map(lambda x: jnp.expand_dims(x, axis=0), obj)
return get_first(default_device_sync(obj, sync_op))
return obj
def host_all_gather(x: PyTree) -> PyTree:
"""Gathers on every host the values of the PyTree leaves `x`."""
return host_sync(x, lax.all_gather)
def host_mean(x: PyTree) -> PyTree:
"""Computes the mean of the PyTree leaves of `x` over multiple hosts."""
return host_sync(x, lax.pmean)
def sync_and_divide_value(
value: PyTree,
counter: chex.Numeric,
axis_name: Optional[str] = None,
) -> PyTree:
"""Computes the mean of `value` over all hosts and divides it by `counter`."""
value = jax.tree_map(lambda x: x / counter, value)
return pmean_if_pmap(value, axis_name)
jit_sync_and_divide_value = jax.jit(sync_and_divide_value, donate_argnums=0)
pmap_sync_and_divide_value = jax.pmap(
functools.partial(sync_and_divide_value, axis_name="i"),
axis_name="i",
donate_argnums=0,
)
def copy_array(x: chex.Array) -> chex.Array:
"""Copies a Jax array so that it can be donated freely."""
return x + jnp.zeros_like(x)
copy_obj = jax.jit(lambda x: jax.tree_map(copy_array, x))
pmap_copy_obj = jax.pmap(copy_obj)
# __ __ _______ _ _
# | \/ | /\|__ __| | | |
# | \ / | / \ | | | |__| |
# | |\/| | / /\ \ | | | __ |
# | | | |/ ____ \| | | | | |
# |_| |_/_/ \_\_| |_| |_|
#
def product(iterable_object: Iterable[chex.Numeric]) -> chex.Numeric:
"""Computes the product of all elements in the iterable."""
x = 1
for element in iterable_object:
x = x * element
return x
def scalar_mul(obj: PyTree, scalar: chex.Numeric) -> PyTree:
"""Multiplies all PyTree leaves of the object by the provided scalar."""
# The check below is in its current form because of how `jax.jit` tracing
# mechanism work. If we use `scalar == 1` and `scalar` is an array, inside a
# `jit` context, jax will raise an error, since you are not allowed to use
# abstract values in concrete boolean statements, like native python
# if/while/for constructs.
if isinstance(scalar, _CHEX_SCALAR_TYPES) and scalar == 1.0:
return obj
return jax.tree_map(lambda x: x * scalar, obj)
def scalar_div(obj: PyTree, scalar: chex.Numeric) -> PyTree:
"""Divides all PyTree leaves of the object by the provided scalar."""
# The check below is in its current form because of how `jax.jit` tracing
# mechanism work. If we use `scalar == 1` and `scalar` is an array, inside a
# `jit` context, jax will raise an error, since you are not allowed to use
# abstract values in concrete boolean statements, like native python
# if/while/for constructs.
if isinstance(scalar, _CHEX_SCALAR_TYPES) and scalar == 1.0:
return obj
return jax.tree_map(lambda x: x / scalar, obj)
def weighted_sum_of_objects(
objects: Sequence[PyTree],
coefficients: Sequence[chex.Numeric],
) -> PyTree:
"""Computes a weighted sum of the objects'.
The function computes `sum_i coefficients[i] * objects[i]`. All objects must
have the same PyTree structure, and PyTree leaves in equivalent positions must
have the same shape.
Args:
objects: The sequence of objects to be summed together.
coefficients: The coefficients corresponding to each object instance.
Returns:
An object, representing the weighted sum, of the same type as the inputs.
"""
if len(objects) != len(coefficients):
raise ValueError("The number of coefficients must equal the number of "
"objects.")
if not objects:
raise ValueError("The objects' sequences can not be empty.")
accumulator = scalar_mul(objects[0], coefficients[0])
for o_i, c_i in zip(objects[1:], coefficients[1:]):
if not abstract_objects_equal(accumulator, o_i):
raise ValueError("One or more objects do not have equivalent abstract "
"structure.")
accumulator = jax.tree_map(jnp.add, accumulator, scalar_mul(o_i, c_i))
return accumulator
def _inner_product_float64(obj1: PyTree, obj2: PyTree) -> chex.Array:
"""Computes inner product explicitly in float64 precision."""
def array_ip(x, y):
x = jnp.array(jnp.reshape(x, [-1]), dtype=jnp.float64)
y = jnp.array(jnp.reshape(y, [-1]), dtype=jnp.float64)
return jnp.dot(x, y, precision=lax.Precision.HIGHEST)
with jax.experimental.enable_x64():
elements_inner_products = jax.tree_map(array_ip, obj1, obj2)
flat_list = jax.tree_leaves(elements_inner_products)
result = flat_list[0]
for element_ip in flat_list[1:]:
result = result + element_ip
# Convert back to default Jax dtype (usually float32)
return jnp.array(result)
def inner_product(
obj1: PyTree,
obj2: PyTree,
in_float64: bool = False
) -> chex.Array:
"""Computes the inner product `<vec(obj1), vec(obj2)>`.
To compute the inner product, each of the two input objects is assumed to
represent a vector by flattening and concatenating all of their PyTree leaves.
Objects `obj1` and `obj2` must have the same PyTree structure, and PyTree
leaves in equivalent positions must have the same shape.
Args:
obj1: The first object representing a vector.
obj2: The second object representing a vector.
in_float64: Whether to compute the inner product explicitly in `float64`
precision. If this is set to `True` the computation will be in double
precision regardless of whether `float64` has been enabled in Jax.
Returns:
The scalar value of the inner product.
"""
if not abstract_objects_equal(obj1, obj2, check_dtype=False):
raise ValueError("The objects do not have identical abstract structure.")
if in_float64:
return _inner_product_float64(obj1, obj2)
elements_product = jax.tree_map(lambda x, y: jnp.sum(x * y), obj1, obj2)
return sum(jax.tree_leaves(elements_product))
def symmetric_matrix_inner_products(
vectors1: Sequence[PyTree],
vectors2: Sequence[PyTree],
) -> chex.Array:
"""Computes a matrix of the inner products between the two sequences.
Args:
vectors1: A sequence of identically structured PyTrees, each one
representing a single vector.
vectors2: A sequence of identically structured PyTrees, each one
representing a single vector.
Returns:
A symmetric matrix `m` with elements `m[i, j] = <vectors[i], vectors2[j]>`
for `i >= j`.
"""
if len(vectors1) != len(vectors2):
raise ValueError("The two sequences should have the same length.")
m = [[] for _ in vectors1]
for i, v_i in enumerate(vectors1):
for j, v_j in enumerate(vectors2):
if j < i:
m[i].append(m[j][i])
else:
m[i].append(inner_product(v_i, v_j))
return jnp.asarray(m)
def matrix_of_inner_products(vectors: Sequence[PyTree]) -> chex.Array:
"""Computes the matrix of inner products of the sequence of vectors.
Args:
vectors: A sequence of identically structured PyTrees, each one representing
a single vector.
Returns:
A matrix `m` with elements `m[i, j] = <vectors[i], vectors[j]>`.
"""
return symmetric_matrix_inner_products(vectors, vectors)
def vector_of_inner_products(
base: PyTree,
vectors: Sequence[PyTree]
) -> chex.Array:
"""Computes a vector of inner products with base.
Args:
base: A PyTree representing the base vector.
vectors: A sequence of identically structured PyTrees, each one representing
a single vector.
Returns:
A vector `v` with elements `v[i] = <base, vectors[i]>`.
"""
v = []
for v_i in vectors:
v.append(inner_product(v_i, base))
return jnp.asarray(v)
def block_permuted(
matrix: chex.Array,
block_sizes: Sequence[int],
block_order: Sequence[int],
) -> chex.Array:
"""Permutes whole blocks of the input matrix.
Given a square matrix, this function splits it into blocks, each one having
a size defined in `block_sizes` and permutes them, both in rows and
columns. The permutation sends to the `i` slot the `block_order[i]` block of
the input matrix. Example:
matrix = [[A_0, B_0, C_0], [A_1, B_1, C_1], [A_2, B_2, C_2]]
block_order = [2, 0, 1]
=> [[C_2, A_2, B_2], [C_0, A_0, B_0], [C_1, A_1, B_1]]
Args:
matrix: The matrix, whose blocks will be permuted.
block_sizes: A sequences of each block's size.
block_order: A sequence of the order of the blocks.
Returns:
The resulting matrix after permuting the blocks.
"""
if len(block_sizes) != len(block_order):
raise ValueError(
f"The length of `block_sizes` (=={len(block_sizes)} "
f"and `block_order` (=={len(block_order)}) must be "
"the same.")
if all(i == j for i, j in enumerate(block_order)):
return matrix
indices = np.cumsum(block_sizes)[:-1]
blocks = [jnp.split(row, indices, 1) for row in jnp.split(matrix, indices, 0)]
reordered_blocks = [[blocks[i][j] for j in block_order] for i in block_order]
return jnp.block(reordered_blocks)
def norm(obj: PyTree) -> chex.Array:
"""Computes the Euclidean norm of the provided PyTree object."""
elements_squared_norm = jax.tree_map(
lambda x: jnp.sum(jnp.square(x)), obj)
return jnp.sqrt(sum(jax.tree_flatten(elements_squared_norm)[0]))
def psd_inv_cholesky(matrix: chex.Array, damping: chex.Array) -> chex.Array:
"""Computes the inverse of `matrix + damping*I`, with matrix assumed PSD."""
if matrix.shape[:1] != matrix.shape[1:]:
raise ValueError(f"Expected square matrix, but got shape {matrix.shape}.")
identity = jnp.eye(matrix.shape[0])
return linalg.solve(matrix + damping * identity, identity, sym_pos=True)
def pi_adjusted_inverse(
a: chex.Array,
b: chex.Array,
damping: chex.Numeric,
pmap_axis_name: Optional[str],
) -> Tuple[chex.Array, chex.Array]:
"""Computes an approximation to the inverse of `(a kron b + damping * I)`.
The inverse of `a kron b + damping * I` is not Kronecker factored in general,
because of the added identity. This function computes the pi-adjusted inverse
from [1] which finds two matrices whose Kronecker product approximates the
inverse. The two input matrices `a` and `b` are assumed to be PSD.
[1] - https://arxiv.org/abs/1503.05671
Args:
a: The left Kronecker factor.
b: The right Kronecker factor.
damping: The weight of the identity added to the Kronecker product.
pmap_axis_name: A `jax.pmap` axis name to use for synchronization.
Returns:
A pair of factors `(a_inv, b_inv)` whose Kronecker product approximates the
inverse of `(a kron b + damping * I)`.
"""
# Compute the nuclear/trace norms of each factor
a_norm = jnp.trace(a)
b_norm = jnp.trace(b)
# We need to sync the norms here, because reduction can be non-deterministic.
# They specifically are on GPUs by default for better performance.
# Hence although factor_0 and factor_1 are synced, the trace operation above
# can still produce different answers on different devices.
a_norm, b_norm = pmean_if_pmap((a_norm, b_norm), pmap_axis_name)
# Compute the overall scale
scale = a_norm * b_norm
def regular_inverse() -> Tuple[chex.Array, chex.Array]:
# Special cases with one or two scalar factors
if a.size == 1 and b.size == 1:
# Case: Inverse of a scalar. Has exact solution.
value = jnp.full_like(a, jnp.sqrt(scale + damping))
return value, value
elif a.size == 1:
# Case: Inverse of the matrix `b` and scalar `a`:
# `(a * b + d * I)^-1 = (1/scale) * (b/||b|| + d / scale * I)`
# since `scale = a * ||b||`.
b_normalized = b / b_norm
b_damping = damping / scale
b_inv = psd_inv_cholesky(b_normalized, b_damping)
return jnp.full_like(a, 1.0 / scale), b_inv
elif b.size == 1:
# Case: Inverse of the matrix `a` and scalar `b`:
# `(a * b + d * I)^-1 = (1/scale) * (a/||a|| + d / scale)^-1`
# since `scale = ||a|| * b`.
a_normalized = a / a_norm
a_damping = damping / scale
a_inv = psd_inv_cholesky(a_normalized, a_damping)
return a_inv, jnp.full_like(b, 1.0 / scale)
else:
# Case: The standard inversion from [1]
# Invert first factor
a_normalized = a / a_norm
a_damping = jnp.sqrt(damping * b.shape[0] / (scale * a.shape[0]))
a_inv = psd_inv_cholesky(a_normalized, a_damping) / jnp.sqrt(scale)
# Invert second factor
b_normalized = b / b_norm
b_damping = jnp.sqrt(damping * a.shape[0] / (scale * b.shape[0]))
b_inv = psd_inv_cholesky(b_normalized, b_damping) / jnp.sqrt(scale)
return a_inv, b_inv
def zero_inverse() -> Tuple[chex.Array, chex.Array]:
return (jnp.eye(a[0].shape[0]) / jnp.sqrt(damping),
jnp.eye(b[1].shape[0]) / jnp.sqrt(damping))
if get_special_case_zero_inv():
# In the special case where for some reason one of the factors is zero, then
# the correct inverse of `(0 kron A + lambda I)` is
# `(I/sqrt(lambda) kron (I/sqrt(lambda)`. However, because one of the norms
# is zero, then `pi` and `1/pi` would be 0 and infinity leading to NaN
# values. Hence, we need to make this check explicitly.
return lax.cond(
jnp.greater(scale, 0.0),
regular_inverse,
zero_inverse)
else:
return regular_inverse()
def kronecker_product_mul_v(
a: chex.Array,
b: chex.Array,
v: chex.Array,
a_is_symmetric: bool,
) -> chex.Array:
"""Computes `unvec[(a kron b) vec(v)]` for correctly sized input matrices."""
a_transpose = a if a_is_symmetric else jnp.swapaxes(a, -1, -2)
return (b @ v) @ a_transpose
def kronecker_eigen_basis_mul_v(
q_a: chex.Array,
q_b: chex.Array,
eigenvalues: chex.Array,
v: chex.Array,
) -> chex.Array:
"""Computes a matrix-vector product in a Kronecker product eigen-basis.
The function computes:
`(q_a kron q_b) diagonal(eigenvalues) (q_a kron q_b)^T vec(v)`
where all variables are appropriately sized matrices. The computation is
related to the usual Kronecker product `(a kron b) vec(v)`, if `a` and `b` are
symmetric matrices and `q_a` and `q_b` are the matrices of eigenvectors of `a`
and `b` and `eigenvalues` is the outer product of the eigenvalues of `a` and
`b`. However, the function does not assume anything about the `eigenvalues`
and allows for any dense matrix.
Args:
q_a: An orthonormal basis for eigenvectors of the first Kronecker factor.
q_b: An orthonormal basis for eigenvectors of the second Kronecker factor.
eigenvalues: A matrix containing the eigenvalues (e.g. the product of
eigenvalues of both factors).
v: The input vector as a matrix.
Returns:
The result of the matrix-vector product.
"""
q_a_transpose = jnp.swapaxes(q_a, -1, -2)
q_b_transpose = jnp.swapaxes(q_b, -1, -2)
q_proj_v = kronecker_product_mul_v(q_a_transpose, q_b_transpose, v, False)
if eigenvalues.shape != q_proj_v.shape:
raise ValueError("The eigenvalues array should have the same shape as the "
"projection of `v` onto `q_a kron q_b`.")
eig_weighted_v = eigenvalues * q_proj_v
return kronecker_product_mul_v(q_a, q_b, eig_weighted_v, False)
def safe_psd_eigh(x: chex.Array) -> Tuple[chex.Array, chex.Array]:
"""Computes the eigenvalue decomposition for a PSD matrix.
The function is similar to `jax.numpy.linalg.eigh`, but it clips the returned
eigenvalues to always be non-negative, which we know mathematically holds for
PSD matrices, but due to numerical errors `jax.numpy.linalg.eigh` could return
negative values.
Args:
x: The input matrix, assumed to be PSD.
Returns:
A pair of (eigenvalues, eigenvectors) arrays.
"""
d = x.shape[0]
# Here we are handling the case of NaNs separately, because in some versions
# of cuda and cudablas they can cause a runtime error.
s, q = lax.cond(
jnp.any(jnp.isnan(x)),
lambda _: (jnp.full([d], jnp.nan), jnp.full([d, d], jnp.nan)),
jnp.linalg.eigh,
x,
)
# The matrix is PSD by construction, but numerical inaccuracies can produce
# slightly negative eigenvalues. Hence, clip at zero.
return jnp.clip(s, a_min=0.0), q
# __ __ _____ _____ _____
# | \/ |_ _|/ ____|/ ____|
# | \ / | | | | (___ | |
# | |\/| | | | \___ \| |
# | | | |_| |_ ____) | |____
# |_| |_|_____|_____/ \_____|
def tree_is_empty(obj: PyTree) -> bool:
"""Returns whether the given PyTree is empty."""
return not jax.tree_leaves(obj)
def abstract_objects_equal(
obj1: PyTree,
obj2: PyTree,
check_dtype: bool = True
) -> bool:
"""`True` if the objects have the same PyTree structure, shapes and dtypes."""
return (jax.tree_structure(obj1) == jax.tree_structure(obj2) and
all(e1.shape == e2.shape and (e1.dtype == e2.dtype or not check_dtype)
for e1, e2 in zip(jax.tree_leaves(obj1), jax.tree_leaves(obj2))))
def to_tuple_or_repeat(
x: Union[chex.Numeric, Sequence[chex.Numeric]],
length: int,
) -> Tuple[chex.Numeric, ...]:
"""Converts `x` to a tuple of fixed length.
If `x` is an array, it is split along its last axis to a tuple (assumed to
have `x.shape[-1] == length`). If it is a scalar, the scalar is repeated
`length` times into a tuple, and if it is a list or a tuple it is just
verified that its length is the same.
Args:
x: The input array, scalar, list or tuple.
length: The length of the returned tuple.
Returns:
A tuple constructed by either replicating or splitting `x`.
"""
if isinstance(x, jnp.ndarray) and x.size > 1: # pytype: disable=attribute-error
assert x.shape[-1] == length # pytype: disable=attribute-error
return tuple(x[..., i] for i in range(length))
elif isinstance(x, (list, tuple)):
assert len(x) == length
return tuple(x)
elif isinstance(x, (int, float, jnp.ndarray)):
return (x,) * length
else:
raise ValueError(f"Unrecognized type for `x` - {type(x)}.")
def first_dim_is_size(size: int, *args: chex.Array) -> bool:
"""Checks that each element of `args` has first axis size equal to `size`."""
return all(arg.shape[0] == size for arg in args)
def pytree_dataclass(class_type: Type[Any]) -> Type[Any]:
"""Extended dataclass decorator, which also registers the class as a PyTree.
The function is equivalent to `dataclasses.dataclass`, but additionally
registers the `class_type` as a PyTree. This is done done by setting the
PyTree nodes to all of the `dataclasses.fields` of the class.
Args:
class_type: The class type to transform.
Returns:
The transformed `class_type` which is now a dataclass and also registered as
a PyTree.
"""
class_type = dataclasses.dataclass(class_type)
fields_names = tuple(field.name for field in dataclasses.fields(class_type))
def serialize_state(instance) -> Tuple[Tuple[Any, ...], Any]:
return tuple(getattr(instance, name) for name in fields_names), None
def deserialize_state(_: Any, args: Sequence[Any]) -> Any:
return class_type(*args)
tree_util.register_pytree_node(class_type, serialize_state, deserialize_state)
return class_type
@pytree_dataclass
class WeightedMovingAverage:
"""A wrapped class for an arbitrary weighted moving average."""
weight: chex.Array
raw_value: PyTree
@property
def value(self) -> PyTree:
"""The value of the underlying arrays data structure."""
return jax.tree_map(lambda x: x / self.weight, self.raw_value)
def update(
self,
value: PyTree,
old_weight_multiplier: chex.Numeric,
new_weight: chex.Numeric,
) -> None:
"""Updates the underlying array and weight accordingly."""
self.weight = self.weight * old_weight_multiplier + new_weight
self.raw_value = jax.tree_map(
lambda x, y: x * old_weight_multiplier + y * new_weight,
self.raw_value,
value,
)
def sync(self, pmap_axis_name: Optional[str]) -> None:
"""Syncs the underlying array across devices."""
self.raw_value = pmean_if_pmap(self.raw_value, pmap_axis_name)
@classmethod
def zero(cls, shape: chex.Shape) -> "WeightedMovingAverage":
"""Initializes a `WeightedMovingAverage` with a single array of zeros."""
return WeightedMovingAverage(
weight=jnp.zeros([]), raw_value=jnp.zeros(shape))
@classmethod
def zeros_like(cls, value: PyTree) -> "WeightedMovingAverage":
"""Initializes a `WeightedMovingAverage` with zeros structure like `value`."""
return WeightedMovingAverage(
weight=jnp.zeros([]), raw_value=jax.tree_map(jnp.zeros_like, value))
class MultiChunkAccumulator:
"""Statistics accumulation, abstracted over multiple chunks."""
def __init__(
self,
init_obj_value: Optional[PyTree],
weight: chex.Numeric,
multi_device: bool,
):
"""Initializes an accumulator instance with the provided object and counter.
Args:
init_obj_value: The initial value of the accumulator.
weight: The initial weight, which specifies how many samples are assumed
to have been already counted in the initial value of the accumulator.
multi_device: Whether the objects that are accumulated are outputs of a
multi-device computation (e.g. `jax.pmap`).
"""
self._accumulator = init_obj_value
self._weight = weight
self._multi_device = multi_device
@property
def accumulator(self) -> PyTree:
"""The current value of the underlying not-normalized accumulator."""
return self._accumulator
@property
def weight(self) -> chex.Numeric:
"""The current normalization weight of the underlying accumulator."""
return self._weight
@property
def multi_device(self) -> bool:
"""Whether the accumulator is the output of a multi-device computation."""
return self._multi_device
@property
def value(self) -> PyTree:
"""The current normalized value of the accumulator."""
if tree_is_empty(self.accumulator):
return self.accumulator
if self._multi_device:
return pmap_sync_and_divide_value(self.accumulator, self.weight)
else:
return jit_sync_and_divide_value(self.accumulator, self.weight)
def clear(self) -> None:
"""Sets the underlying accumulator and weight to `None`."""
self._accumulator = None
self._weight = None
def value_and_clear(self) -> PyTree:
"""Retrieves the normalized value of the accumulator and clears it."""
value = self.value
self.clear()
return value
def add(self, value_obj: PyTree, weight: chex.Numeric = 1) -> None:
"""Adds an element to the moving average and the max.
The exact update equation for the statistics are:
raw_value_t = raw_value_{t-1} + value_obj * weight
weight_t = weight_{t-1} + weight
Args:
value_obj: The value of the object, which scaled by `weight` will be added
to the accumulator.
weight: The relative weight of the `value_obj`.
"""
value_obj = jax.tree_map(lambda x: x * weight, value_obj)
if self._accumulator is None:
self._accumulator = value_obj
if isinstance(weight, _CHEX_SCALAR_TYPES):
self._weight = jnp.full_like(self._weight, weight)
elif not isinstance(weight, jnp.ndarray):
raise ValueError("`weight` should be an instance of float, int or "
"jnp.ndarray.")
elif self._weight.shape != weight.shape:
raise ValueError("If `weight` is an `jnp.ndarray` then should have the "
"same shape as the weight of the accumulator.")
else:
self._weight = weight
return
if not tree_is_empty(self._accumulator):
if tree_is_empty(value_obj):
raise ValueError("The provided `value_obj` has an empty PyTree "
"structure, but the accumulator has been initialized "
"with a non-empty PyTree object.")
self._accumulator = jax.tree_map(
jnp.add, self._accumulator, value_obj)
elif not tree_is_empty(value_obj):
raise ValueError("The provided `value_obj` has a non-empty PyTree "
"structure, but the accumulator has been initialized "
"with an empty PyTree object.")
self._weight = self._weight + weight
@classmethod
def zeros_like(
cls,
obj: PyTree,
multi_device: bool
) -> "MultiChunkAccumulator":
"""Creates a zero initialized accumulator as `obj`."""
if multi_device:
value_obj = pmap_zeros_like(obj) if not tree_is_empty(obj) else obj
weight = replicate_all_local_devices(jnp.zeros([], dtype=jnp.int32))
else:
value_obj = jit_zeros_like(obj) if not tree_is_empty(obj) else obj
weight = jnp.zeros([], dtype=jnp.int32)
return cls(value_obj, weight, multi_device)
@classmethod
def empty(cls, multi_device: bool) -> "MultiChunkAccumulator":
"""Creates an empty accumulator."""
weight = jnp.zeros([], dtype=jnp.int32)
if multi_device:
weight = replicate_all_local_devices(weight)
return cls(None, weight, multi_device)
def __repr__(self):
return (f"{self.__class__.__name__}({self._accumulator!r}, "
f"{self._weight!r}, {self._multi_device})")
tree_util.register_pytree_node(
MultiChunkAccumulator,
lambda x: ((x.accumulator, x.weight), (x.multi_device,)),
lambda fixed, arrays: MultiChunkAccumulator(*arrays, *fixed)
)
class Finalizable(abc.ABC):
"""A mixin for classes that can "finalize" their attributes.
The class provides the function `finalize` which freezes all attributes of the
instance after its call. Any attributes assignment thereafter will raise an
error. All subclasses must always call `super().__init__()` for the mixin to
function properly, and they must set any attributes before any call to
`finalize` has happened.
"""
def __init__(
self,
forbid_setting_attributes_after_finalize: bool = True,
excluded_attribute_names: Sequence[str] = (),
**parent_kwargs: Any,
):
"""Initializes the instance.
Args:
forbid_setting_attributes_after_finalize: If `True`, trying to set
attributes (via direct obj.attr = ...) after `finalize` was called on
the instance will raise an error. If `False`, this is not checked.
excluded_attribute_names: When `forbid_setting_attributes_after_finalize`
is set to `True` this specifies any attributes names that can still be
set.
**parent_kwargs: Any keyword arguments to be passed to any parent class.
"""
self._finalized = False
self._forbid_setting_attributes = forbid_setting_attributes_after_finalize
self._excluded_attribute_names = frozenset(excluded_attribute_names)
super().__init__(**parent_kwargs)
@property
def finalized(self) -> bool:
"""Whether the object has already been finalized."""
return self._finalized # pytype: disable=attribute-error
def finalize(self, *args: Any, **kwargs: Any):
"""Finalizes the object, after which no attributes can be set."""
if self.finalized:
raise ValueError("Object has already been finalized.")
self._finalize(*args, **kwargs)
self._finalized = True
def _finalize(self, *args: Any, **kwargs: Any):
"""Any logic that a child class needs to do during the finalization."""
def __setattr__(self, name: str, value: Any):
if (not getattr(self, "_finalized", False) or
not getattr(self, "_forbid_setting_attributes", True) or
name in getattr(self, "_excluded_attribute_names", ())):
super().__setattr__(name, value)
else:
raise AttributeError("Can't set attributes after finalization.")
class WithStagedMethods(Finalizable):
"""An mixin for classes which can have staged/compiled methods."""
class StagingContext:
"""A context manager for handling methods that are staged/compiled."""
def __init__(self, wsm_instance: "WithStagedMethods"):
"""Initializes the context manager.
Args:
wsm_instance: The corresponding `WithStagedMethods` instance.
"""
self._wsm_instance = wsm_instance
def __enter__(self):
"""Enters the staging context."""
if self._wsm_instance._in_staging:
raise RuntimeError("Cannot enter staging context while already in "
"staging context.")
self._wsm_instance._in_staging = True
def __exit__(self, *_):
"""Exits the staging context."""
assert self._wsm_instance._in_staging, "Exiting while not in staging."
self._wsm_instance._in_staging = False
def __init__(
self,
multi_device: bool = False,
pmap_axis_name: Optional[str] = None,
debug: bool = False,
**parent_kwargs: Any,
):
"""Initializes the instance.
Args:
multi_device: Whether any of decorated staged methods are to be run on a
single or multiple devices. If this is set to `True` than any call
would internally be delegated to `jax.pmap` and otherwise to `jax.jit`.
pmap_axis_name: The name of the pmap axis to use when running on
multiple devices. This is required if `multi_device=True`.
debug: If this is set `True` than any call to a stage method would
directly call the method and would not stage/compile it.
**parent_kwargs: Any additional keyword arguments for the parent class.
"""
if "excluded_attribute_names" in parent_kwargs:
parent_kwargs["excluded_attribute_names"] = (
("_in_staging",) + tuple(parent_kwargs["excluded_attribute_names"]))
else:
parent_kwargs["excluded_attribute_names"] = ("_in_staging",)
super().__init__(**parent_kwargs)
if multi_device and not isinstance(pmap_axis_name, str):
raise ValueError("When `multi_device=True` you must pass in a string for "
"`pmap_axis_name`.")
self._multi_device = multi_device
self._pmap_axis_name = pmap_axis_name
self._debug = debug
self._in_staging = False
@property
def multi_device(self) -> bool:
"""Indicates whether staged method will be run across multiple devices."""
return self._multi_device
@property
def pmap_axis_name(self) -> Optional[str]:
"""The name of the `jax.pmap` axis to use for staged methods."""
return self._pmap_axis_name
@property
def debug(self) -> bool:
"""Whether staged methods would be run in 'debug' mode."""
return self._debug
@property
def in_staging(self) -> bool:
"""Whether we are in a staging context while compiling staged methods."""
return self._in_staging
def staging_context(self) -> "StagingContext":
"""Returns a staging context manager, linked to this instance."""
return self.StagingContext(self)
def get_first(self, obj: PyTree) -> PyTree:
"""Indexes the `obj` PyTree leaves over leading axis if `multi_device`."""
return get_first(obj) if self.multi_device else obj
def copy_obj(self, obj: PyTree) -> PyTree:
"""Copies the object."""
return pmap_copy_obj(obj) if self.multi_device else copy_obj(obj)
def replicate(self, obj: PyTree) -> PyTree:
"""Replicates the object to all local devices if `multi_device`."""
return replicate_all_local_devices(obj) if self.multi_device else obj
def staged(
method: Callable[..., PyTree],
static_argnums: Optional[Union[int, Sequence[int]]] = None,
donate_argnums: Optional[Union[int, Sequence[int]]] = None,
) -> Callable[..., PyTree]:
"""Makes the instance method staged.
This decorator **should** only be applied to instance methods of classes that
inherit from the `WithStagedMethods` class. The decorator makes the decorated
method staged, which is equivalent to `jax.jit` if `instance.multi_device` is
`False` and to `jax.pmap` otherwise. When specifying static and donated
argunms, the `self` reference **must not** be counted. Example:
@functools.partial(staged, donate_argunms=0)
def try(self, x):
...
then `instance.try(x)` is equivalent to
`jax.jit(instance.try, donate_argnums=0)(x)` if `instance.multi_device` is
`False` and to `jax.pmap(instance.try, donate_argnums=0)(x)` otherwise.
Args:
method: The method to be transformed into a staged method.
static_argnums: The static argument numbers, as defined in `jax.jit/pmap`.
donate_argnums: The donated argument numbers, as defined in
`jax.jit/pmap`.
Returns:
The transformed method, which will now be a staged function.
"""
if isinstance(static_argnums, int):
static_argnums = (static_argnums,)
# This is needed because of b/147015762
if donate_argnums is None:
donate_argnums = ()
if isinstance(donate_argnums, int):
donate_argnums = (donate_argnums,)
else:
donate_argnums: Tuple[int, ...] = tuple(donate_argnums)
bcast_argnums = static_argnums
# shift static_argnums by 1 and include instance (self)
static_argnums = (0,) + tuple(i + 1 for i in (static_argnums or ()))
# shift donate_argnums by 1 and include state
donate_argnums = tuple(i + 1 for i in donate_argnums)
pmap_funcs = {}
jitted_func = jax.jit(method,
static_argnums=static_argnums,
donate_argnums=donate_argnums)
@functools.wraps(method)
def decorated(instance: "WithStagedMethods", *args: Any) -> PyTree:
if instance.in_staging:
return method(instance, *args)
with instance.staging_context():
if instance.multi_device and instance.debug:
# In this case we want to call `method` once for each device index.
# Note that this might not always produce sensible behavior, and will
# depend on the details of the method and if it has side-effects on the
# state of the class.
outs = []
non_bcast_args = [args[i] if i not in bcast_argnums else None
for i in range(len(args))]
for i in range(jax.local_device_count()):
non_bcast_args_i = jax.tree_map(
operator.itemgetter(i), non_bcast_args)
args_i = [
non_bcast_args_i[j] if j not in bcast_argnums else args[j]
for j in range(len(args))
]
outs.append(method(instance, *args_i))
outs = jax.tree_map(jnp.stack, *outs)
elif instance.debug:
outs = method(instance, *args)
elif instance.multi_device:
new_args = list(args)
for i in range(len(args)):
if i + 1 not in static_argnums:
new_args[i] = check_and_fix_format_for_pmap(args[i])
func = pmap_funcs.get(instance.pmap_axis_name)
if func is None:
func = jax.pmap(
method,
static_broadcasted_argnums=static_argnums,
donate_argnums=donate_argnums,
axis_name=instance.pmap_axis_name,
)
pmap_funcs[instance.pmap_axis_name] = func
outs = func(instance, *new_args)
else:
outs = jitted_func(instance, *args)
return outs
return decorated
| [
"jax.tree_flatten",
"jax.numpy.full_like",
"jax.numpy.block",
"jax.lax.psum",
"jax.experimental.enable_x64",
"jax.process_index",
"jax.numpy.reshape",
"jax.numpy.swapaxes",
"jax.jit",
"jax.numpy.mean",
"jax.tree_util.register_pytree_node",
"jax.local_device_count",
"jax.numpy.greater",
"ja... | [((1072, 1084), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {}), "('T')\n", (1079, 1084), False, 'from typing import Any, Callable, Iterable, Iterator, Optional, Sequence, Tuple, Type, TypeVar, Union\n'), ((8943, 8964), 'jax.pmap', 'jax.pmap', (['(lambda x: x)'], {}), '(lambda x: x)\n', (8951, 8964), False, 'import jax\n'), ((12168, 12216), 'jax.jit', 'jax.jit', (['sync_and_divide_value'], {'donate_argnums': '(0)'}), '(sync_and_divide_value, donate_argnums=0)\n', (12175, 12216), False, 'import jax\n'), ((12575, 12593), 'jax.pmap', 'jax.pmap', (['copy_obj'], {}), '(copy_obj)\n', (12583, 12593), False, 'import jax\n'), ((2864, 2905), 'jax.tree_map', 'jax.tree_map', (['np.zeros_like', 'init_element'], {}), '(np.zeros_like, init_element)\n', (2876, 2905), False, 'import jax\n'), ((4219, 4233), 'jax.vmap', 'jax.vmap', (['func'], {}), '(func)\n', (4227, 4233), False, 'import jax\n'), ((4238, 4259), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (4253, 4259), False, 'import functools\n'), ((7367, 7390), 'functools.wraps', 'functools.wraps', (['p_func'], {}), '(p_func)\n', (7382, 7390), False, 'import functools\n'), ((8584, 8622), 'jax.tree_map', 'jax.tree_map', (['index_if_not_scalar', 'obj'], {}), '(index_if_not_scalar, obj)\n', (8596, 8622), False, 'import jax\n'), ((9218, 9242), 'jax.local_device_count', 'jax.local_device_count', ([], {}), '()\n', (9240, 9242), False, 'import jax\n'), ((10010, 10034), 'jax.local_device_count', 'jax.local_device_count', ([], {}), '()\n', (10032, 10034), False, 'import jax\n'), ((10341, 10373), 'jax.tree_map', 'jax.tree_map', (['check_and_fix', 'obj'], {}), '(check_and_fix, obj)\n', (10353, 10373), False, 'import jax\n'), ((12054, 12096), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x / counter)', 'value'], {}), '(lambda x: x / counter, value)\n', (12066, 12096), False, 'import jax\n'), ((12260, 12315), 'functools.partial', 'functools.partial', (['sync_and_divide_value'], {'axis_name': '"""i"""'}), "(sync_and_divide_value, axis_name='i')\n", (12277, 12315), False, 'import functools\n'), ((13552, 13591), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x * scalar)', 'obj'], {}), '(lambda x: x * scalar, obj)\n', (13564, 13591), False, 'import jax\n'), ((14147, 14186), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x / scalar)', 'obj'], {}), '(lambda x: x / scalar, obj)\n', (14159, 14186), False, 'import jax\n'), ((16039, 16056), 'jax.numpy.array', 'jnp.array', (['result'], {}), '(result)\n', (16048, 16056), True, 'import jax.numpy as jnp\n'), ((18086, 18100), 'jax.numpy.asarray', 'jnp.asarray', (['m'], {}), '(m)\n', (18097, 18100), True, 'import jax.numpy as jnp\n'), ((18972, 18986), 'jax.numpy.asarray', 'jnp.asarray', (['v'], {}), '(v)\n', (18983, 18986), True, 'import jax.numpy as jnp\n'), ((20309, 20336), 'jax.numpy.block', 'jnp.block', (['reordered_blocks'], {}), '(reordered_blocks)\n', (20318, 20336), True, 'import jax.numpy as jnp\n'), ((20888, 20912), 'jax.numpy.eye', 'jnp.eye', (['matrix.shape[0]'], {}), '(matrix.shape[0])\n', (20895, 20912), True, 'import jax.numpy as jnp\n'), ((20922, 20987), 'jax.scipy.linalg.solve', 'linalg.solve', (['(matrix + damping * identity)', 'identity'], {'sym_pos': '(True)'}), '(matrix + damping * identity, identity, sym_pos=True)\n', (20934, 20987), False, 'from jax.scipy import linalg\n'), ((22001, 22013), 'jax.numpy.trace', 'jnp.trace', (['a'], {}), '(a)\n', (22010, 22013), True, 'import jax.numpy as jnp\n'), ((22025, 22037), 'jax.numpy.trace', 'jnp.trace', (['b'], {}), '(b)\n', (22034, 22037), True, 'import jax.numpy as jnp\n'), ((26079, 26104), 'jax.numpy.swapaxes', 'jnp.swapaxes', (['q_a', '(-1)', '(-2)'], {}), '(q_a, -1, -2)\n', (26091, 26104), True, 'import jax.numpy as jnp\n'), ((26123, 26148), 'jax.numpy.swapaxes', 'jnp.swapaxes', (['q_b', '(-1)', '(-2)'], {}), '(q_b, -1, -2)\n', (26135, 26148), True, 'import jax.numpy as jnp\n'), ((30009, 30042), 'dataclasses.dataclass', 'dataclasses.dataclass', (['class_type'], {}), '(class_type)\n', (30030, 30042), False, 'import dataclasses\n'), ((30351, 30429), 'jax.tree_util.register_pytree_node', 'tree_util.register_pytree_node', (['class_type', 'serialize_state', 'deserialize_state'], {}), '(class_type, serialize_state, deserialize_state)\n', (30381, 30429), False, 'from jax import tree_util\n'), ((44437, 44514), 'jax.jit', 'jax.jit', (['method'], {'static_argnums': 'static_argnums', 'donate_argnums': 'donate_argnums'}), '(method, static_argnums=static_argnums, donate_argnums=donate_argnums)\n', (44444, 44514), False, 'import jax\n'), ((44567, 44590), 'functools.wraps', 'functools.wraps', (['method'], {}), '(method)\n', (44582, 44590), False, 'import functools\n'), ((4727, 4763), 'jax.tree_map', 'jax.tree_map', (['(lambda _x: _x[0])', 'args'], {}), '(lambda _x: _x[0], args)\n', (4739, 4763), False, 'import jax\n'), ((5742, 5791), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x[:all_chunks_size])', 'args'], {}), '(lambda x: x[:all_chunks_size], args)\n', (5754, 5791), False, 'import jax\n'), ((6628, 6677), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x[all_chunks_size:])', 'args'], {}), '(lambda x: x[all_chunks_size:], args)\n', (6640, 6677), False, 'import jax\n'), ((7930, 7947), 'jax.lax.pmean', 'lax.pmean', (['x', '"""i"""'], {}), "(x, 'i')\n", (7939, 7947), False, 'from jax import lax\n'), ((7997, 8013), 'jax.lax.psum', 'lax.psum', (['x', '"""i"""'], {}), "(x, 'i')\n", (8005, 8013), False, 'from jax import lax\n'), ((9002, 9033), 'jax.tree_map', 'jax.tree_map', (['jnp.zeros_like', 'x'], {}), '(jnp.zeros_like, x)\n', (9014, 9033), False, 'import jax\n'), ((9070, 9101), 'jax.tree_map', 'jax.tree_map', (['jnp.zeros_like', 'x'], {}), '(jnp.zeros_like, x)\n', (9082, 9101), False, 'import jax\n'), ((9543, 9562), 'jax.process_index', 'jax.process_index', ([], {}), '()\n', (9560, 9562), False, 'import jax\n'), ((9594, 9618), 'jax.local_device_count', 'jax.local_device_count', ([], {}), '()\n', (9616, 9618), False, 'import jax\n'), ((10797, 10816), 'jax.process_count', 'jax.process_count', ([], {}), '()\n', (10814, 10816), False, 'import jax\n'), ((12481, 12498), 'jax.numpy.zeros_like', 'jnp.zeros_like', (['x'], {}), '(x)\n', (12495, 12498), True, 'import jax.numpy as jnp\n'), ((12530, 12557), 'jax.tree_map', 'jax.tree_map', (['copy_array', 'x'], {}), '(copy_array, x)\n', (12542, 12557), False, 'import jax\n'), ((15667, 15713), 'jax.numpy.dot', 'jnp.dot', (['x', 'y'], {'precision': 'lax.Precision.HIGHEST'}), '(x, y, precision=lax.Precision.HIGHEST)\n', (15674, 15713), True, 'import jax.numpy as jnp\n'), ((15722, 15751), 'jax.experimental.enable_x64', 'jax.experimental.enable_x64', ([], {}), '()\n', (15749, 15751), False, 'import jax\n'), ((15783, 15817), 'jax.tree_map', 'jax.tree_map', (['array_ip', 'obj1', 'obj2'], {}), '(array_ip, obj1, obj2)\n', (15795, 15817), False, 'import jax\n'), ((15834, 15874), 'jax.tree_leaves', 'jax.tree_leaves', (['elements_inner_products'], {}), '(elements_inner_products)\n', (15849, 15874), False, 'import jax\n'), ((17201, 17234), 'jax.tree_leaves', 'jax.tree_leaves', (['elements_product'], {}), '(elements_product)\n', (17216, 17234), False, 'import jax\n'), ((20111, 20133), 'numpy.cumsum', 'np.cumsum', (['block_sizes'], {}), '(block_sizes)\n', (20120, 20133), True, 'import numpy as np\n'), ((20151, 20177), 'jax.numpy.split', 'jnp.split', (['row', 'indices', '(1)'], {}), '(row, indices, 1)\n', (20160, 20177), True, 'import jax.numpy as jnp\n'), ((24891, 24914), 'jax.numpy.swapaxes', 'jnp.swapaxes', (['a', '(-1)', '(-2)'], {}), '(a, -1, -2)\n', (24903, 24914), True, 'import jax.numpy as jnp\n'), ((27481, 27503), 'jax.numpy.clip', 'jnp.clip', (['s'], {'a_min': '(0.0)'}), '(s, a_min=0.0)\n', (27489, 27503), True, 'import jax.numpy as jnp\n'), ((27789, 27809), 'jax.tree_leaves', 'jax.tree_leaves', (['obj'], {}), '(obj)\n', (27804, 27809), False, 'import jax\n'), ((30720, 30775), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x / self.weight)', 'self.raw_value'], {}), '(lambda x: x / self.weight, self.raw_value)\n', (30732, 30775), False, 'import jax\n'), ((31063, 31160), 'jax.tree_map', 'jax.tree_map', (['(lambda x, y: x * old_weight_multiplier + y * new_weight)', 'self.raw_value', 'value'], {}), '(lambda x, y: x * old_weight_multiplier + y * new_weight, self.\n raw_value, value)\n', (31075, 31160), False, 'import jax\n'), ((34262, 34307), 'jax.tree_map', 'jax.tree_map', (['(lambda x: x * weight)', 'value_obj'], {}), '(lambda x: x * weight, value_obj)\n', (34274, 34307), False, 'import jax\n'), ((36239, 36269), 'jax.numpy.zeros', 'jnp.zeros', (['[]'], {'dtype': 'jnp.int32'}), '([], dtype=jnp.int32)\n', (36248, 36269), True, 'import jax.numpy as jnp\n'), ((4785, 4824), 'jax.make_jaxpr', 'jax.make_jaxpr', (['func'], {'return_shape': '(True)'}), '(func, return_shape=True)\n', (4799, 4824), False, 'import jax\n'), ((7652, 7678), 'jax.core.axis_frame', 'core.axis_frame', (['axis_name'], {}), '(axis_name)\n', (7667, 7678), False, 'from jax import core\n'), ((9282, 9308), 'jax.numpy.stack', 'jnp.stack', (['([x] * n)'], {'axis': '(0)'}), '([x] * n, axis=0)\n', (9291, 9308), True, 'import jax.numpy as jnp\n'), ((9701, 9722), 'jax.random.split', 'jax.random.split', (['key'], {}), '(key)\n', (9717, 9722), False, 'import jax\n'), ((9771, 9797), 'jax.random.split', 'jax.random.split', (['key', 'num'], {}), '(key, num)\n', (9787, 9797), False, 'import jax\n'), ((10185, 10222), 'jax.numpy.stack', 'jnp.stack', (['([x] * device_count)'], {'axis': '(0)'}), '([x] * device_count, axis=0)\n', (10194, 10222), True, 'import jax.numpy as jnp\n'), ((15556, 15576), 'jax.numpy.reshape', 'jnp.reshape', (['x', '[-1]'], {}), '(x, [-1])\n', (15567, 15576), True, 'import jax.numpy as jnp\n'), ((15615, 15635), 'jax.numpy.reshape', 'jnp.reshape', (['y', '[-1]'], {}), '(y, [-1])\n', (15626, 15635), True, 'import jax.numpy as jnp\n'), ((17160, 17174), 'jax.numpy.sum', 'jnp.sum', (['(x * y)'], {}), '(x * y)\n', (17167, 17174), True, 'import jax.numpy as jnp\n'), ((20189, 20218), 'jax.numpy.split', 'jnp.split', (['matrix', 'indices', '(0)'], {}), '(matrix, indices, 0)\n', (20198, 20218), True, 'import jax.numpy as jnp\n'), ((24530, 24553), 'jax.numpy.greater', 'jnp.greater', (['scale', '(0.0)'], {}), '(scale, 0.0)\n', (24541, 24553), True, 'import jax.numpy as jnp\n'), ((27217, 27229), 'jax.numpy.isnan', 'jnp.isnan', (['x'], {}), '(x)\n', (27226, 27229), True, 'import jax.numpy as jnp\n'), ((28007, 28031), 'jax.tree_structure', 'jax.tree_structure', (['obj1'], {}), '(obj1)\n', (28025, 28031), False, 'import jax\n'), ((28035, 28059), 'jax.tree_structure', 'jax.tree_structure', (['obj2'], {}), '(obj2)\n', (28053, 28059), False, 'import jax\n'), ((35228, 35279), 'jax.tree_map', 'jax.tree_map', (['jnp.add', 'self._accumulator', 'value_obj'], {}), '(jnp.add, self._accumulator, value_obj)\n', (35240, 35279), False, 'import jax\n'), ((36026, 36056), 'jax.numpy.zeros', 'jnp.zeros', (['[]'], {'dtype': 'jnp.int32'}), '([], dtype=jnp.int32)\n', (36035, 36056), True, 'import jax.numpy as jnp\n'), ((11439, 11465), 'jax.numpy.expand_dims', 'jnp.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (11454, 11465), True, 'import jax.numpy as jnp\n'), ((20507, 20520), 'jax.numpy.square', 'jnp.square', (['x'], {}), '(x)\n', (20517, 20520), True, 'import jax.numpy as jnp\n'), ((20550, 20589), 'jax.tree_flatten', 'jax.tree_flatten', (['elements_squared_norm'], {}), '(elements_squared_norm)\n', (20566, 20589), False, 'import jax\n'), ((22686, 22711), 'jax.numpy.sqrt', 'jnp.sqrt', (['(scale + damping)'], {}), '(scale + damping)\n', (22694, 22711), True, 'import jax.numpy as jnp\n'), ((24014, 24036), 'jax.numpy.eye', 'jnp.eye', (['a[0].shape[0]'], {}), '(a[0].shape[0])\n', (24021, 24036), True, 'import jax.numpy as jnp\n'), ((24039, 24056), 'jax.numpy.sqrt', 'jnp.sqrt', (['damping'], {}), '(damping)\n', (24047, 24056), True, 'import jax.numpy as jnp\n'), ((24070, 24092), 'jax.numpy.eye', 'jnp.eye', (['b[1].shape[0]'], {}), '(b[1].shape[0])\n', (24077, 24092), True, 'import jax.numpy as jnp\n'), ((24095, 24112), 'jax.numpy.sqrt', 'jnp.sqrt', (['damping'], {}), '(damping)\n', (24103, 24112), True, 'import jax.numpy as jnp\n'), ((27249, 27271), 'jax.numpy.full', 'jnp.full', (['[d]', 'jnp.nan'], {}), '([d], jnp.nan)\n', (27257, 27271), True, 'import jax.numpy as jnp\n'), ((27273, 27298), 'jax.numpy.full', 'jnp.full', (['[d, d]', 'jnp.nan'], {}), '([d, d], jnp.nan)\n', (27281, 27298), True, 'import jax.numpy as jnp\n'), ((30090, 30120), 'dataclasses.fields', 'dataclasses.fields', (['class_type'], {}), '(class_type)\n', (30108, 30120), False, 'import dataclasses\n'), ((31571, 31584), 'jax.numpy.zeros', 'jnp.zeros', (['[]'], {}), '([])\n', (31580, 31584), True, 'import jax.numpy as jnp\n'), ((31596, 31612), 'jax.numpy.zeros', 'jnp.zeros', (['shape'], {}), '(shape)\n', (31605, 31612), True, 'import jax.numpy as jnp\n'), ((31827, 31840), 'jax.numpy.zeros', 'jnp.zeros', (['[]'], {}), '([])\n', (31836, 31840), True, 'import jax.numpy as jnp\n'), ((31852, 31887), 'jax.tree_map', 'jax.tree_map', (['jnp.zeros_like', 'value'], {}), '(jnp.zeros_like, value)\n', (31864, 31887), False, 'import jax\n'), ((34451, 34486), 'jax.numpy.full_like', 'jnp.full_like', (['self._weight', 'weight'], {}), '(self._weight, weight)\n', (34464, 34486), True, 'import jax.numpy as jnp\n'), ((35896, 35926), 'jax.numpy.zeros', 'jnp.zeros', (['[]'], {'dtype': 'jnp.int32'}), '([], dtype=jnp.int32)\n', (35905, 35926), True, 'import jax.numpy as jnp\n'), ((45581, 45611), 'jax.tree_map', 'jax.tree_map', (['jnp.stack', '*outs'], {}), '(jnp.stack, *outs)\n', (45593, 45611), False, 'import jax\n'), ((4343, 4364), 'jax.tree_leaves', 'jax.tree_leaves', (['args'], {}), '(args)\n', (4358, 4364), False, 'import jax\n'), ((4883, 4911), 'jax.tree_leaves', 'jax.tree_leaves', (['output_tree'], {}), '(output_tree)\n', (4898, 4911), False, 'import jax\n'), ((6064, 6109), 'jax.tree_map', 'jax.tree_map', (['jnp.add', 'accumulator', 'avg_value'], {}), '(jnp.add, accumulator, avg_value)\n', (6076, 6109), False, 'import jax\n'), ((11042, 11080), 'jax.local_devices', 'jax.local_devices', ([], {'process_index': 'p_idx'}), '(process_index=p_idx)\n', (11059, 11080), False, 'import jax\n'), ((23057, 23086), 'jax.numpy.full_like', 'jnp.full_like', (['a', '(1.0 / scale)'], {}), '(a, 1.0 / scale)\n', (23070, 23086), True, 'import jax.numpy as jnp\n'), ((23584, 23637), 'jax.numpy.sqrt', 'jnp.sqrt', (['(damping * b.shape[0] / (scale * a.shape[0]))'], {}), '(damping * b.shape[0] / (scale * a.shape[0]))\n', (23592, 23637), True, 'import jax.numpy as jnp\n'), ((23792, 23845), 'jax.numpy.sqrt', 'jnp.sqrt', (['(damping * a.shape[0] / (scale * b.shape[0]))'], {}), '(damping * a.shape[0] / (scale * b.shape[0]))\n', (23800, 23845), True, 'import jax.numpy as jnp\n'), ((45246, 45270), 'jax.local_device_count', 'jax.local_device_count', ([], {}), '()\n', (45268, 45270), False, 'import jax\n'), ((6016, 6035), 'jax.numpy.mean', 'jnp.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (6024, 6035), True, 'import jax.numpy as jnp\n'), ((11128, 11147), 'jax.process_count', 'jax.process_count', ([], {}), '()\n', (11145, 11147), False, 'import jax\n'), ((23418, 23447), 'jax.numpy.full_like', 'jnp.full_like', (['b', '(1.0 / scale)'], {}), '(b, 1.0 / scale)\n', (23431, 23447), True, 'import jax.numpy as jnp\n'), ((23696, 23711), 'jax.numpy.sqrt', 'jnp.sqrt', (['scale'], {}), '(scale)\n', (23704, 23711), True, 'import jax.numpy as jnp\n'), ((23904, 23919), 'jax.numpy.sqrt', 'jnp.sqrt', (['scale'], {}), '(scale)\n', (23912, 23919), True, 'import jax.numpy as jnp\n'), ((28177, 28198), 'jax.tree_leaves', 'jax.tree_leaves', (['obj1'], {}), '(obj1)\n', (28192, 28198), False, 'import jax\n'), ((28200, 28221), 'jax.tree_leaves', 'jax.tree_leaves', (['obj2'], {}), '(obj2)\n', (28215, 28221), False, 'import jax\n'), ((45330, 45352), 'operator.itemgetter', 'operator.itemgetter', (['i'], {}), '(i)\n', (45349, 45352), False, 'import operator\n'), ((6379, 6397), 'jax.numpy.zeros', 'jnp.zeros', (['x.shape'], {}), '(x.shape)\n', (6388, 6397), True, 'import jax.numpy as jnp\n'), ((45984, 46114), 'jax.pmap', 'jax.pmap', (['method'], {'static_broadcasted_argnums': 'static_argnums', 'donate_argnums': 'donate_argnums', 'axis_name': 'instance.pmap_axis_name'}), '(method, static_broadcasted_argnums=static_argnums, donate_argnums=\n donate_argnums, axis_name=instance.pmap_axis_name)\n', (45992, 46114), False, 'import jax\n')] |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import unittest
import numpy as np
import paddle
import paddle.fluid.core as core
from op_test import OpTest
paddle.enable_static()
class ApiFMinTest(unittest.TestCase):
"""ApiFMinTest"""
def setUp(self):
"""setUp"""
if core.is_compiled_with_cuda():
self.place = core.CUDAPlace(0)
else:
self.place = core.CPUPlace()
self.input_x = np.random.rand(10, 15).astype("float32")
self.input_y = np.random.rand(10, 15).astype("float32")
self.input_z = np.random.rand(15).astype("float32")
self.input_a = np.array([0, np.nan, np.nan]).astype('int64')
self.input_b = np.array([2, np.inf, -np.inf]).astype('int64')
self.input_c = np.array([4, 1, 3]).astype('int64')
self.np_expected1 = np.fmin(self.input_x, self.input_y)
self.np_expected2 = np.fmin(self.input_x, self.input_z)
self.np_expected3 = np.fmin(self.input_a, self.input_c)
self.np_expected4 = np.fmin(self.input_b, self.input_c)
def test_static_api(self):
"""test_static_api"""
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.static.data("x", shape=[10, 15], dtype="float32")
data_y = paddle.static.data("y", shape=[10, 15], dtype="float32")
result_fmin = paddle.fmin(data_x, data_y)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"y": self.input_y},
fetch_list=[result_fmin])
self.assertTrue(np.allclose(res, self.np_expected1))
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_x = paddle.static.data("x", shape=[10, 15], dtype="float32")
data_z = paddle.static.data("z", shape=[15], dtype="float32")
result_fmin = paddle.fmin(data_x, data_z)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"x": self.input_x,
"z": self.input_z},
fetch_list=[result_fmin])
self.assertTrue(np.allclose(res, self.np_expected2))
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_a = paddle.static.data("a", shape=[3], dtype="int64")
data_c = paddle.static.data("c", shape=[3], dtype="int64")
result_fmin = paddle.fmin(data_a, data_c)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"a": self.input_a,
"c": self.input_c},
fetch_list=[result_fmin])
self.assertTrue(np.allclose(res, self.np_expected3))
with paddle.static.program_guard(paddle.static.Program(),
paddle.static.Program()):
data_b = paddle.static.data("b", shape=[3], dtype="int64")
data_c = paddle.static.data("c", shape=[3], dtype="int64")
result_fmin = paddle.fmin(data_b, data_c)
exe = paddle.static.Executor(self.place)
res, = exe.run(feed={"b": self.input_b,
"c": self.input_c},
fetch_list=[result_fmin])
self.assertTrue(np.allclose(res, self.np_expected4))
def test_dynamic_api(self):
"""test_dynamic_api"""
paddle.disable_static()
x = paddle.to_tensor(self.input_x)
y = paddle.to_tensor(self.input_y)
z = paddle.to_tensor(self.input_z)
a = paddle.to_tensor(self.input_a)
b = paddle.to_tensor(self.input_b)
c = paddle.to_tensor(self.input_c)
res = paddle.fmin(x, y)
res = res.numpy()
self.assertTrue(np.allclose(res, self.np_expected1))
# test broadcast
res = paddle.fmin(x, z)
res = res.numpy()
self.assertTrue(np.allclose(res, self.np_expected2))
res = paddle.fmin(a, c)
res = res.numpy()
self.assertTrue(np.allclose(res, self.np_expected3))
res = paddle.fmin(b, c)
res = res.numpy()
self.assertTrue(np.allclose(res, self.np_expected4))
class TestElementwiseFminOp(OpTest):
"""TestElementwiseFminOp"""
def setUp(self):
"""setUp"""
self.op_type = "elementwise_fmin"
self.python_api = paddle.fmin
# If x and y have the same value, the min() is not differentiable.
# So we generate test data by the following method
# to avoid them being too close to each other.
x = np.random.uniform(0.1, 1, [13, 17]).astype("float64")
sgn = np.random.choice([-1, 1], [13, 17]).astype("float64")
y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype("float64")
self.inputs = {'X': x, 'Y': y}
self.outputs = {'Out': np.fmin(self.inputs['X'], self.inputs['Y'])}
def test_check_output(self):
"""test_check_output"""
self.check_output(check_eager=True)
def test_check_grad_normal(self):
"""test_check_grad_normal"""
self.check_grad(['X', 'Y'], 'Out', check_eager=True)
def test_check_grad_ingore_x(self):
"""test_check_grad_ingore_x"""
self.check_grad(
['Y'],
'Out',
max_relative_error=0.005,
no_grad_set=set("X"),
check_eager=True)
def test_check_grad_ingore_y(self):
"""test_check_grad_ingore_y"""
self.check_grad(
['X'],
'Out',
max_relative_error=0.005,
no_grad_set=set('Y'),
check_eager=True)
class TestElementwiseFmin2Op(OpTest):
"""TestElementwiseFmin2Op"""
def setUp(self):
"""setUp"""
self.op_type = "elementwise_fmin"
self.python_api = paddle.fmin
# If x and y have the same value, the min() is not differentiable.
# So we generate test data by the following method
# to avoid them being too close to each other.
x = np.random.uniform(0.1, 1, [13, 17]).astype("float64")
sgn = np.random.choice([-1, 1], [13, 17]).astype("float64")
y = x + sgn * np.random.uniform(0.1, 1, [13, 17]).astype("float64")
y[2, 10:] = np.nan
self.inputs = {'X': x, 'Y': y}
self.outputs = {'Out': np.fmin(self.inputs['X'], self.inputs['Y'])}
def test_check_output(self):
"""test_check_output"""
self.check_output(check_eager=True)
def test_check_grad_normal(self):
"""test_check_grad_normal"""
self.check_grad(['X', 'Y'], 'Out', check_eager=True)
def test_check_grad_ingore_x(self):
"""test_check_grad_ingore_x"""
self.check_grad(
['Y'],
'Out',
max_relative_error=0.005,
no_grad_set=set("X"),
check_eager=True)
def test_check_grad_ingore_y(self):
"""test_check_grad_ingore_y"""
self.check_grad(
['X'],
'Out',
max_relative_error=0.005,
no_grad_set=set('Y'),
check_eager=True)
if __name__ == "__main__":
paddle.enable_static()
unittest.main()
| [
"unittest.main",
"numpy.fmin",
"paddle.static.data",
"numpy.random.uniform",
"numpy.random.choice",
"paddle.fluid.core.CUDAPlace",
"paddle.enable_static",
"numpy.allclose",
"paddle.static.Program",
"paddle.fluid.core.CPUPlace",
"numpy.array",
"paddle.disable_static",
"paddle.static.Executor"... | [((760, 782), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (780, 782), False, 'import paddle\n'), ((8005, 8027), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (8025, 8027), False, 'import paddle\n'), ((8032, 8047), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8045, 8047), False, 'import unittest\n'), ((898, 926), 'paddle.fluid.core.is_compiled_with_cuda', 'core.is_compiled_with_cuda', ([], {}), '()\n', (924, 926), True, 'import paddle.fluid.core as core\n'), ((1442, 1477), 'numpy.fmin', 'np.fmin', (['self.input_x', 'self.input_y'], {}), '(self.input_x, self.input_y)\n', (1449, 1477), True, 'import numpy as np\n'), ((1506, 1541), 'numpy.fmin', 'np.fmin', (['self.input_x', 'self.input_z'], {}), '(self.input_x, self.input_z)\n', (1513, 1541), True, 'import numpy as np\n'), ((1570, 1605), 'numpy.fmin', 'np.fmin', (['self.input_a', 'self.input_c'], {}), '(self.input_a, self.input_c)\n', (1577, 1605), True, 'import numpy as np\n'), ((1634, 1669), 'numpy.fmin', 'np.fmin', (['self.input_b', 'self.input_c'], {}), '(self.input_b, self.input_c)\n', (1641, 1669), True, 'import numpy as np\n'), ((1740, 1762), 'paddle.enable_static', 'paddle.enable_static', ([], {}), '()\n', (1760, 1762), False, 'import paddle\n'), ((4266, 4289), 'paddle.disable_static', 'paddle.disable_static', ([], {}), '()\n', (4287, 4289), False, 'import paddle\n'), ((4302, 4332), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_x'], {}), '(self.input_x)\n', (4318, 4332), False, 'import paddle\n'), ((4345, 4375), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_y'], {}), '(self.input_y)\n', (4361, 4375), False, 'import paddle\n'), ((4388, 4418), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_z'], {}), '(self.input_z)\n', (4404, 4418), False, 'import paddle\n'), ((4432, 4462), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_a'], {}), '(self.input_a)\n', (4448, 4462), False, 'import paddle\n'), ((4475, 4505), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_b'], {}), '(self.input_b)\n', (4491, 4505), False, 'import paddle\n'), ((4518, 4548), 'paddle.to_tensor', 'paddle.to_tensor', (['self.input_c'], {}), '(self.input_c)\n', (4534, 4548), False, 'import paddle\n'), ((4564, 4581), 'paddle.fmin', 'paddle.fmin', (['x', 'y'], {}), '(x, y)\n', (4575, 4581), False, 'import paddle\n'), ((4709, 4726), 'paddle.fmin', 'paddle.fmin', (['x', 'z'], {}), '(x, z)\n', (4720, 4726), False, 'import paddle\n'), ((4829, 4846), 'paddle.fmin', 'paddle.fmin', (['a', 'c'], {}), '(a, c)\n', (4840, 4846), False, 'import paddle\n'), ((4949, 4966), 'paddle.fmin', 'paddle.fmin', (['b', 'c'], {}), '(b, c)\n', (4960, 4966), False, 'import paddle\n'), ((953, 970), 'paddle.fluid.core.CUDAPlace', 'core.CUDAPlace', (['(0)'], {}), '(0)\n', (967, 970), True, 'import paddle.fluid.core as core\n'), ((1010, 1025), 'paddle.fluid.core.CPUPlace', 'core.CPUPlace', ([], {}), '()\n', (1023, 1025), True, 'import paddle.fluid.core as core\n'), ((1917, 1973), 'paddle.static.data', 'paddle.static.data', (['"""x"""'], {'shape': '[10, 15]', 'dtype': '"""float32"""'}), "('x', shape=[10, 15], dtype='float32')\n", (1935, 1973), False, 'import paddle\n'), ((1995, 2051), 'paddle.static.data', 'paddle.static.data', (['"""y"""'], {'shape': '[10, 15]', 'dtype': '"""float32"""'}), "('y', shape=[10, 15], dtype='float32')\n", (2013, 2051), False, 'import paddle\n'), ((2078, 2105), 'paddle.fmin', 'paddle.fmin', (['data_x', 'data_y'], {}), '(data_x, data_y)\n', (2089, 2105), False, 'import paddle\n'), ((2124, 2158), 'paddle.static.Executor', 'paddle.static.Executor', (['self.place'], {}), '(self.place)\n', (2146, 2158), False, 'import paddle\n'), ((2341, 2376), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected1'], {}), '(res, self.np_expected1)\n', (2352, 2376), True, 'import numpy as np\n'), ((2533, 2589), 'paddle.static.data', 'paddle.static.data', (['"""x"""'], {'shape': '[10, 15]', 'dtype': '"""float32"""'}), "('x', shape=[10, 15], dtype='float32')\n", (2551, 2589), False, 'import paddle\n'), ((2611, 2663), 'paddle.static.data', 'paddle.static.data', (['"""z"""'], {'shape': '[15]', 'dtype': '"""float32"""'}), "('z', shape=[15], dtype='float32')\n", (2629, 2663), False, 'import paddle\n'), ((2690, 2717), 'paddle.fmin', 'paddle.fmin', (['data_x', 'data_z'], {}), '(data_x, data_z)\n', (2701, 2717), False, 'import paddle\n'), ((2736, 2770), 'paddle.static.Executor', 'paddle.static.Executor', (['self.place'], {}), '(self.place)\n', (2758, 2770), False, 'import paddle\n'), ((2953, 2988), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected2'], {}), '(res, self.np_expected2)\n', (2964, 2988), True, 'import numpy as np\n'), ((3145, 3194), 'paddle.static.data', 'paddle.static.data', (['"""a"""'], {'shape': '[3]', 'dtype': '"""int64"""'}), "('a', shape=[3], dtype='int64')\n", (3163, 3194), False, 'import paddle\n'), ((3216, 3265), 'paddle.static.data', 'paddle.static.data', (['"""c"""'], {'shape': '[3]', 'dtype': '"""int64"""'}), "('c', shape=[3], dtype='int64')\n", (3234, 3265), False, 'import paddle\n'), ((3292, 3319), 'paddle.fmin', 'paddle.fmin', (['data_a', 'data_c'], {}), '(data_a, data_c)\n', (3303, 3319), False, 'import paddle\n'), ((3338, 3372), 'paddle.static.Executor', 'paddle.static.Executor', (['self.place'], {}), '(self.place)\n', (3360, 3372), False, 'import paddle\n'), ((3555, 3590), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected3'], {}), '(res, self.np_expected3)\n', (3566, 3590), True, 'import numpy as np\n'), ((3747, 3796), 'paddle.static.data', 'paddle.static.data', (['"""b"""'], {'shape': '[3]', 'dtype': '"""int64"""'}), "('b', shape=[3], dtype='int64')\n", (3765, 3796), False, 'import paddle\n'), ((3818, 3867), 'paddle.static.data', 'paddle.static.data', (['"""c"""'], {'shape': '[3]', 'dtype': '"""int64"""'}), "('c', shape=[3], dtype='int64')\n", (3836, 3867), False, 'import paddle\n'), ((3894, 3921), 'paddle.fmin', 'paddle.fmin', (['data_b', 'data_c'], {}), '(data_b, data_c)\n', (3905, 3921), False, 'import paddle\n'), ((3940, 3974), 'paddle.static.Executor', 'paddle.static.Executor', (['self.place'], {}), '(self.place)\n', (3962, 3974), False, 'import paddle\n'), ((4157, 4192), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected4'], {}), '(res, self.np_expected4)\n', (4168, 4192), True, 'import numpy as np\n'), ((4632, 4667), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected1'], {}), '(res, self.np_expected1)\n', (4643, 4667), True, 'import numpy as np\n'), ((4777, 4812), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected2'], {}), '(res, self.np_expected2)\n', (4788, 4812), True, 'import numpy as np\n'), ((4897, 4932), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected3'], {}), '(res, self.np_expected3)\n', (4908, 4932), True, 'import numpy as np\n'), ((5017, 5052), 'numpy.allclose', 'np.allclose', (['res', 'self.np_expected4'], {}), '(res, self.np_expected4)\n', (5028, 5052), True, 'import numpy as np\n'), ((5716, 5759), 'numpy.fmin', 'np.fmin', (["self.inputs['X']", "self.inputs['Y']"], {}), "(self.inputs['X'], self.inputs['Y'])\n", (5723, 5759), True, 'import numpy as np\n'), ((7190, 7233), 'numpy.fmin', 'np.fmin', (["self.inputs['X']", "self.inputs['Y']"], {}), "(self.inputs['X'], self.inputs['Y'])\n", (7197, 7233), True, 'import numpy as np\n'), ((1050, 1072), 'numpy.random.rand', 'np.random.rand', (['(10)', '(15)'], {}), '(10, 15)\n', (1064, 1072), True, 'import numpy as np\n'), ((1114, 1136), 'numpy.random.rand', 'np.random.rand', (['(10)', '(15)'], {}), '(10, 15)\n', (1128, 1136), True, 'import numpy as np\n'), ((1178, 1196), 'numpy.random.rand', 'np.random.rand', (['(15)'], {}), '(15)\n', (1192, 1196), True, 'import numpy as np\n'), ((1238, 1267), 'numpy.array', 'np.array', (['[0, np.nan, np.nan]'], {}), '([0, np.nan, np.nan])\n', (1246, 1267), True, 'import numpy as np\n'), ((1307, 1337), 'numpy.array', 'np.array', (['[2, np.inf, -np.inf]'], {}), '([2, np.inf, -np.inf])\n', (1315, 1337), True, 'import numpy as np\n'), ((1377, 1396), 'numpy.array', 'np.array', (['[4, 1, 3]'], {}), '([4, 1, 3])\n', (1385, 1396), True, 'import numpy as np\n'), ((1804, 1827), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (1825, 1827), False, 'import paddle\n'), ((1870, 1893), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (1891, 1893), False, 'import paddle\n'), ((2420, 2443), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (2441, 2443), False, 'import paddle\n'), ((2486, 2509), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (2507, 2509), False, 'import paddle\n'), ((3032, 3055), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (3053, 3055), False, 'import paddle\n'), ((3098, 3121), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (3119, 3121), False, 'import paddle\n'), ((3634, 3657), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (3655, 3657), False, 'import paddle\n'), ((3700, 3723), 'paddle.static.Program', 'paddle.static.Program', ([], {}), '()\n', (3721, 3723), False, 'import paddle\n'), ((5448, 5483), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(1)', '[13, 17]'], {}), '(0.1, 1, [13, 17])\n', (5465, 5483), True, 'import numpy as np\n'), ((5516, 5551), 'numpy.random.choice', 'np.random.choice', (['[-1, 1]', '[13, 17]'], {}), '([-1, 1], [13, 17])\n', (5532, 5551), True, 'import numpy as np\n'), ((6894, 6929), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(1)', '[13, 17]'], {}), '(0.1, 1, [13, 17])\n', (6911, 6929), True, 'import numpy as np\n'), ((6962, 6997), 'numpy.random.choice', 'np.random.choice', (['[-1, 1]', '[13, 17]'], {}), '([-1, 1], [13, 17])\n', (6978, 6997), True, 'import numpy as np\n'), ((5592, 5627), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(1)', '[13, 17]'], {}), '(0.1, 1, [13, 17])\n', (5609, 5627), True, 'import numpy as np\n'), ((7038, 7073), 'numpy.random.uniform', 'np.random.uniform', (['(0.1)', '(1)', '[13, 17]'], {}), '(0.1, 1, [13, 17])\n', (7055, 7073), True, 'import numpy as np\n')] |
# Credit: https://stackoverflow.com/questions/28089942/difference-between-fill-and-expand-options-for-tkinter-pack-method/28090362
import tkinter as tk
import numpy as np
class Shadow(tk.Tk):
'''
Add shadow to a widget
This class adds a squared shadow to a widget. The size, the position, and
the color of the shadow can be customized at wills. Different shadow
behaviors can also be specified when hovering or clicking on the widget,
with binding autonomously performed when initializing the shadow. If the
widget has a 'command' function, it will be preserved when updating the
shadow appearance.
Note that enough space around the widget is required for the shadow to
correctly appear. Moreover, other widgets nearer than shadow's size will be
covered by the shadow.
'''
def __init__(self, widget, color='#212121', size=5, offset_x=0, offset_y=0,
onhover={}, onclick={}):
'''
Bind shadow to a widget.
Parameters
----------
widget : tkinter widget
Widgets to which shadow should be binded.
color : str, optional
Shadow color in hex notation. The default is '#212121'.
size : int or float, optional
Size of the shadow. If int type, it is the size of the shadow out
from the widget bounding box. If float type, it is a multiplier of
the widget bounding box (e.g. if size=2. then shadow is double in
size with respect to widget). The default is 5.
offset_x : int, optional
Offset by which shadow will be moved in the horizontal axis. If
positive, shadow moves toward right direction. The default is 0.
offset_y : int, optional
Offset by which shadow will be moved in the vertical axis. If
positive, shadow moves toward down direction. The default is 0.
onhover : dict, optional
Specify the behavior of the shadow when widget is hovered. Keys may
be: 'size', 'color', 'offset_x', 'offset_y'. If a key-value pair is
not provided, normal behavior is maintained for that key. The
default is {}.
onclick : dict, optional
Specify the behavior of the shadow when widget is clicked. Keys may
be: 'size', 'color', 'offset_x', 'offset_y'. If a key-value pair is
not provided, normal behavior is maintained for that key. The
default is {}.
Returns
-------
None.
'''
# Save parameters
self.widget = widget
self.normal_size = size
self.normal_color = color
self.normal_x = int(offset_x)
self.normal_y = int(offset_y)
self.onhover_size = onhover.get('size', size)
self.onhover_color = onhover.get('color', color)
self.onhover_x = onhover.get('offset_x', offset_x)
self.onhover_y = onhover.get('offset_y', offset_y)
self.onclick_size = onclick.get('size', size)
self.onclick_color = onclick.get('color', color)
self.onclick_x = onclick.get('offset_x', offset_x)
self.onclick_y = onclick.get('offset_y', offset_y)
# Get master and master's background
self.master = widget.master
self.to_rgb = tuple([el//257 for el in self.master.winfo_rgb(self.master.cget('bg'))])
# Start with normal view
self.__lines = []
self.__normal()
# Bind events to widget
self.widget.bind("<Enter>", self.__onhover, add='+')
self.widget.bind("<Leave>", self.__normal, add='+')
self.widget.bind("<ButtonPress-1>", self.__onclick, add='+')
self.widget.bind("<ButtonRelease-1>", self.__normal, add='+')
def __normal(self, event=None):
''' Update shadow to normal state '''
self.shadow_size = self.normal_size
self.shadow_color = self.normal_color
self.shadow_x = self.normal_x
self.shadow_y = self.normal_y
self.display()
def __onhover(self, event=None):
''' Update shadow to hovering state '''
self.shadow_size = self.onhover_size
self.shadow_color = self.onhover_color
self.shadow_x = self.onhover_x
self.shadow_y = self.onhover_y
self.display()
def __onclick(self, event=None):
''' Update shadow to clicked state '''
self.shadow_size = self.onclick_size
self.shadow_color = self.onclick_color
self.shadow_x = self.onclick_x
self.shadow_y = self.onclick_y
self.display()
def __destroy_lines(self):
''' Destroy previous shadow lines '''
for ll in self.__lines:
ll.destroy()
self.__lines = []
def display(self):
''' Destroy shadow according to selected configuration '''
def _rgb2hex(rgb):
"""
Translates an rgb tuple of int to hex color
"""
return "#%02x%02x%02x" % rgb
def _hex2rgb(h):
"""
Translates an hex color to rgb tuple of int
"""
h = h.strip('#')
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
# Destroy old lines
self.__destroy_lines()
# Get widget position and size
self.master.update_idletasks()
x0, y0, w, h = self.widget.winfo_x(), self.widget.winfo_y(), self.widget.winfo_width(), self.widget.winfo_height()
x1 = x0 + w - 1
y1 = y0 + h - 1
# Get shadow size from borders
if type(self.shadow_size) is int:
wh_shadow_size = self.shadow_size
else:
wh_shadow_size = min([int(dim * (self.shadow_size - 1)) for dim in (w,h)])
uldr_shadow_size = wh_shadow_size - self.shadow_y, wh_shadow_size - self.shadow_x, \
wh_shadow_size + self.shadow_y, wh_shadow_size + self.shadow_x
uldr_shadow_size = {k:v for k,v in zip('uldr', uldr_shadow_size)}
self.uldr_shadow_size = uldr_shadow_size
# Prepare shadow color
shadow_color = self.shadow_color
if not shadow_color.startswith('#'):
shadow_color = _rgb2hex(tuple([min(max(self.to_rgb) + 30, 255)] * 3))
self.from_rgb = _hex2rgb(shadow_color)
# Draw shadow lines
max_size = max(uldr_shadow_size.values())
diff_size = {k: max_size-ss for k,ss in uldr_shadow_size.items()}
rs = np.linspace(self.from_rgb[0], self.to_rgb[0], max_size, dtype=int)
gs = np.linspace(self.from_rgb[2], self.to_rgb[2], max_size, dtype=int)
bs = np.linspace(self.from_rgb[1], self.to_rgb[1], max_size, dtype=int)
rgbs = [_rgb2hex((r,g,b)) for r,g,b in zip(rs,gs,bs)]
for direction, size in uldr_shadow_size.items():
for ii, rgb in enumerate(rgbs):
ff = tk.Frame(self.master, bg=rgb)
self.__lines.append(ff)
if direction=='u' or direction=='d':
diff_1 = diff_size['l']
diff_2 = diff_size['r']
yy = y0-ii+1+diff_size[direction] if direction == 'u' else y1+ii-diff_size[direction]
if diff_1 <= ii < diff_size[direction]:
ff1 = tk.Frame(self.master, bg=rgb)
self.__lines.append(ff1)
ff1.configure(width=ii+1-diff_1, height=1)
ff1.place(x=x0-ii+1+diff_size['l'], y=yy)
if diff_2 <= ii < diff_size[direction]:
ff2 = tk.Frame(self.master, bg=rgb)
self.__lines.append(ff2)
ff2.configure(width=ii+1-diff_2, height=1)
ff2.place(x=x1, y=yy)
if ii >= diff_size[direction]:
ff.configure(width=x1-x0+ii*2-diff_size['l']-diff_size['r'], height=1)
ff.place(x=x0-ii+1+diff_size['l'], y=yy)
elif direction=='l' or direction=='r':
diff_1 = diff_size['u']
diff_2 = diff_size['d']
xx = x0-ii+1+diff_size[direction] if direction == 'l' else x1+ii-diff_size[direction]
if diff_1 <= ii < diff_size[direction]:
ff1 = tk.Frame(self.master, bg=rgb)
self.__lines.append(ff1)
ff1.configure(width=1, height=ii+1-diff_1)
ff1.place(x=xx, y=y0-ii+1+diff_size['u'])
if diff_2 <= ii < diff_size[direction]:
ff2 = tk.Frame(self.master, bg=rgb)
self.__lines.append(ff2)
ff2.configure(width=1, height=ii+1-diff_2)
ff2.place(x=xx, y=y1)
if ii >= diff_size[direction]:
ff.configure(width=1, height=y1-y0+ii*2-diff_size['u']-diff_size['d'])
ff.place(x=xx, y=y0-ii+1+diff_size['u'])
| [
"numpy.linspace",
"tkinter.Frame"
] | [((6587, 6653), 'numpy.linspace', 'np.linspace', (['self.from_rgb[0]', 'self.to_rgb[0]', 'max_size'], {'dtype': 'int'}), '(self.from_rgb[0], self.to_rgb[0], max_size, dtype=int)\n', (6598, 6653), True, 'import numpy as np\n'), ((6667, 6733), 'numpy.linspace', 'np.linspace', (['self.from_rgb[2]', 'self.to_rgb[2]', 'max_size'], {'dtype': 'int'}), '(self.from_rgb[2], self.to_rgb[2], max_size, dtype=int)\n', (6678, 6733), True, 'import numpy as np\n'), ((6747, 6813), 'numpy.linspace', 'np.linspace', (['self.from_rgb[1]', 'self.to_rgb[1]', 'max_size'], {'dtype': 'int'}), '(self.from_rgb[1], self.to_rgb[1], max_size, dtype=int)\n', (6758, 6813), True, 'import numpy as np\n'), ((6998, 7027), 'tkinter.Frame', 'tk.Frame', (['self.master'], {'bg': 'rgb'}), '(self.master, bg=rgb)\n', (7006, 7027), True, 'import tkinter as tk\n'), ((7405, 7434), 'tkinter.Frame', 'tk.Frame', (['self.master'], {'bg': 'rgb'}), '(self.master, bg=rgb)\n', (7413, 7434), True, 'import tkinter as tk\n'), ((7707, 7736), 'tkinter.Frame', 'tk.Frame', (['self.master'], {'bg': 'rgb'}), '(self.master, bg=rgb)\n', (7715, 7736), True, 'import tkinter as tk\n'), ((8449, 8478), 'tkinter.Frame', 'tk.Frame', (['self.master'], {'bg': 'rgb'}), '(self.master, bg=rgb)\n', (8457, 8478), True, 'import tkinter as tk\n'), ((8751, 8780), 'tkinter.Frame', 'tk.Frame', (['self.master'], {'bg': 'rgb'}), '(self.master, bg=rgb)\n', (8759, 8780), True, 'import tkinter as tk\n')] |
import numpy as np
from ..env import ParasolEnvironment
__all__ = ['Rotation']
def shape_check(mats, shapes):
try:
for i in range(len(mats)):
mat, shape = mats[i], shapes[i]
for j in range(len(mat.shape)):
if mat.shape[j] != shape[j]:
return False
return True
except IndexError:
return False
# from pylds
def random_rotation(dim):
if dim == 1:
return np.random.rand() * np.eye(1)
theta = np.pi / 30
rot = np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]])
out = np.zeros((dim, dim))
out[:2, :2] = rot
q = np.linalg.qr(np.random.randn(dim, dim))[0]
return q.dot(out).dot(q.T)
class Rotation(ParasolEnvironment):
environment_name = 'Rotation'
def __init__(self, dims=(2, 2, 2), horizon=100, init=None, dyn=None, obs=None, **kwargs):
self.ds, self.do, self.da = dims
ds, do, da = self.ds, self.do, self.da
self.horizon = H = horizon + 1
if init:
assert shape_check(init, ((ds,), (ds, ds)))
self.mu0, self.Q0 = init
else:
self.mu0, self.Q0 = np.ones(ds), 0.01 * np.eye(ds)
if dyn:
assert shape_check(dyn, ((H-1, ds, ds), (H-1, ds, da), (H-1, ds, ds)))
self.A, self.B, self.Q = dyn
else:
self.A = 0.99 * np.tile(random_rotation(ds), [H-1, 1, 1])
self.B = 0.1 * np.tile(np.random.randn(ds, da), [H-1, 1, 1])
self.Q = 0.01 * np.tile(np.eye(ds), [H-1, 1, 1])
if obs:
assert shape_check(obs, ((H, do, ds), (H, do, do)))
self.C, self.R = obs
else:
self.C = np.tile(np.eye(ds), [H, 1, 1])
self.R = 1e-2 * np.tile(np.eye(do), [H, 1, 1])
super(Rotation, self).__init__(**kwargs)
def config(self):
return {
'init': (self.mu0, self.Q0),
'dyn': (self.A, self.B, self.Q),
'obs': (self.C, self.R),
'sliding_window': self.sliding_window
}
def make_summary(self, *args, **kwargs):
pass
def state_dim(self):
return self.ds
def action_dim(self):
return self.da
def _observe(self):
s, _, t = self._curr_state
mean, cov = self.C[t].dot(s), self.R[t]
return np.random.multivariate_normal(mean, cov)
def reset(self):
s0 = np.random.multivariate_normal(self.mu0, self.Q0)
self._curr_state = [s0, np.zeros(self.da), 0]
return self.observe()
def step(self, action):
self._curr_state = self.dynamics(self._curr_state, action)
done = (self._curr_state[-1] == self.horizon-1)
return self.observe(), 0.0, done, {}
def get_state_dim(self):
return self.do
def get_action_dim(self):
return self.da
def render(self):
pass
def torque_matrix(self):
return np.eye(self.da)
def dynamics(self, state, a):
s, _, t = state
mean, cov = self.A[t].dot(s) + self.B[t].dot(a), self.Q[t]
sp = np.random.multivariate_normal(mean, cov)
return [sp, a, t+1]
def start_recording(self):
pass
def grab_frame(self):
pass
def stop_recording(self):
pass
| [
"numpy.random.randn",
"numpy.zeros",
"numpy.ones",
"numpy.sin",
"numpy.random.multivariate_normal",
"numpy.cos",
"numpy.random.rand",
"numpy.eye"
] | [((628, 648), 'numpy.zeros', 'np.zeros', (['(dim, dim)'], {}), '((dim, dim))\n', (636, 648), True, 'import numpy as np\n'), ((2387, 2427), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean', 'cov'], {}), '(mean, cov)\n', (2416, 2427), True, 'import numpy as np\n'), ((2463, 2511), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['self.mu0', 'self.Q0'], {}), '(self.mu0, self.Q0)\n', (2492, 2511), True, 'import numpy as np\n'), ((2981, 2996), 'numpy.eye', 'np.eye', (['self.da'], {}), '(self.da)\n', (2987, 2996), True, 'import numpy as np\n'), ((3136, 3176), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mean', 'cov'], {}), '(mean, cov)\n', (3165, 3176), True, 'import numpy as np\n'), ((459, 475), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (473, 475), True, 'import numpy as np\n'), ((478, 487), 'numpy.eye', 'np.eye', (['(1)'], {}), '(1)\n', (484, 487), True, 'import numpy as np\n'), ((692, 717), 'numpy.random.randn', 'np.random.randn', (['dim', 'dim'], {}), '(dim, dim)\n', (707, 717), True, 'import numpy as np\n'), ((2544, 2561), 'numpy.zeros', 'np.zeros', (['self.da'], {}), '(self.da)\n', (2552, 2561), True, 'import numpy as np\n'), ((533, 546), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (539, 546), True, 'import numpy as np\n'), ((586, 599), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (592, 599), True, 'import numpy as np\n'), ((601, 614), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (607, 614), True, 'import numpy as np\n'), ((1205, 1216), 'numpy.ones', 'np.ones', (['ds'], {}), '(ds)\n', (1212, 1216), True, 'import numpy as np\n'), ((1752, 1762), 'numpy.eye', 'np.eye', (['ds'], {}), '(ds)\n', (1758, 1762), True, 'import numpy as np\n'), ((549, 562), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (555, 562), True, 'import numpy as np\n'), ((1225, 1235), 'numpy.eye', 'np.eye', (['ds'], {}), '(ds)\n', (1231, 1235), True, 'import numpy as np\n'), ((1496, 1519), 'numpy.random.randn', 'np.random.randn', (['ds', 'da'], {}), '(ds, da)\n', (1511, 1519), True, 'import numpy as np\n'), ((1570, 1580), 'numpy.eye', 'np.eye', (['ds'], {}), '(ds)\n', (1576, 1580), True, 'import numpy as np\n'), ((1811, 1821), 'numpy.eye', 'np.eye', (['do'], {}), '(do)\n', (1817, 1821), True, 'import numpy as np\n')] |
# #########################################################################
# Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
# #
# See LICENSE file. #
# #########################################################################
"""
This module is a suite of utility functions.
"""
import tifffile as tf
import pylibconfig2 as cfg
import numpy as np
import os
import logging
import stat
from functools import reduce
__author__ = "<NAME>"
__copyright__ = "Copyright (c), UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = ['get_logger',
'read_tif',
'save_tif',
'read_config',
'prepare_config',
'get_good_dim',
'binning',
'get_centered',
'get_centered_both',
'get_zero_padded_centered',
'adjust_dimensions',
'crop_center',
'get_norm',
'flip',
'gaussian',
'gauss_conv_fft',
'shrink_wrap',
'read_results',
'zero_phase',
'sum_phase_tight_support',
'get_metric',
'save_metrics',
'write_plot_errors',
'save_results',
'sub_pixel_shift',
'arr_property',
'get_gpu_load',
'get_gpu_distribution',
'measure' ]
def get_logger(name, ldir=''):
"""
Creates looger instance that will write to default.log file in a given directory.
Parameters
----------
name : str
logger name
ldir : str
directory where to create log file
Returns
-------
logger : logger
logger object from logging module
"""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
log_file = os.path.join(ldir, 'default.log')
fh = logging.FileHandler(log_file)
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
def read_tif(filename):
"""
This method reads tif type file and returns the data as array.
Parameters
----------
filename : str
tif format file name
Returns
-------
data : ndarray
an array containing the data parsed from the file
"""
ar = tf.imread(filename).transpose()
return ar
def save_tif(arr, filename):
"""
This method saves array in tif format file.
Parameters
----------
arr : ndarray
array to save
filename : str
tif format file name
Returns
-------
nothing
"""
tf.imsave(filename, arr.transpose().astype(np.float32))
def read_config(config):
"""
This function gets configuration file. It checks if the file exists and parses it into an object.
Parameters
----------
config : str
configuration file name, including path
Returns
-------
config_map : Config object
a Config containing parsed configuration, None if the given file does not exist
"""
if os.path.isfile(config):
with open(config, 'r') as f:
config_map = cfg.Config(f.read())
return config_map;
else:
return None
def prepare_config(file):
algs = []
algs_repeats = []
def parse_alg_token(s):
items = s.replace('(','').replace(')','').split(',')
repeat = int(items[0])
items = items[1:]
for j in range(repeat):
for i in range(len(items)):
if (i + 1) % 2 == 0:
algs_repeats.append(int(items[i]))
else:
algs.append(items[i][1:-1])
with open(file, 'r') as f:
lines = f.readlines()
f.close()
lines_c = []
starts = []
ends = []
for i in range(len(lines)):
if '=' in lines[i]:
starts.append(i)
if i != 0:
ends.append(i-1)
ends.append(len(lines)-1)
for i in range(len(starts)):
line_c = ''
for j in range(starts[i],ends[i]+1):
line_c += lines[j]
lines_c.append(line_c.replace(" ", ""))
# prepare algorithm sequence, triggers, and remove " around strings
for i in range(len(lines_c)):
tokens = []
if lines_c[i].startswith('algorithm_sequence'):
line = lines_c[i][20 : -2] # remove 'algorithm_sequence=' and outer ()
if line.startswith('('):
while (line.find('))') > 0):
ind = line.find('))')
token = line[1 : ind + 1]
tokens.append(token)
line = line[ind + 2 :]
if line.startswith(','):
line = line[1 :]
else:
tokens.append(line)
for t in tokens:
parse_alg_token(t)
lines_c.append('algs=' + str(tuple(algs)) + '\n')
lines_c.append('algs_repeats=' + str(tuple(algs_repeats)) + '\n')
lines_c.append('num_iter=' + str(sum(algs_repeats)))
tmp_file = file + '_tmp'
open(tmp_file, 'w').close()
with open(tmp_file, 'w') as tf:
for line in lines_c:
tf.write(line.replace('"','').replace("'",""))
tf.close()
def get_good_dim(dim):
"""
This function calculates the dimension supported by opencl library (i.e. is multiplier of 2, 3, or 5) and is closest to the given starting dimension.
If the dimension is not supported the function adds 1 and verifies the new dimension. It iterates until it finds supported value.
Parameters
----------
dim : int
initial dimension
Returns
-------
new_dim : int
a dimension that is supported by the opencl library, and closest to the original dimension
"""
def is_correct(x):
sub = x
if sub % 3 == 0:
sub = sub / 3
if sub % 3 == 0:
sub = sub / 3
if sub % 5 == 0:
sub = sub / 5
while sub % 2 == 0:
sub = sub / 2
return sub == 1
new_dim = dim
if new_dim % 2 == 1:
new_dim += 1
while not is_correct(new_dim):
new_dim += 2
return new_dim
def binning(array, binsizes):
"""
This function does the binning of the array. The array is binned in each dimension by the corresponding binsizes elements.
If binsizes list is shorter than the array dimensions, the remaining dimensions are not binned.
Parameters
----------
array : ndarray
the original array to be binned
binsizes : list
a list defining binning factors for corresponding dimensions
Returns
-------
binned_array : ndarray
binned array
"""
data_dims = array.shape
# trim array
for ax in range(len(binsizes)):
cut_slices = range(data_dims[ax] - data_dims[ax] % binsizes[ax], data_dims[ax])
array = np.delete(array, cut_slices, ax)
binned_array = array
new_shape = list(array.shape)
for ax in range(len(binsizes)):
if binsizes[ax] > 1:
new_shape[ax] = binsizes[ax]
new_shape.insert(ax, int(array.shape[ax] / binsizes[ax]))
binned_array = np.reshape(binned_array, tuple(new_shape))
binned_array = np.sum(binned_array, axis=ax + 1)
new_shape = list(binned_array.shape)
return binned_array
def get_centered(arr, center_shift):
"""
This function finds maximum value in the array, and puts it in a center of a new array. If center_shift is not zeros, the array will be shifted accordingly. The shifted elements are rolled into the other end of array.
Parameters
----------
arr : array
the original array to be centered
center_shift : list
a list defining shift of the center
Returns
-------
ndarray
centered array
"""
max_coordinates = list(np.unravel_index(np.argmax(arr), arr.shape))
max_coordinates = np.add(max_coordinates, center_shift)
shape = arr.shape
centered = arr
for i in range(len(max_coordinates)):
centered = np.roll(centered, int(shape[i] / 2) - max_coordinates[i], i)
return centered
def get_centered_both(arr, support):
"""
This function finds maximum value in the array, and puts it in a center of a new array. The support array will be shifted the same way. The shifted elements are rolled into the other end of array.
Parameters
----------
arr : array
the original array to be centered
support : array
the associated array to be shifted the same way centered array is
Returns
-------
centered, centered_supp : ndarray, ndarray
the centered arrays
"""
max_coordinates = list(np.unravel_index(np.argmax(arr), arr.shape))
shape = arr.shape
centered = arr
centered_supp = support
for i in range(len(max_coordinates)):
centered = np.roll(centered, int(shape[i] / 2) - max_coordinates[i], i)
centered_supp = np.roll(centered_supp, int(shape[i] / 2) - max_coordinates[i], i)
return centered, centered_supp
def get_zero_padded_centered(arr, new_shape):
"""
This function pads the array with zeros to the new shape with the array in the center.
Parameters
----------
arr : array
the original array to be padded
new_shape : tuple
new dimensions
Returns
-------
centered : array
the zero padded centered array
"""
shape = arr.shape
pad = []
c_vals = []
for i in range(len(new_shape)):
pad.append((0, new_shape[i] - shape[i]))
c_vals.append((0.0, 0.0))
arr = np.lib.pad(arr, (pad), 'constant', constant_values=c_vals)
centered = arr
for i in range(len(new_shape)):
centered = np.roll(centered, int((new_shape[i] - shape[i] + 1) / 2), i)
return centered
def adjust_dimensions(arr, pads):
"""
This function adds to or subtracts from each dimension of the array elements defined by pad. If the pad is positive, the array is padded in this dimension. If the pad is negative, the array is cropped.
The dimensions of the new array is then adjusted to be supported by the opencl library.
Parameters
----------
arr : ndarray
the array to pad/crop
pad : list
list of three pad values, for each dimension
Returns
-------
adjusted : ndarray
the padded/cropped array
"""
old_dims = arr.shape
start = []
stop = []
for i in range(len(old_dims)):
pad = pads[i]
first = max(0, -pad[0])
last = old_dims[i] - max(0, -pad[1])
if first >= last:
print ('the crop exceeds size, please change the crop and run again')
return None
else:
start.append(first)
stop.append(last)
cropped = arr[ start[0]:stop[0], start[1]:stop[1], start[2]:stop[2] ]
dims = cropped.shape
c_vals = []
new_pad = []
for i in range(len(dims)):
pad = pads[i]
# find a good dimension and find padding
temp_dim = old_dims[i] + pad[0] + pad[1]
new_dim = get_good_dim(temp_dim)
added = new_dim - temp_dim
# if the pad is positive
pad_front = max(0, pad[0]) + int(added / 2)
pad_end = new_dim - dims[i] - pad_front
new_pad.append((pad_front, pad_end))
c_vals.append((0.0, 0.0))
adjusted = np.pad(cropped, new_pad, 'constant', constant_values=c_vals)
return adjusted
def crop_center(arr, new_size):
"""
This function crops the array to the new size, leaving the array in the center.
The dimensions of the new array is then adjusted to be supported by the opencl library.
Parameters
----------
arr : ndarray
the array to crop
new_size : tuple
new size
Returns
-------
cropped : ndarray
the cropped array
"""
size = arr.shape
cropped = arr
for i in range(len(size)):
crop_front = int((size[i] - new_size[i]) / 2)
crop_end = crop_front + new_size[i]
splitted = np.split(cropped, [crop_front, crop_end], axis=i)
cropped = splitted[1]
return cropped
def get_norm(arr):
"""
Used in development. Returns array norm.
Parameters
----------
arr : ndarray
the array to calculate norm
Returns
-------
float
the array norm
"""
return sum(sum(sum(abs(arr) ** 2)))
def flip(m, axis):
"""
Copied from numpy 1.12.0.
"""
if not hasattr(m, 'ndim'):
m = np.asarray(m)
indexer = [slice(None)] * m.ndim
try:
indexer[axis] = slice(None, None, -1)
except IndexError:
raise ValueError("axis=%i is invalid for the %i-dimensional input array"
% (axis, m.ndim))
return m[tuple(indexer)]
def gaussian(shape, sigmas, alpha=1):
"""
Calculates Gaussian distribution grid in ginven dimensions.
Parameters
----------
shape : tuple
shape of the grid
sigmas : list
sigmas in all dimensions
alpha : float
a multiplier
Returns
-------
grid : ndarray
Gaussian distribution grid
"""
grid = np.full(shape, 1.0)
for i in range(len(shape)):
# prepare indexes for tile and transpose
tile_shape = list(shape)
tile_shape.pop(i)
tile_shape.append(1)
trans_shape = list(range(len(shape) - 1))
trans_shape.insert(i, len(shape) - 1)
multiplier = - 0.5 * alpha / pow(sigmas[i], 2)
line = np.linspace(-(shape[i] - 1) / 2.0, (shape[i] - 1) / 2.0, shape[i])
gi = np.tile(line, tile_shape)
gi = np.transpose(gi, tuple(trans_shape))
exponent = np.power(gi, 2) * multiplier
gi = np.exp(exponent)
grid = grid * gi
grid_total = np.sum(grid)
return grid / grid_total
def gauss_conv_fft(arr, sigmas):
"""
Calculates convolution of array with the Gaussian.
A Guassian distribution grid is calculated with the array dimensions. Fourier transform of the array is multiplied by the grid and and inverse transformed. A correction is calculated and applied.
Parameters
----------
arr : ndarray
subject array
sigmas : list
sigmas in all dimensions
Returns
-------
convag : ndarray
convolution array
"""
arr_sum = np.sum(abs(arr))
arr_f = np.fft.ifftshift(np.fft.fftn(np.fft.ifftshift(arr)))
shape = list(arr.shape)
for i in range(len(sigmas)):
sigmas[i] = shape[i] / 2.0 / np.pi / sigmas[i]
convag = arr_f * gaussian(shape, sigmas)
convag = np.fft.ifftshift(np.fft.ifftn(np.fft.ifftshift(convag)))
convag = convag.real
convag = np.clip(convag, 0, None)
correction = arr_sum / np.sum(convag)
convag *= correction
return convag
def shrink_wrap(arr, threshold, sigma, type='gauss'):
"""
Calculates support array.
Parameters
----------
arr : ndarray
subject array
threshold : float
support is formed by points above this valuue
sigmas : list
sigmas in all dimensions
type : str
a type of algorithm to apply to calculate the support, currently supporting 'gauss'
Returns
-------
support : ndarray
support array
"""
sigmas = [sigma] * len(arr.shape)
if type == 'gauss':
convag = gauss_conv_fft(abs(arr), sigmas)
max_convag = np.amax(convag)
convag = convag / max_convag
support = np.where(convag >= threshold, 1, 0)
return support
else:
return None
def read_results(read_dir):
"""
Reads results and returns array representation.
Parameters
----------
read_dir : str
directory to read the results from
Returns
-------
image, support, coh : ndarray, ndarray, ndarray (or None)
image, support, and coherence arrays
"""
try:
imagefile = os.path.join(read_dir, 'image.npy')
image = np.load(imagefile)
except:
image = None
try:
supportfile = os.path.join(read_dir, 'support.npy')
support = np.load(supportfile)
except:
support = None
try:
cohfile = os.path.join(read_dir, 'coherence.npy')
coh = np.load(cohfile)
except:
coh = None
return image, support, coh
def zero_phase(arr, val=0):
"""
Calculates average phase of the input array bounded by very tight support. Shifts the phases in the array by avarage plus given value.
Parameters
----------
arr : ndarray
array to shift the phase
val : float
a value to add to shift
Returns
-------
ndarray
array with modified phase
"""
ph = np.angle(arr)
support = shrink_wrap(abs(arr), .2, .5) #get just the crystal, i.e very tight support
avg_ph = np.sum(ph * support)/np.sum(support)
ph = ph - avg_ph + val
return abs(arr) * np.exp(1j * ph)
def sum_phase_tight_support(arr):
"""
Calculates average phase of the input array bounded by very tight support. Shifts the phases in the array by avarage plus given value.
Parameters
----------
arr : ndarray
array to shift the phase
val : float
a value to add to shift
Returns
-------
ndarray
array with modified phase
"""
arr = zero_phase(arr)
ph = np.arctan2(arr.imag, arr.real)
support = shrink_wrap(abs(arr), .2, .5)
return sum( abs(ph * support))
def get_metric(image, errs):
"""
Callculates array characteristic based on various formulas.
Parameters
----------
arr : ndarray
array to get characteristic
errs : list
list of "chi" error by iteration
Returns
-------
metric : dict
dictionary with all metric
"""
metric = {}
metric['chi'] = errs[-1]
metric['sharpness'] = np.sum(pow(abs(image), 4)).item()
metric['summed_phase'] = np.sum(sum_phase_tight_support(image)).item()
metric['area'] = np.sum(shrink_wrap(image, .2, .5)).item()
return metric
def save_metrics(errs, dir, metrics=None):
"""
Saves arrays metrics and errors by iterations in text file.
Parameters
----------
errs : list
list of "chi" error by iteration
dir : str
directory to write the file containing array metrics
metrics : dict
dictionary with metric type keys, and metric values
Returns
-------
nothing
"""
metric_file = os.path.join(dir, 'summary')
if os.path.isfile(metric_file):
os.remove(metric_file)
with open(metric_file, 'a') as f:
if metrics is not None:
f.write('metric result\n')
for key in metrics:
value = metrics[key]
f.write(key + ' = ' + str(value) + '\n')
f.write('\nerrors by iteration\n')
for er in errs:
f.write(str(er) + ' ')
f.close()
def write_plot_errors(save_dir):
"""
Creates python executable that draw plot of error by iteration. It assumes that the given directory contains "errors.npy" file
Parameters
----------
errs : list
list of "chi" error by iteration
dir : str
directory to write the file containing array metrics
metrics : dict
dictionary with metric type keys, and metric values
Returns
-------
nothing
"""
plot_file = os.path.join(save_dir, 'plot_errors.py')
f = open(plot_file, 'w+')
f.write("#! /usr/bin/env python\n")
f.write("import matplotlib.pyplot as plt\n")
f.write("import numpy as np\n")
f.write("import sys\n")
f.write("import os\n")
f.write("current_dir = sys.path[0]\n")
f.write("errs = np.load(os.path.join(current_dir, 'errors.npy')).tolist()\n")
f.write("errs.pop(0)\n")
f.write("plt.plot(errs)\n")
f.write("plt.ylabel('errors')\n")
f.write("plt.show()")
f.close()
st = os.stat(plot_file)
os.chmod(plot_file, st.st_mode | stat.S_IEXEC)
def save_results(image, support, coh, errs, flow, iter_array, save_dir, metric=None):
"""
Saves results of reconstruction. Saves the following files: image.np, support.npy, errors.npy, optionally coherence.npy, plot_errors.py, graph.npy, flow.npy, iter_array.npy
Parameters
----------
image : ndarray
reconstructed image array
support : ndarray
support array related to the image
coh : ndarray
coherence array when pcdi feature is active, None otherwise
errs : ndarray
errors "chi" by iterations
flow : ndarray
for development, contains functions that can be activated in fast module during iteration
iter_array : ndarray
for development, matrix indicating which function in fast module was active by iteration
save_dir : str
directory to write the files
metrics : dict
dictionary with metric type keys, and metric values
Returns
-------
nothing
"""
if not os.path.exists(save_dir):
os.makedirs(save_dir)
image_file = os.path.join(save_dir, 'image')
np.save(image_file, image)
support_file = os.path.join(save_dir, 'support')
np.save(support_file, support)
errs_file = os.path.join(save_dir, 'errors')
np.save(errs_file, errs)
if not coh is None:
coh_file = os.path.join(save_dir, 'coherence')
np.save(coh_file, coh)
write_plot_errors(save_dir)
graph_dir = os.path.join(save_dir, 'graph')
if not os.path.exists(graph_dir):
os.makedirs(graph_dir)
flow_file = os.path.join(graph_dir, 'flow')
np.save(flow_file, np.asarray(flow))
iter_array_file = os.path.join(graph_dir, 'iter_array')
np.save(iter_array_file, iter_array)
save_metrics(errs, save_dir, metric)
def sub_pixel_shift(arr, row_shift, col_shift, z_shift):
"""
Shifts pixels in a regularly sampled LR image with a subpixel precision according to local gradient.
Parameters
----------
arr : ndarray
array to shift
row_shift, col_shift, z_shift : float, float, float
shift in each dimension
Returns
-------
ndarray
shifted array
"""
buf2ft = np.fft.fftn(arr)
shape = arr.shape
Nr = np.fft.ifftshift(np.array(list(range(-int(np.floor(shape[0] / 2)), shape[0] - int(np.floor(shape[0] / 2))))))
Nc = np.fft.ifftshift(np.array(list(range(-int(np.floor(shape[1] / 2)), shape[1] - int(np.floor(shape[1] / 2))))))
Nz = np.fft.ifftshift(np.array(list(range(-int(np.floor(shape[2] / 2)), shape[2] - int(np.floor(shape[2] / 2))))))
[Nc, Nr, Nz] = np.meshgrid(Nc, Nr, Nz)
Greg = buf2ft * np.exp(1j * 2 * np.pi * (-row_shift * Nr / shape[0] - col_shift * Nc / shape[1] - z_shift * Nz / shape[2]))
return np.fft.ifftn(Greg)
def arr_property(arr):
"""
Used only in development. Prints max value of the array and max coordinates.
Parameters
----------
arr : ndarray
array to find max
Returns
-------
nothing
"""
arr1 = abs(arr)
print ('norm', np.sum(pow(abs(arr),2)))
max_coordinates = list(np.unravel_index(np.argmax(arr1), arr.shape))
print ('max coords, value', max_coordinates, arr[max_coordinates[0], max_coordinates[1],max_coordinates[2]])
def get_gpu_load(mem_size, ids):
"""
This function is only used when running on Linux OS. The GPUtil module is not supported on mac.
This function finds available GPU memory in each GPU that id is included in ids list. It calculates how many reconstruction can fit in each GPU available memory.
Parameters
----------
mem_size : int
array size
ids : list
list of GPU ids user configured for use
Returns
-------
available : list
list of available runs aligned with the GPU id list
"""
import GPUtil
gpus = GPUtil.getGPUs()
total_avail = 0
available_dir = {}
for gpu in gpus:
if gpu.id in ids:
free_mem = gpu.memoryFree
avail_runs = int(free_mem / mem_size)
if avail_runs > 0:
total_avail += avail_runs
available_dir[gpu.id] = avail_runs
available = []
for id in ids:
try:
avail_runs = available_dir[id]
except:
avail_runs = 0
available.append(avail_runs)
return available
def get_gpu_distribution(runs, available):
"""
Finds how to distribute the available runs to perform the given number of runs.
Parameters
----------
runs : int
number of reconstruction requested
available : list
list of available runs aligned with the GPU id list
Returns
-------
distributed : list
list of runs aligned with the GPU id list, the runs are equally distributed across the GPUs
"""
all_avail = reduce((lambda x,y: x+y), available)
distributed = [0] * len(available)
sum_distr = 0
while runs > sum_distr and all_avail > 0:
# balance distribution
for i in range(len(available)):
if available[i] > 0:
available[i] -= 1
all_avail -= 1
distributed[i] += 1
sum_distr += 1
if sum_distr == runs:
break
return distributed
def estimate_no_proc(arr_size, factor):
"""
Estimates number of processes the prep can be run on. Determined by number of available cpus and size of array
Parameters
----------
arr_size : int
size of array
factor : int
an estimate of how much memory is required to process comparing to array size
Returns
-------
number of processes
"""
from multiprocessing import cpu_count
import psutil
ncpu = cpu_count()
freemem = psutil.virtual_memory().available
nmem = freemem / (factor * arr_size)
# decide what limits, ncpu or nmem
if nmem > ncpu:
return ncpu
else:
return int(nmem)
# supposedly this is faster than np.roll or scipy interpolation shift.
# https://stackoverflow.com/questions/30399534/shift-elements-in-a-numpy-array
def fast_shift(arr, shifty, fill_val=0):
"""
Shifts array by given numbers for shift in each dimension.
Parameters
----------
arr : array
array to shift
shifty : list
a list of integer to shift the array in each dimension
fill_val : float
values to fill emptied space
Returns
-------
result : array
shifted array
"""
dims = arr.shape
result = np.ones_like(arr)
result *= fill_val
result_slices = []
arr_slices = []
for n in range(len(dims)):
if shifty[n] > 0:
result_slices.append(slice(shifty[n], dims[n]))
arr_slices.append(slice(0, -shifty[n]))
elif shifty[n] < 0:
result_slices.append(slice(0, shifty[n]))
arr_slices.append(slice(-shifty[n], dims[n]))
else:
result_slices.append(slice(0, dims[n]))
arr_slices.append(slice(0, dims[n]))
result_slices = tuple(result_slices)
arr_slices = tuple(arr_slices)
result[result_slices] = arr[arr_slices]
return result
def shift_to_ref_array(fft_ref, array):
"""
Returns an array shifted to align with ref, only single pixel resolution pass fft of ref array to save doing that a lot.
Parameters
----------
fft_ref : array
Fourier transform of reference array
array : array
array to align with reference array
Returns
-------
shifted_array : array
array shifted to be aligned with reference array
"""
# get cross correlation and pixel shift
fft_array = np.fft.fftn(array)
cross_correlation = np.fft.ifftn(fft_ref * np.conj(fft_array))
corelated = np.array(cross_correlation.shape)
amp = np.abs(cross_correlation)
intshift = np.unravel_index(amp.argmax(), corelated)
shifted = np.array(intshift)
pixelshift = np.where(shifted >= corelated / 2, shifted - corelated, shifted)
shifted_arr = fast_shift(array, pixelshift)
del cross_correlation
del fft_array
return shifted_arr
#https://stackoverflow.com/questions/51503672/decorator-for-timeit-timeit-method/51503837#51503837
from functools import wraps
from time import time
def measure(func):
@wraps(func)
def _time_it(*args, **kwargs):
start = int(round(time() * 1000))
try:
return func(*args, **kwargs)
finally:
end_ = int(round(time() * 1000)) - start
print("Total execution time: {end_ if end_ > 0 else 0} ms")
return _time_it
| [
"numpy.load",
"GPUtil.getGPUs",
"numpy.sum",
"numpy.arctan2",
"numpy.abs",
"os.remove",
"psutil.virtual_memory",
"numpy.angle",
"numpy.argmax",
"numpy.floor",
"numpy.clip",
"logging.Formatter",
"os.path.isfile",
"numpy.tile",
"numpy.exp",
"numpy.lib.pad",
"os.path.join",
"multiproc... | [((1839, 1862), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (1856, 1862), False, 'import logging\n'), ((1913, 1946), 'os.path.join', 'os.path.join', (['ldir', '"""default.log"""'], {}), "(ldir, 'default.log')\n", (1925, 1946), False, 'import os\n'), ((1956, 1985), 'logging.FileHandler', 'logging.FileHandler', (['log_file'], {}), '(log_file)\n', (1975, 1985), False, 'import logging\n'), ((2033, 2106), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'], {}), "('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (2050, 2106), False, 'import logging\n'), ((3266, 3288), 'os.path.isfile', 'os.path.isfile', (['config'], {}), '(config)\n', (3280, 3288), False, 'import os\n'), ((8232, 8269), 'numpy.add', 'np.add', (['max_coordinates', 'center_shift'], {}), '(max_coordinates, center_shift)\n', (8238, 8269), True, 'import numpy as np\n'), ((9976, 10032), 'numpy.lib.pad', 'np.lib.pad', (['arr', 'pad', '"""constant"""'], {'constant_values': 'c_vals'}), "(arr, pad, 'constant', constant_values=c_vals)\n", (9986, 10032), True, 'import numpy as np\n'), ((11774, 11834), 'numpy.pad', 'np.pad', (['cropped', 'new_pad', '"""constant"""'], {'constant_values': 'c_vals'}), "(cropped, new_pad, 'constant', constant_values=c_vals)\n", (11780, 11834), True, 'import numpy as np\n'), ((13616, 13635), 'numpy.full', 'np.full', (['shape', '(1.0)'], {}), '(shape, 1.0)\n', (13623, 13635), True, 'import numpy as np\n'), ((14249, 14261), 'numpy.sum', 'np.sum', (['grid'], {}), '(grid)\n', (14255, 14261), True, 'import numpy as np\n'), ((15165, 15189), 'numpy.clip', 'np.clip', (['convag', '(0)', 'None'], {}), '(convag, 0, None)\n', (15172, 15189), True, 'import numpy as np\n'), ((17257, 17270), 'numpy.angle', 'np.angle', (['arr'], {}), '(arr)\n', (17265, 17270), True, 'import numpy as np\n'), ((17917, 17947), 'numpy.arctan2', 'np.arctan2', (['arr.imag', 'arr.real'], {}), '(arr.imag, arr.real)\n', (17927, 17947), True, 'import numpy as np\n'), ((19099, 19127), 'os.path.join', 'os.path.join', (['dir', '"""summary"""'], {}), "(dir, 'summary')\n", (19111, 19127), False, 'import os\n'), ((19135, 19162), 'os.path.isfile', 'os.path.isfile', (['metric_file'], {}), '(metric_file)\n', (19149, 19162), False, 'import os\n'), ((20064, 20104), 'os.path.join', 'os.path.join', (['save_dir', '"""plot_errors.py"""'], {}), "(save_dir, 'plot_errors.py')\n", (20076, 20104), False, 'import os\n'), ((20588, 20606), 'os.stat', 'os.stat', (['plot_file'], {}), '(plot_file)\n', (20595, 20606), False, 'import os\n'), ((20611, 20657), 'os.chmod', 'os.chmod', (['plot_file', '(st.st_mode | stat.S_IEXEC)'], {}), '(plot_file, st.st_mode | stat.S_IEXEC)\n', (20619, 20657), False, 'import os\n'), ((21808, 21839), 'os.path.join', 'os.path.join', (['save_dir', '"""image"""'], {}), "(save_dir, 'image')\n", (21820, 21839), False, 'import os\n'), ((21844, 21870), 'numpy.save', 'np.save', (['image_file', 'image'], {}), '(image_file, image)\n', (21851, 21870), True, 'import numpy as np\n'), ((21890, 21923), 'os.path.join', 'os.path.join', (['save_dir', '"""support"""'], {}), "(save_dir, 'support')\n", (21902, 21923), False, 'import os\n'), ((21928, 21958), 'numpy.save', 'np.save', (['support_file', 'support'], {}), '(support_file, support)\n', (21935, 21958), True, 'import numpy as np\n'), ((21976, 22008), 'os.path.join', 'os.path.join', (['save_dir', '"""errors"""'], {}), "(save_dir, 'errors')\n", (21988, 22008), False, 'import os\n'), ((22013, 22037), 'numpy.save', 'np.save', (['errs_file', 'errs'], {}), '(errs_file, errs)\n', (22020, 22037), True, 'import numpy as np\n'), ((22198, 22229), 'os.path.join', 'os.path.join', (['save_dir', '"""graph"""'], {}), "(save_dir, 'graph')\n", (22210, 22229), False, 'import os\n'), ((22315, 22346), 'os.path.join', 'os.path.join', (['graph_dir', '"""flow"""'], {}), "(graph_dir, 'flow')\n", (22327, 22346), False, 'import os\n'), ((22410, 22447), 'os.path.join', 'os.path.join', (['graph_dir', '"""iter_array"""'], {}), "(graph_dir, 'iter_array')\n", (22422, 22447), False, 'import os\n'), ((22452, 22488), 'numpy.save', 'np.save', (['iter_array_file', 'iter_array'], {}), '(iter_array_file, iter_array)\n', (22459, 22488), True, 'import numpy as np\n'), ((22977, 22993), 'numpy.fft.fftn', 'np.fft.fftn', (['arr'], {}), '(arr)\n', (22988, 22993), True, 'import numpy as np\n'), ((23392, 23415), 'numpy.meshgrid', 'np.meshgrid', (['Nc', 'Nr', 'Nz'], {}), '(Nc, Nr, Nz)\n', (23403, 23415), True, 'import numpy as np\n'), ((23555, 23573), 'numpy.fft.ifftn', 'np.fft.ifftn', (['Greg'], {}), '(Greg)\n', (23567, 23573), True, 'import numpy as np\n'), ((24676, 24692), 'GPUtil.getGPUs', 'GPUtil.getGPUs', ([], {}), '()\n', (24690, 24692), False, 'import GPUtil\n'), ((25690, 25727), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'available'], {}), '(lambda x, y: x + y, available)\n', (25696, 25727), False, 'from functools import reduce\n'), ((26599, 26610), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (26608, 26610), False, 'from multiprocessing import cpu_count\n'), ((27394, 27411), 'numpy.ones_like', 'np.ones_like', (['arr'], {}), '(arr)\n', (27406, 27411), True, 'import numpy as np\n'), ((28549, 28567), 'numpy.fft.fftn', 'np.fft.fftn', (['array'], {}), '(array)\n', (28560, 28567), True, 'import numpy as np\n'), ((28651, 28684), 'numpy.array', 'np.array', (['cross_correlation.shape'], {}), '(cross_correlation.shape)\n', (28659, 28684), True, 'import numpy as np\n'), ((28695, 28720), 'numpy.abs', 'np.abs', (['cross_correlation'], {}), '(cross_correlation)\n', (28701, 28720), True, 'import numpy as np\n'), ((28792, 28810), 'numpy.array', 'np.array', (['intshift'], {}), '(intshift)\n', (28800, 28810), True, 'import numpy as np\n'), ((28828, 28892), 'numpy.where', 'np.where', (['(shifted >= corelated / 2)', '(shifted - corelated)', 'shifted'], {}), '(shifted >= corelated / 2, shifted - corelated, shifted)\n', (28836, 28892), True, 'import numpy as np\n'), ((29183, 29194), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (29188, 29194), False, 'from functools import wraps\n'), ((5454, 5464), 'tifffile.close', 'tf.close', ([], {}), '()\n', (5462, 5464), True, 'import tifffile as tf\n'), ((7149, 7181), 'numpy.delete', 'np.delete', (['array', 'cut_slices', 'ax'], {}), '(array, cut_slices, ax)\n', (7158, 7181), True, 'import numpy as np\n'), ((12476, 12525), 'numpy.split', 'np.split', (['cropped', '[crop_front, crop_end]'], {'axis': 'i'}), '(cropped, [crop_front, crop_end], axis=i)\n', (12484, 12525), True, 'import numpy as np\n'), ((12955, 12968), 'numpy.asarray', 'np.asarray', (['m'], {}), '(m)\n', (12965, 12968), True, 'import numpy as np\n'), ((13972, 14038), 'numpy.linspace', 'np.linspace', (['(-(shape[i] - 1) / 2.0)', '((shape[i] - 1) / 2.0)', 'shape[i]'], {}), '(-(shape[i] - 1) / 2.0, (shape[i] - 1) / 2.0, shape[i])\n', (13983, 14038), True, 'import numpy as np\n'), ((14052, 14077), 'numpy.tile', 'np.tile', (['line', 'tile_shape'], {}), '(line, tile_shape)\n', (14059, 14077), True, 'import numpy as np\n'), ((14189, 14205), 'numpy.exp', 'np.exp', (['exponent'], {}), '(exponent)\n', (14195, 14205), True, 'import numpy as np\n'), ((15217, 15231), 'numpy.sum', 'np.sum', (['convag'], {}), '(convag)\n', (15223, 15231), True, 'import numpy as np\n'), ((15915, 15930), 'numpy.amax', 'np.amax', (['convag'], {}), '(convag)\n', (15922, 15930), True, 'import numpy as np\n'), ((15986, 16021), 'numpy.where', 'np.where', (['(convag >= threshold)', '(1)', '(0)'], {}), '(convag >= threshold, 1, 0)\n', (15994, 16021), True, 'import numpy as np\n'), ((16431, 16466), 'os.path.join', 'os.path.join', (['read_dir', '"""image.npy"""'], {}), "(read_dir, 'image.npy')\n", (16443, 16466), False, 'import os\n'), ((16483, 16501), 'numpy.load', 'np.load', (['imagefile'], {}), '(imagefile)\n', (16490, 16501), True, 'import numpy as np\n'), ((16575, 16612), 'os.path.join', 'os.path.join', (['read_dir', '"""support.npy"""'], {}), "(read_dir, 'support.npy')\n", (16587, 16612), False, 'import os\n'), ((16631, 16651), 'numpy.load', 'np.load', (['supportfile'], {}), '(supportfile)\n', (16638, 16651), True, 'import numpy as np\n'), ((16715, 16754), 'os.path.join', 'os.path.join', (['read_dir', '"""coherence.npy"""'], {}), "(read_dir, 'coherence.npy')\n", (16727, 16754), False, 'import os\n'), ((16769, 16785), 'numpy.load', 'np.load', (['cohfile'], {}), '(cohfile)\n', (16776, 16785), True, 'import numpy as np\n'), ((17375, 17395), 'numpy.sum', 'np.sum', (['(ph * support)'], {}), '(ph * support)\n', (17381, 17395), True, 'import numpy as np\n'), ((17396, 17411), 'numpy.sum', 'np.sum', (['support'], {}), '(support)\n', (17402, 17411), True, 'import numpy as np\n'), ((17461, 17478), 'numpy.exp', 'np.exp', (['(1.0j * ph)'], {}), '(1.0j * ph)\n', (17467, 17478), True, 'import numpy as np\n'), ((19172, 19194), 'os.remove', 'os.remove', (['metric_file'], {}), '(metric_file)\n', (19181, 19194), False, 'import os\n'), ((21735, 21759), 'os.path.exists', 'os.path.exists', (['save_dir'], {}), '(save_dir)\n', (21749, 21759), False, 'import os\n'), ((21769, 21790), 'os.makedirs', 'os.makedirs', (['save_dir'], {}), '(save_dir)\n', (21780, 21790), False, 'import os\n'), ((22081, 22116), 'os.path.join', 'os.path.join', (['save_dir', '"""coherence"""'], {}), "(save_dir, 'coherence')\n", (22093, 22116), False, 'import os\n'), ((22125, 22147), 'numpy.save', 'np.save', (['coh_file', 'coh'], {}), '(coh_file, coh)\n', (22132, 22147), True, 'import numpy as np\n'), ((22241, 22266), 'os.path.exists', 'os.path.exists', (['graph_dir'], {}), '(graph_dir)\n', (22255, 22266), False, 'import os\n'), ((22276, 22298), 'os.makedirs', 'os.makedirs', (['graph_dir'], {}), '(graph_dir)\n', (22287, 22298), False, 'import os\n'), ((22370, 22386), 'numpy.asarray', 'np.asarray', (['flow'], {}), '(flow)\n', (22380, 22386), True, 'import numpy as np\n'), ((23436, 23549), 'numpy.exp', 'np.exp', (['(1.0j * 2 * np.pi * (-row_shift * Nr / shape[0] - col_shift * Nc / shape[1] -\n z_shift * Nz / shape[2]))'], {}), '(1.0j * 2 * np.pi * (-row_shift * Nr / shape[0] - col_shift * Nc /\n shape[1] - z_shift * Nz / shape[2]))\n', (23442, 23549), True, 'import numpy as np\n'), ((26625, 26648), 'psutil.virtual_memory', 'psutil.virtual_memory', ([], {}), '()\n', (26646, 26648), False, 'import psutil\n'), ((2493, 2512), 'tifffile.imread', 'tf.imread', (['filename'], {}), '(filename)\n', (2502, 2512), True, 'import tifffile as tf\n'), ((7516, 7549), 'numpy.sum', 'np.sum', (['binned_array'], {'axis': '(ax + 1)'}), '(binned_array, axis=ax + 1)\n', (7522, 7549), True, 'import numpy as np\n'), ((8182, 8196), 'numpy.argmax', 'np.argmax', (['arr'], {}), '(arr)\n', (8191, 8196), True, 'import numpy as np\n'), ((9058, 9072), 'numpy.argmax', 'np.argmax', (['arr'], {}), '(arr)\n', (9067, 9072), True, 'import numpy as np\n'), ((14147, 14162), 'numpy.power', 'np.power', (['gi', '(2)'], {}), '(gi, 2)\n', (14155, 14162), True, 'import numpy as np\n'), ((14872, 14893), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['arr'], {}), '(arr)\n', (14888, 14893), True, 'import numpy as np\n'), ((15100, 15124), 'numpy.fft.ifftshift', 'np.fft.ifftshift', (['convag'], {}), '(convag)\n', (15116, 15124), True, 'import numpy as np\n'), ((23928, 23943), 'numpy.argmax', 'np.argmax', (['arr1'], {}), '(arr1)\n', (23937, 23943), True, 'import numpy as np\n'), ((28615, 28633), 'numpy.conj', 'np.conj', (['fft_array'], {}), '(fft_array)\n', (28622, 28633), True, 'import numpy as np\n'), ((29256, 29262), 'time.time', 'time', ([], {}), '()\n', (29260, 29262), False, 'from time import time\n'), ((23067, 23089), 'numpy.floor', 'np.floor', (['(shape[0] / 2)'], {}), '(shape[0] / 2)\n', (23075, 23089), True, 'import numpy as np\n'), ((23107, 23129), 'numpy.floor', 'np.floor', (['(shape[0] / 2)'], {}), '(shape[0] / 2)\n', (23115, 23129), True, 'import numpy as np\n'), ((23186, 23208), 'numpy.floor', 'np.floor', (['(shape[1] / 2)'], {}), '(shape[1] / 2)\n', (23194, 23208), True, 'import numpy as np\n'), ((23226, 23248), 'numpy.floor', 'np.floor', (['(shape[1] / 2)'], {}), '(shape[1] / 2)\n', (23234, 23248), True, 'import numpy as np\n'), ((23305, 23327), 'numpy.floor', 'np.floor', (['(shape[2] / 2)'], {}), '(shape[2] / 2)\n', (23313, 23327), True, 'import numpy as np\n'), ((23345, 23367), 'numpy.floor', 'np.floor', (['(shape[2] / 2)'], {}), '(shape[2] / 2)\n', (23353, 23367), True, 'import numpy as np\n'), ((29372, 29378), 'time.time', 'time', ([], {}), '()\n', (29376, 29378), False, 'from time import time\n')] |
import numpy as np
from io import StringIO
import matplotlib.pyplot as plt
from joblib import Parallel, delayed
import multiprocessing
import config
import logging
import pandas as pd
from sqlalchemy import create_engine
class Data_Retreival:
def __init__(self):
self.code_complexity_query = 'SELECT Merge_Scenario_merge_commit_hash, measure1_diff, measure2_diff, ' \
'measure3_diff, measure4_diff, measure5_diff, measure6_diff, measure7_diff, ' \
'measure8_diff ' \
'FROM Merge_Data.Code_Complexity'
self.code_violation_query = 'SELECT Code_Violation.Merge_Scenario_merge_commit_hash, ' \
'Code_Violation.parent1_style_violation_num - ' \
' Code_Violation.parent2_style_violation_num ' \
'FROM Merge_Data.Code_Style_Violation Code_Violation '
self.parallel_changes_query = 'SELECT merge_commit_hash, parallel_changed_file_num ' \
'FROM Merge_Data.Merge_Scenario'
self.commit_num_query = 'SELECT Merge_Scenario.merge_commit_hash, count(Commits.commit_hash) ' \
'FROM Merge_Data.Merge_Scenario Merge_Scenario LEFT JOIN ' \
'Merge_Data.Merge_Related_Commit Commits ' \
'on Merge_Scenario.merge_commit_hash = Commits.Merge_Scenario_merge_commit_hash' \
' AND Commits.merge_commit_parent = {} ' \
'GROUP BY Merge_Scenario.merge_commit_hash'
self.commit_density_two_weeks = 'SELECT Merge_Scenario.merge_commit_hash, count(Commits.commit_hash) FROM ' \
'Merge_Data.Merge_Scenario Merge_Scenario' \
' LEFT JOIN Merge_Data.Merge_Related_Commit Commits ' \
'on Merge_Scenario.merge_commit_hash = Commits.Merge_Scenario_merge_commit_hash ' \
'AND Commits.merge_commit_parent = {} AND ' \
'TIMESTAMPDIFF(WEEK, Merge_Scenario.merge_commit_date, Commits.date) < 3 ' \
'GROUP BY Merge_Scenario.merge_commit_hash'
self.file_change_query = 'SELECT Merge_Scenario.merge_commit_hash, COALESCE(SUM(file_added_num), 0), ' \
'COALESCE(SUM(file_removed_num), 0), COALESCE(SUM(file_renamed_num), 0), ' \
'COALESCE(SUM(file_copied_num), 0), COALESCE(SUM(file_modified_num), 0) ' \
' FROM Merge_Data.Merge_Scenario Merge_Scenario ' \
'LEFT JOIN Merge_Data.Merge_Related_Commit Commits ' \
'on Merge_Scenario.merge_commit_hash = Commits.Merge_Scenario_merge_commit_hash' \
' AND Commits.merge_commit_parent = {} ' \
'GROUP BY Merge_Scenario.merge_commit_hash'
self.line_change_query = 'SELECT Merge_Scenario.merge_commit_hash, COALESCE(SUM(line_added_num), 0), COALESCE(SUM(line_removed_num), 0) ' \
'FROM Merge_Data.Merge_Scenario Merge_Scenario ' \
'LEFT JOIN Merge_Data.Merge_Related_Commit Commits ' \
'on Merge_Scenario.merge_commit_hash = Commits.Merge_Scenario_merge_commit_hash ' \
'AND Commits.merge_commit_parent = {} ' \
'GROUP BY Merge_Scenario.merge_commit_hash'
self.developer_num_query = 'SELECT merge_commit_hash, parent{}_developer_num ' \
'FROM Merge_Data.Merge_Scenario'
self.commit_message_quey = 'SELECT GROUP_CONCAT(Commits.message SEPARATOR \' ||| \') ' \
'FROM Merge_Data.Merge_Scenario Merge_Scenario ' \
'LEFT JOIN Merge_Data.Merge_Related_Commit Commits ' \
'on Merge_Scenario.merge_commit_hash = Commits.Merge_Scenario_merge_commit_hash ' \
'AND Commits.merge_commit_parent = {} ' \
'GROUP BY Merge_Scenario.merge_commit_hash'
self.branch_duration = 'SELECT Merge_Scenario.merge_commit_hash, TIMESTAMPDIFF(HOUR, ' \
'Merge_Scenario.ancestor_date, Merge_Scenario.parent{}_date) ' \
'FROM Merge_Data.Merge_Scenario Merge_Scenario'
self.is_conflict_query = 'SELECT Merge_Replay.Merge_Scenario_merge_commit_hash, Merge_Replay.is_conflict ' \
'FROM Merge_Data.Merge_Replay Merge_Replay'
self.conflict_rate_query = """SELECT scenarios.name AS 'Repository Name'
, scenarios.scenarios AS '# Merge Scenarios',
conflicts.conflicts AS '# Merge Scenarios with Conflicts',
100 * conflicts.conflicts/scenarios.scenarios 'Conflict Rate (%)'
FROM
(SELECT Repository.name,
COUNT(Merge_Replay.Merge_Scenario_merge_commit_hash) AS 'scenarios'
FROM Merge_Data.Repository
JOIN Merge_Data.Merge_Replay
ON id = Merge_Scenario_Repository_id
GROUP BY name
ORDER BY name) scenarios
INNER JOIN
(SELECT name, COUNT(Merge_Replay.Merge_Scenario_merge_commit_hash) AS 'conflicts'
FROM Merge_Data.Repository
JOIN Merge_Data.Merge_Replay
ON id = Merge_Scenario_Repository_id
WHERE is_conflict = 1
GROUP BY name
ORDER BY name) conflicts
ON scenarios. name = conflicts.name"""
self.repository_stat = """(SELECT MIN(star_num) as Min, AVG(star_num) as AVG,MAX(star_num) as Max
FROM Merge_Data.Repository)
UNION ALL
(SELECT MIN(watch_num), AVG(watch_num),MAX(watch_num)
FROM Merge_Data.Repository)
UNION ALL
(SELECT MIN(fork_num), AVG(fork_num),MAX(fork_num)
FROM Merge_Data.Repository)
UNION ALL
(SELECT MIN(issue_num), AVG(issue_num),MAX(issue_num)
FROM Merge_Data.Repository)
UNION ALL
(SELECT MIN(size) / 1024, AVG(size) / 1024,MAX(size) / 1024
FROM Merge_Data.Repository)"""
self.parallel_changed_commits_query = """select merge_commit_hash from Merge_Data.Merge_Scenario sc Where parallel_changed_file_num > 0"""
self.merge_commits_langs_query = """SELECT language, COUNT(is_conflict) AS "Merge Scnenario No.",SUM(is_conflict) AS "Conflict No."
FROM Merge_Data.Repository JOIN Merge_Data.Merge_Replay
ON Repository.id = Merge_Replay.Merge_Scenario_Repository_id
WHERE language IN ('Java', 'Python', 'PHP', 'RUBY', 'C++')
GROUP BY language"""
self.conflict_per_language_query = """SELECT language, COUNT(is_conflict),SUM(is_conflict)
FROM Merge_Data.Repository JOIN Merge_Data.Merge_Replay
ON Repository.id = Merge_Replay.Merge_Scenario_Repository_id
WHERE language IN ('Java', 'Python', 'PHP', 'RUBY', 'C++')
GROUP BY language"""
self.repository_per_language_query = """SELECT language, COUNT(name) AS "Repository No."
FROM Merge_Data.Repository
WHERE language IN ('Java', 'Python', 'PHP', 'RUBY', 'C++')
GROUP BY language"""
self.scenarios_num_of_lang_query = """SELECT COUNT(merge_commit_hash)
FROM Merge_Data.Repository LEFT JOIN Merge_Data.Merge_Scenario on id = Repository_id
WHERE language = '{}'
GROUP BY name"""
self.star_num_of_lang_query = """SELECT star_num
FROM Merge_Data.Repository
WHERE language = '{}'"""
self.conflicts_num_of_lang_query = """SELECT SUM(is_conflict)
FROM Merge_Data.Repository LEFT JOIN Merge_Data.Merge_Replay on id = Merge_Scenario_Repository_id
WHERE language = '{}'
GROUP BY name"""
def get_star_nums_by_lang(self, lang):
logging.info('Getting all scenarios of lang...')
return self.get_data_frame_of_query_result(self.get_query_result(self.star_num_of_lang_query.format(lang)))
def get_conflicts_nums_by_lang(self, lang):
logging.info('Getting all scenarios of lang...')
return self.get_data_frame_of_query_result(self.get_query_result(self.conflicts_num_of_lang_query.format(lang)))
def get_scenarios_nums_by_lang(self, lang):
logging.info('Getting all scenarios of lang...')
return self.get_data_frame_of_query_result(self.get_query_result(self.scenarios_num_of_lang_query.format(lang)))
def get_conflict_per_language(self):
logging.info('Extracting conflicts per language...')
return self.get_data_frame_of_query_result(self.get_query_result(self.conflict_per_language_query))
def get_repository_per_language(self):
logging.info('Extracting conflicts per language...')
return self.get_data_frame_of_query_result(self.get_query_result(self.repository_per_language_query))
def get_parallel_changed_commits(self):
logging.info('Extracting parallel changes...')
return self.get_data_frame_of_query_result(self.get_query_result(self.parallel_changed_commits_query))
def get_query_result(self, query):
engine = create_engine('mysql+pymysql://{}:{}@localhost/{}'.format(config.DB_USER_NAME, config.DB_PASSWORD, config.DB_NAME))
df = pd.read_sql_query(query, engine)
return df
def get_data_frame_of_query_result(self, query_result):
return query_result
if len(query_result) == 0:
print('Empty result!')
return -1
return pd.read_csv(StringIO(query_result), delimiter='\t')
def get_complexity(self):
logging.info('Extracting code complexity...')
return self.get_data_frame_of_query_result(self.get_query_result(self.code_complexity_query))
def get_code_violation(self):
logging.info('Extracting code style violation...')
return self.get_data_frame_of_query_result(self.get_query_result(self.code_violation_query))
def get_parallel_changes(self):
logging.info('Extracting code parallel changes...')
return self.get_data_frame_of_query_result(self.get_query_result(self.parallel_changes_query))
def get_commit_num(self, parent): # TODO: The number of data in two branches is not the same.
logging.info('Extracting the number of commits...')
return self.get_data_frame_of_query_result(self.get_query_result(self.commit_num_query.format(parent)))
def get_commit_density(self, parent):
logging.info('Extracting commit density...')
return self.get_data_frame_of_query_result(self.get_query_result(self.commit_density_two_weeks.format(parent)))
def get_file_changes(self, parent):
logging.info('Extracting file changes...')
return self.get_data_frame_of_query_result(self.get_query_result(self.file_change_query.format(parent)))
def get_line_changes(self, parent):
logging.info('Extracting line changes...')
return self.get_data_frame_of_query_result(self.get_query_result(self.line_change_query.format(parent)))
def get_developer_num(self, parent):
logging.info('Extracting developer num...')
res = self.get_data_frame_of_query_result(self.get_query_result(self.developer_num_query.format(parent))).drop('merge_commit_hash', axis=1).values
return pd.DataFrame([item for sublist in res for item in sublist], columns=['# Developers'])
def get_merge_scenarios_in_lang(self, langs):
logging.info('Extracting merges by language...')
langs = ','.join(['\'{}\''.format(lang) for lang in langs])
return self.get_data_frame_of_query_result(self.get_query_result(self.merge_commits_langs_query.format(langs)))
def get_commit_messege_characteristics(self, parent):
logging.info('Extracting message characteristics...')
commit_messages = self.get_query_result(self.commit_message_quey.format(parent))
commit_messages_list = commit_messages.values[1:]
commit_messages_list = [item for sublist in commit_messages_list for item in sublist if item is not None]
keywords = sorted(['fix', 'bug', 'feature', 'improve', 'document', 'refactor', 'update', 'add', 'remove', 'use',
'delete', 'change'])
keywords_frequency = []
commit_messege_length_stats = []
for merge_scenrio_commits in commit_messages_list:
keywords_frequency.append([merge_scenrio_commits.lower().count(word) for word in keywords])
if merge_scenrio_commits != 'NULL':
seperated_commit_message = merge_scenrio_commits.replace(' ||| ', '\n').split('\n')
commit_messege_length = [len(msg.split()) for msg in seperated_commit_message]
commit_messege_length_stats.append([np.min(commit_messege_length), np.mean(commit_messege_length),
np.median(commit_messege_length), np.max(commit_messege_length)])
else:
commit_messege_length_stats.append([0.0, 0.0, 0.0, 0.0])
column_names_frequency = ['# fix', '# bug', '# feature', '# improve', '# document', '# refactor', '# update',
'# add', '# remove', '# use', '# delete', '# change']
column_names_stats = ['Min Msg Length', 'Mean Msg Length', 'Median Msg Length', 'Max Msg Length']
return pd.DataFrame(keywords_frequency, columns=column_names_frequency), \
pd.DataFrame(commit_messege_length_stats, columns=column_names_stats)
def get_branch_duration(self, parent):
logging.info('Extracting branch duration...')
res = self.get_data_frame_of_query_result(self.get_query_result(self.branch_duration.format(parent))).drop(
'merge_commit_hash', axis=1).values
return pd.DataFrame([item for sublist in res for item in sublist], columns=['Branch Duration'])
def get_is_conflict(self):
res = self.get_data_frame_of_query_result(self.get_query_result(self.is_conflict_query.format())).drop(
'Merge_Scenario_merge_commit_hash', axis=1).values
return pd.DataFrame([item for sublist in res for item in sublist], columns=['Is Conflict'])
def get_merge_scenario_prediction_data(self, langs):
keywords_frequency1, commit_messege_length_stats1 = self.get_commit_messege_characteristics(1)
keywords_frequency2, commit_messege_length_stats2 = self.get_commit_messege_characteristics(2)
git_features_scenario = self.get_parallel_changes()
features = [git_features_scenario,
self.get_commit_num(1).drop('merge_commit_hash', axis=1) - self.get_commit_num(2).drop('merge_commit_hash',
axis=1),
self.get_commit_density(1).drop('merge_commit_hash', axis=1) - self.get_commit_density(2).drop(
'merge_commit_hash', axis=1),
self.get_file_changes(1).drop('merge_commit_hash', axis=1) - self.get_file_changes(2).drop(
'merge_commit_hash', axis=1),
self.get_line_changes(1).drop('merge_commit_hash', axis=1) - self.get_line_changes(2).drop(
'merge_commit_hash', axis=1),
self.get_developer_num(1) - self.get_developer_num(2),
keywords_frequency1 - keywords_frequency2,
commit_messege_length_stats1 - commit_messege_length_stats2,
self.get_branch_duration(1) - self.get_branch_duration(2)]
lang_data = self.get_merge_scenarios_in_lang(langs)
data = pd.concat([pd.concat(features, axis=1).sort_values(by=['merge_commit_hash']), lang_data], axis=1)
data = data[data['language'].isin(langs)].drop('merge_commit_hash', axis=1).drop('language', axis=1)
label = self.get_data_frame_of_query_result(self.get_query_result(self.is_conflict_query.format())).sort_values(by=['Merge_Scenario_merge_commit_hash']).drop(
'Merge_Scenario_merge_commit_hash', axis=1).values
label = pd.DataFrame([item for sublist in label for item in sublist], columns=['Is Conflict'])
label = pd.concat([label, lang_data], axis=1)
label = label[label['language'].isin(langs)].drop('merge_commit_hash', axis=1).drop('language', axis=1)
return data, label
def save_prediction_data_to_csv(self, langs, post_name):
logging.info('Start {}'.format(post_name))
data, label = self.get_merge_scenario_prediction_data(langs)
data.to_csv(path_or_buf=config.PREDICTION_CSV_PATH + config.PREDICTION_CSV_DATA_NAME + post_name)
label.to_csv(path_or_buf=config.PREDICTION_CSV_PATH + config.PREDICTION_CSV_LABEL_NAME + post_name)
def get_conflict_ratio(self):
return self.get_data_frame_of_query_result(self.get_query_result(self.conflict_rate_query))
def get_repository_stats(self):
return self.get_data_frame_of_query_result(self.get_query_result(self.repository_stat)).rename(index={0:'star', 1:'watch', 2: 'fork', 3: 'issue', 4:'size'})
def print_df_stats(self, df):
print('DataFrame Stats:')
print(' - # Data Points: {}'.format(df.shape[0]))
print(' - # Features: {}'.format(df.shape[1]))
print(' - Index: {}'.format(df.index))
print(' - Columns: {}'.format(df.columns))
def draw_normalized_scenarios_per_lang():
obj = Data_Retreival()
conflict_per_language = obj.get_conflict_per_language()
repository_per_language = obj.get_repository_per_language()
merges_per_language_normalized= conflict_per_language['COUNT(is_conflict)'].div(repository_per_language['Repository No.'], axis=0)
conflicts_per_language_normalized= conflict_per_language['SUM(is_conflict)'].div(repository_per_language['Repository No.'], axis=0)
pd.concat([merges_per_language_normalized, conflicts_per_language_normalized], axis=1).plot(kind='bar')
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
y_pos = np.arange(len(langs))
plt.xticks(y_pos, langs)
plt.xlabel('Programming Languages')
plt.ylabel('NN. Merges / No. Repositories')
plt.legend(['Total Merge Scenarios', 'Conflicting Merge Scenarios'])
plt.show()
def draw_likelihood_merges():
obj = Data_Retreival()
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
ax = obj.get_scenarios_nums_by_lang(langs[0]).plot.kde()
for i, item in enumerate(langs):
if i == 0:
continue
obj.get_scenarios_nums_by_lang(langs[i]).plot.kde(ax=ax)
plt.xlim((0, 1500))
plt.legend(langs)
plt.xlabel('No. Merge Scenarios')
plt.ylabel('Likelihood')
plt.show()
def draw_likelihood_conflicts():
obj = Data_Retreival()
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
ax = obj.get_conflicts_nums_by_lang(langs[0]).plot.kde()
for i, item in enumerate(langs):
if i == 0:
continue
obj.get_scenarios_nums_by_lang(langs[i]).plot.kde(ax=ax)
plt.xlim((0, 1500))
plt.legend(langs)
plt.xlabel('No. Merge Scenarios')
plt.ylabel('Likelihood')
plt.show()
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
return lower_adjacent_value, upper_adjacent_value
def draw_violin_scenarios():
obj = Data_Retreival()
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
data = []
for i, item in enumerate(langs):
data.append(obj.get_scenarios_nums_by_lang(langs[i]).values)
fig, ax = plt.subplots()
parts = ax.violinplot(data, showmeans=True)
# plt.legend(langs)
plt.xlabel('Programming Languages')
plt.ylabel('No. Merge Scenarios')
ind = np.arange(len(langs)) + 1
plt.xticks(ind, langs)
plt.show()
def draw_violin_conflicts():
obj = Data_Retreival()
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
data = []
for i, item in enumerate(langs):
data.append(obj.get_conflicts_nums_by_lang(langs[i]).values)
fig, ax = plt.subplots()
parts = ax.violinplot(data, showmeans=True)
# plt.legend(langs)
plt.xlabel('Programming Languages')
plt.ylabel('No. Conflicting Merge Scenarios')
ind = np.arange(len(langs)) + 1
plt.xticks(ind, langs)
plt.show()
def draw_violin_scenarios_conflicts():
obj = Data_Retreival()
langs = ['C++', 'Java', 'PHP', 'Python', 'Ruby']
data_scenarios = []
data_conflicts = []
for i, item in enumerate(langs):
data_scenarios.append(obj.get_conflicts_nums_by_lang(langs[i]).values)
data_conflicts.append(obj.get_scenarios_nums_by_lang(langs[i]).values)
data2 = data_scenarios
data1 = data_conflicts
v1 = plt.violinplot(data1, positions=np.arange(0, len(data1)), widths=1,
showmeans=False, showextrema=False, showmedians=False)
for b in v1['bodies']:
m = np.mean(b.get_paths()[0].vertices[:, 0])
b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
b.set_color('r')
b.set_alpha(0.5)
b.set_edgecolor('k')
v2 = plt.violinplot(data2, positions=np.arange(0, len(data2)), widths=1,
showmeans=False, showextrema=False, showmedians=False)
for b in v2['bodies']:
m = np.mean(b.get_paths()[0].vertices[:, 0])
b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
b.set_color('b')
b.set_alpha(0.5)
b.set_edgecolor('k')
b1, b2 = plt.plot([1],'b'), plt.plot([1],'r')
# plt.legend([b1[0], b2[0]], ['Conflicting Merge Scenarios', 'Total Merge Scenarios'], loc = 0)
ind = np.arange(len(langs))
plt.xticks(ind, langs)
plt.xlabel('Programming Languages')
plt.ylabel('No. Merge Scenarios')
plt.gca().set_ylim([0, 1200])
plt.show()
if __name__ == "__main__":
# Logging
logging.basicConfig(level=logging.INFO,
format='%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s',
datefmt='%y-%m-%d %H:%M:%S')
#draw_violin_scenarios()
#draw_violin_conflicts()
#exit()
obj = Data_Retreival()
print(obj.get_conflict_ratio())
exit()
print('Start data saving')
lang_test = [['Java'], ['Python'], ['PHP'], ['Ruby'], ['C++'], ['Java', 'Python', 'Ruby', 'PHP', 'C++']]
name_test = ['_JAVA', '_PYTHON', '_PHP', '_RUBY', '_C++', '_ALL']
# Parallel execution
core_num = multiprocessing.cpu_count()
Parallel(n_jobs=core_num)(delayed(obj.save_prediction_data_to_csv)(lang_test[i], name_test[i]) for i in range(len(name_test)))
print('Finish data saving')
#print(obj.get_repository_stats())
| [
"numpy.clip",
"numpy.mean",
"matplotlib.pyplot.gca",
"multiprocessing.cpu_count",
"pandas.DataFrame",
"numpy.max",
"pandas.read_sql_query",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"pandas.concat",
"io.StringIO",
"matplotlib.pyplot.show",
"numpy.median",
"matplotlib.pyplot... | [((19411, 19435), 'matplotlib.pyplot.xticks', 'plt.xticks', (['y_pos', 'langs'], {}), '(y_pos, langs)\n', (19421, 19435), True, 'import matplotlib.pyplot as plt\n'), ((19440, 19475), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Programming Languages"""'], {}), "('Programming Languages')\n", (19450, 19475), True, 'import matplotlib.pyplot as plt\n'), ((19480, 19524), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""NN. Merges / No. Repositories"""'], {}), "('NN. Merges / No. Repositories')\n", (19490, 19524), True, 'import matplotlib.pyplot as plt\n'), ((19529, 19597), 'matplotlib.pyplot.legend', 'plt.legend', (["['Total Merge Scenarios', 'Conflicting Merge Scenarios']"], {}), "(['Total Merge Scenarios', 'Conflicting Merge Scenarios'])\n", (19539, 19597), True, 'import matplotlib.pyplot as plt\n'), ((19602, 19612), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19610, 19612), True, 'import matplotlib.pyplot as plt\n'), ((19931, 19950), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 1500)'], {}), '((0, 1500))\n', (19939, 19950), True, 'import matplotlib.pyplot as plt\n'), ((19955, 19972), 'matplotlib.pyplot.legend', 'plt.legend', (['langs'], {}), '(langs)\n', (19965, 19972), True, 'import matplotlib.pyplot as plt\n'), ((19977, 20010), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""No. Merge Scenarios"""'], {}), "('No. Merge Scenarios')\n", (19987, 20010), True, 'import matplotlib.pyplot as plt\n'), ((20015, 20039), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Likelihood"""'], {}), "('Likelihood')\n", (20025, 20039), True, 'import matplotlib.pyplot as plt\n'), ((20044, 20054), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20052, 20054), True, 'import matplotlib.pyplot as plt\n'), ((20376, 20395), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0, 1500)'], {}), '((0, 1500))\n', (20384, 20395), True, 'import matplotlib.pyplot as plt\n'), ((20400, 20417), 'matplotlib.pyplot.legend', 'plt.legend', (['langs'], {}), '(langs)\n', (20410, 20417), True, 'import matplotlib.pyplot as plt\n'), ((20422, 20455), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""No. Merge Scenarios"""'], {}), "('No. Merge Scenarios')\n", (20432, 20455), True, 'import matplotlib.pyplot as plt\n'), ((20460, 20484), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Likelihood"""'], {}), "('Likelihood')\n", (20470, 20484), True, 'import matplotlib.pyplot as plt\n'), ((20489, 20499), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20497, 20499), True, 'import matplotlib.pyplot as plt\n'), ((20612, 20655), 'numpy.clip', 'np.clip', (['upper_adjacent_value', 'q3', 'vals[-1]'], {}), '(upper_adjacent_value, q3, vals[-1])\n', (20619, 20655), True, 'import numpy as np\n'), ((20732, 20774), 'numpy.clip', 'np.clip', (['lower_adjacent_value', 'vals[0]', 'q1'], {}), '(lower_adjacent_value, vals[0], q1)\n', (20739, 20774), True, 'import numpy as np\n'), ((21073, 21087), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (21085, 21087), True, 'import matplotlib.pyplot as plt\n'), ((21164, 21199), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Programming Languages"""'], {}), "('Programming Languages')\n", (21174, 21199), True, 'import matplotlib.pyplot as plt\n'), ((21204, 21237), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No. Merge Scenarios"""'], {}), "('No. Merge Scenarios')\n", (21214, 21237), True, 'import matplotlib.pyplot as plt\n'), ((21278, 21300), 'matplotlib.pyplot.xticks', 'plt.xticks', (['ind', 'langs'], {}), '(ind, langs)\n', (21288, 21300), True, 'import matplotlib.pyplot as plt\n'), ((21305, 21315), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21313, 21315), True, 'import matplotlib.pyplot as plt\n'), ((21560, 21574), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (21572, 21574), True, 'import matplotlib.pyplot as plt\n'), ((21651, 21686), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Programming Languages"""'], {}), "('Programming Languages')\n", (21661, 21686), True, 'import matplotlib.pyplot as plt\n'), ((21691, 21736), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No. Conflicting Merge Scenarios"""'], {}), "('No. Conflicting Merge Scenarios')\n", (21701, 21736), True, 'import matplotlib.pyplot as plt\n'), ((21777, 21799), 'matplotlib.pyplot.xticks', 'plt.xticks', (['ind', 'langs'], {}), '(ind, langs)\n', (21787, 21799), True, 'import matplotlib.pyplot as plt\n'), ((21804, 21814), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (21812, 21814), True, 'import matplotlib.pyplot as plt\n'), ((23235, 23257), 'matplotlib.pyplot.xticks', 'plt.xticks', (['ind', 'langs'], {}), '(ind, langs)\n', (23245, 23257), True, 'import matplotlib.pyplot as plt\n'), ((23262, 23297), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Programming Languages"""'], {}), "('Programming Languages')\n", (23272, 23297), True, 'import matplotlib.pyplot as plt\n'), ((23302, 23335), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No. Merge Scenarios"""'], {}), "('No. Merge Scenarios')\n", (23312, 23335), True, 'import matplotlib.pyplot as plt\n'), ((23374, 23384), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (23382, 23384), True, 'import matplotlib.pyplot as plt\n'), ((23433, 23597), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s"""', 'datefmt': '"""%y-%m-%d %H:%M:%S"""'}), "(level=logging.INFO, format=\n '%(levelname)s in %(threadName)s - %(asctime)s by %(name)-12s : %(message)s'\n , datefmt='%y-%m-%d %H:%M:%S')\n", (23452, 23597), False, 'import logging\n'), ((24036, 24063), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (24061, 24063), False, 'import multiprocessing\n'), ((9236, 9284), 'logging.info', 'logging.info', (['"""Getting all scenarios of lang..."""'], {}), "('Getting all scenarios of lang...')\n", (9248, 9284), False, 'import logging\n'), ((9459, 9507), 'logging.info', 'logging.info', (['"""Getting all scenarios of lang..."""'], {}), "('Getting all scenarios of lang...')\n", (9471, 9507), False, 'import logging\n'), ((9687, 9735), 'logging.info', 'logging.info', (['"""Getting all scenarios of lang..."""'], {}), "('Getting all scenarios of lang...')\n", (9699, 9735), False, 'import logging\n'), ((9907, 9959), 'logging.info', 'logging.info', (['"""Extracting conflicts per language..."""'], {}), "('Extracting conflicts per language...')\n", (9919, 9959), False, 'import logging\n'), ((10120, 10172), 'logging.info', 'logging.info', (['"""Extracting conflicts per language..."""'], {}), "('Extracting conflicts per language...')\n", (10132, 10172), False, 'import logging\n'), ((10336, 10382), 'logging.info', 'logging.info', (['"""Extracting parallel changes..."""'], {}), "('Extracting parallel changes...')\n", (10348, 10382), False, 'import logging\n'), ((10680, 10712), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'engine'], {}), '(query, engine)\n', (10697, 10712), True, 'import pandas as pd\n'), ((11018, 11063), 'logging.info', 'logging.info', (['"""Extracting code complexity..."""'], {}), "('Extracting code complexity...')\n", (11030, 11063), False, 'import logging\n'), ((11209, 11259), 'logging.info', 'logging.info', (['"""Extracting code style violation..."""'], {}), "('Extracting code style violation...')\n", (11221, 11259), False, 'import logging\n'), ((11406, 11457), 'logging.info', 'logging.info', (['"""Extracting code parallel changes..."""'], {}), "('Extracting code parallel changes...')\n", (11418, 11457), False, 'import logging\n'), ((11668, 11719), 'logging.info', 'logging.info', (['"""Extracting the number of commits..."""'], {}), "('Extracting the number of commits...')\n", (11680, 11719), False, 'import logging\n'), ((11883, 11927), 'logging.info', 'logging.info', (['"""Extracting commit density..."""'], {}), "('Extracting commit density...')\n", (11895, 11927), False, 'import logging\n'), ((12097, 12139), 'logging.info', 'logging.info', (['"""Extracting file changes..."""'], {}), "('Extracting file changes...')\n", (12109, 12139), False, 'import logging\n'), ((12302, 12344), 'logging.info', 'logging.info', (['"""Extracting line changes..."""'], {}), "('Extracting line changes...')\n", (12314, 12344), False, 'import logging\n'), ((12508, 12551), 'logging.info', 'logging.info', (['"""Extracting developer num..."""'], {}), "('Extracting developer num...')\n", (12520, 12551), False, 'import logging\n'), ((12722, 12812), 'pandas.DataFrame', 'pd.DataFrame', (['[item for sublist in res for item in sublist]'], {'columns': "['# Developers']"}), "([item for sublist in res for item in sublist], columns=[\n '# Developers'])\n", (12734, 12812), True, 'import pandas as pd\n'), ((12867, 12915), 'logging.info', 'logging.info', (['"""Extracting merges by language..."""'], {}), "('Extracting merges by language...')\n", (12879, 12915), False, 'import logging\n'), ((13171, 13224), 'logging.info', 'logging.info', (['"""Extracting message characteristics..."""'], {}), "('Extracting message characteristics...')\n", (13183, 13224), False, 'import logging\n'), ((14982, 15027), 'logging.info', 'logging.info', (['"""Extracting branch duration..."""'], {}), "('Extracting branch duration...')\n", (14994, 15027), False, 'import logging\n'), ((15207, 15300), 'pandas.DataFrame', 'pd.DataFrame', (['[item for sublist in res for item in sublist]'], {'columns': "['Branch Duration']"}), "([item for sublist in res for item in sublist], columns=[\n 'Branch Duration'])\n", (15219, 15300), True, 'import pandas as pd\n'), ((15518, 15607), 'pandas.DataFrame', 'pd.DataFrame', (['[item for sublist in res for item in sublist]'], {'columns': "['Is Conflict']"}), "([item for sublist in res for item in sublist], columns=[\n 'Is Conflict'])\n", (15530, 15607), True, 'import pandas as pd\n'), ((17449, 17540), 'pandas.DataFrame', 'pd.DataFrame', (['[item for sublist in label for item in sublist]'], {'columns': "['Is Conflict']"}), "([item for sublist in label for item in sublist], columns=[\n 'Is Conflict'])\n", (17461, 17540), True, 'import pandas as pd\n'), ((17552, 17589), 'pandas.concat', 'pd.concat', (['[label, lang_data]'], {'axis': '(1)'}), '([label, lang_data], axis=1)\n', (17561, 17589), True, 'import pandas as pd\n'), ((23062, 23080), 'matplotlib.pyplot.plot', 'plt.plot', (['[1]', '"""b"""'], {}), "([1], 'b')\n", (23070, 23080), True, 'import matplotlib.pyplot as plt\n'), ((23081, 23099), 'matplotlib.pyplot.plot', 'plt.plot', (['[1]', '"""r"""'], {}), "([1], 'r')\n", (23089, 23099), True, 'import matplotlib.pyplot as plt\n'), ((24068, 24093), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'core_num'}), '(n_jobs=core_num)\n', (24076, 24093), False, 'from joblib import Parallel, delayed\n'), ((10939, 10961), 'io.StringIO', 'StringIO', (['query_result'], {}), '(query_result)\n', (10947, 10961), False, 'from io import StringIO\n'), ((14777, 14841), 'pandas.DataFrame', 'pd.DataFrame', (['keywords_frequency'], {'columns': 'column_names_frequency'}), '(keywords_frequency, columns=column_names_frequency)\n', (14789, 14841), True, 'import pandas as pd\n'), ((14860, 14929), 'pandas.DataFrame', 'pd.DataFrame', (['commit_messege_length_stats'], {'columns': 'column_names_stats'}), '(commit_messege_length_stats, columns=column_names_stats)\n', (14872, 14929), True, 'import pandas as pd\n'), ((19216, 19306), 'pandas.concat', 'pd.concat', (['[merges_per_language_normalized, conflicts_per_language_normalized]'], {'axis': '(1)'}), '([merges_per_language_normalized,\n conflicts_per_language_normalized], axis=1)\n', (19225, 19306), True, 'import pandas as pd\n'), ((23340, 23349), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (23347, 23349), True, 'import matplotlib.pyplot as plt\n'), ((24094, 24134), 'joblib.delayed', 'delayed', (['obj.save_prediction_data_to_csv'], {}), '(obj.save_prediction_data_to_csv)\n', (24101, 24134), False, 'from joblib import Parallel, delayed\n'), ((14183, 14212), 'numpy.min', 'np.min', (['commit_messege_length'], {}), '(commit_messege_length)\n', (14189, 14212), True, 'import numpy as np\n'), ((14214, 14244), 'numpy.mean', 'np.mean', (['commit_messege_length'], {}), '(commit_messege_length)\n', (14221, 14244), True, 'import numpy as np\n'), ((14293, 14325), 'numpy.median', 'np.median', (['commit_messege_length'], {}), '(commit_messege_length)\n', (14302, 14325), True, 'import numpy as np\n'), ((14327, 14356), 'numpy.max', 'np.max', (['commit_messege_length'], {}), '(commit_messege_length)\n', (14333, 14356), True, 'import numpy as np\n'), ((17006, 17033), 'pandas.concat', 'pd.concat', (['features'], {'axis': '(1)'}), '(features, axis=1)\n', (17015, 17033), True, 'import pandas as pd\n')] |
import numpy as np
class MyMath(object):
def boxplus( rad_angle_alfa, rad_angle_beta):
c_a, s_a= np.cos(rad_angle_alfa), np.sin(rad_angle_alfa)
c_b, s_b= np.cos(rad_angle_beta), np.sin(rad_angle_beta)
R_alfa = np.array([[ c_a, -s_a], [s_a, c_a ]])
R_beta = np.array([[ c_b, -s_b], [s_b, c_b ]])
R = np.matmul( R_alfa , R_beta)
return np.arctan2( R[1][0], R[0][0])
| [
"numpy.arctan2",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.matmul"
] | [((245, 280), 'numpy.array', 'np.array', (['[[c_a, -s_a], [s_a, c_a]]'], {}), '([[c_a, -s_a], [s_a, c_a]])\n', (253, 280), True, 'import numpy as np\n'), ((300, 335), 'numpy.array', 'np.array', (['[[c_b, -s_b], [s_b, c_b]]'], {}), '([[c_b, -s_b], [s_b, c_b]])\n', (308, 335), True, 'import numpy as np\n'), ((350, 375), 'numpy.matmul', 'np.matmul', (['R_alfa', 'R_beta'], {}), '(R_alfa, R_beta)\n', (359, 375), True, 'import numpy as np\n'), ((393, 421), 'numpy.arctan2', 'np.arctan2', (['R[1][0]', 'R[0][0]'], {}), '(R[1][0], R[0][0])\n', (403, 421), True, 'import numpy as np\n'), ((112, 134), 'numpy.cos', 'np.cos', (['rad_angle_alfa'], {}), '(rad_angle_alfa)\n', (118, 134), True, 'import numpy as np\n'), ((136, 158), 'numpy.sin', 'np.sin', (['rad_angle_alfa'], {}), '(rad_angle_alfa)\n', (142, 158), True, 'import numpy as np\n'), ((179, 201), 'numpy.cos', 'np.cos', (['rad_angle_beta'], {}), '(rad_angle_beta)\n', (185, 201), True, 'import numpy as np\n'), ((203, 225), 'numpy.sin', 'np.sin', (['rad_angle_beta'], {}), '(rad_angle_beta)\n', (209, 225), True, 'import numpy as np\n')] |
import logging
import os
import numpy as np
import pybullet as p
from igibson import object_states
from igibson.objects.articulated_object import URDFObject
from igibson.scenes.empty_scene import EmptyScene
from igibson.simulator import Simulator
from igibson.utils.assets_utils import get_ig_model_path
from igibson.utils.utils import restoreState
def main(selection="user", headless=False, short_exec=False):
"""
Demo of a cleaning task that resets after everything has been cleaned
To save/load state it combines pybullet save/load functionality and additional iG functions for the extended states
Loads an empty scene with a sink, a dusty table and a dirty and stained bowl, and a cleaning tool
If everything is cleaned, or after N steps, the scene resets to the initial state
"""
print("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80)
s = Simulator(mode="gui_interactive" if not headless else "headless", image_width=1280, image_height=720)
if not headless:
# Set a better viewing direction
s.viewer.initial_pos = [-0.5, -0.4, 1.5]
s.viewer.initial_view_direction = [0.7, 0.1, -0.7]
s.viewer.reset_viewer()
scene = EmptyScene(floor_plane_rgba=[0.6, 0.6, 0.6, 1])
s.import_scene(scene)
# Load sink ON
model_path = os.path.join(get_ig_model_path("sink", "sink_1"), "sink_1.urdf")
sink = URDFObject(
filename=model_path,
category="sink",
name="sink_1",
scale=np.array([0.8, 0.8, 0.8]),
abilities={"toggleable": {}, "waterSource": {}},
)
s.import_object(sink)
sink.set_position([1, 1, 0.8])
assert sink.states[object_states.ToggledOn].set_value(True)
# Load cleaning tool
model_path = get_ig_model_path("scrub_brush", "scrub_brush_000")
model_filename = os.path.join(model_path, "scrub_brush_000.urdf")
max_bbox = [0.1, 0.1, 0.1]
avg = {"size": max_bbox, "density": 67.0}
brush = URDFObject(
filename=model_filename,
category="scrub_brush",
name="scrub_brush",
avg_obj_dims=avg,
fit_avg_dim_volume=True,
model_path=model_path,
)
s.import_object(brush)
brush.set_position([0, -2, 0.4])
# Load table with dust
model_path = os.path.join(get_ig_model_path("breakfast_table", "19203"), "19203.urdf")
desk = URDFObject(
filename=model_path,
category="breakfast_table",
name="19898",
scale=np.array([0.8, 0.8, 0.8]),
abilities={"dustyable": {}},
)
s.import_object(desk)
desk.set_position([1, -2, 0.4])
assert desk.states[object_states.Dusty].set_value(True)
# Load a bowl with stains
model_path = os.path.join(get_ig_model_path("bowl", "68_0"), "68_0.urdf")
bowl = URDFObject(filename=model_path, category="bowl", name="bowl", abilities={"dustyable": {}, "stainable": {}})
s.import_object(bowl)
assert bowl.states[object_states.OnTop].set_value(desk, True, use_ray_casting_method=True)
assert bowl.states[object_states.Stained].set_value(True)
# Save the initial state.
pb_initial_state = p.saveState() # Save pybullet state (kinematics)
brush_initial_extended_state = brush.dump_state() # Save brush extended state
print(brush_initial_extended_state)
desk_initial_extended_state = desk.dump_state() # Save desk extended state
print(desk_initial_extended_state)
bowl_initial_extended_state = bowl.dump_state() # Save bowl extended state
print(bowl_initial_extended_state)
# Main simulation loop.
max_steps = 1000
max_iterations = -1 if not short_exec else 1
iteration = 0
try:
while iteration != max_iterations:
# Keep stepping until table or bowl are clean, or we reach 1000 steps
steps = 0
while (
desk.states[object_states.Dusty].get_value()
and bowl.states[object_states.Stained].get_value()
and steps != max_steps
):
steps += 1
s.step()
print("Step {}".format(steps))
if not desk.states[object_states.Dusty].get_value():
print("Reset because Table cleaned")
elif not bowl.states[object_states.Stained].get_value():
print("Reset because Bowl cleaned")
else:
print("Reset because max steps")
# Reset to the initial state
restoreState(pb_initial_state)
brush.load_state(brush_initial_extended_state)
brush.force_wakeup()
desk.load_state(desk_initial_extended_state)
desk.force_wakeup()
bowl.load_state(bowl_initial_extended_state)
bowl.force_wakeup()
iteration += 1
finally:
s.disconnect()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
main()
| [
"pybullet.saveState",
"logging.basicConfig",
"igibson.simulator.Simulator",
"numpy.array",
"igibson.utils.utils.restoreState",
"igibson.utils.assets_utils.get_ig_model_path",
"igibson.objects.articulated_object.URDFObject",
"os.path.join",
"igibson.scenes.empty_scene.EmptyScene"
] | [((886, 991), 'igibson.simulator.Simulator', 'Simulator', ([], {'mode': "('gui_interactive' if not headless else 'headless')", 'image_width': '(1280)', 'image_height': '(720)'}), "(mode='gui_interactive' if not headless else 'headless',\n image_width=1280, image_height=720)\n", (895, 991), False, 'from igibson.simulator import Simulator\n'), ((1204, 1251), 'igibson.scenes.empty_scene.EmptyScene', 'EmptyScene', ([], {'floor_plane_rgba': '[0.6, 0.6, 0.6, 1]'}), '(floor_plane_rgba=[0.6, 0.6, 0.6, 1])\n', (1214, 1251), False, 'from igibson.scenes.empty_scene import EmptyScene\n'), ((1752, 1803), 'igibson.utils.assets_utils.get_ig_model_path', 'get_ig_model_path', (['"""scrub_brush"""', '"""scrub_brush_000"""'], {}), "('scrub_brush', 'scrub_brush_000')\n", (1769, 1803), False, 'from igibson.utils.assets_utils import get_ig_model_path\n'), ((1825, 1873), 'os.path.join', 'os.path.join', (['model_path', '"""scrub_brush_000.urdf"""'], {}), "(model_path, 'scrub_brush_000.urdf')\n", (1837, 1873), False, 'import os\n'), ((1963, 2118), 'igibson.objects.articulated_object.URDFObject', 'URDFObject', ([], {'filename': 'model_filename', 'category': '"""scrub_brush"""', 'name': '"""scrub_brush"""', 'avg_obj_dims': 'avg', 'fit_avg_dim_volume': '(True)', 'model_path': 'model_path'}), "(filename=model_filename, category='scrub_brush', name=\n 'scrub_brush', avg_obj_dims=avg, fit_avg_dim_volume=True, model_path=\n model_path)\n", (1973, 2118), False, 'from igibson.objects.articulated_object import URDFObject\n'), ((2783, 2895), 'igibson.objects.articulated_object.URDFObject', 'URDFObject', ([], {'filename': 'model_path', 'category': '"""bowl"""', 'name': '"""bowl"""', 'abilities': "{'dustyable': {}, 'stainable': {}}"}), "(filename=model_path, category='bowl', name='bowl', abilities={\n 'dustyable': {}, 'stainable': {}})\n", (2793, 2895), False, 'from igibson.objects.articulated_object import URDFObject\n'), ((3128, 3141), 'pybullet.saveState', 'p.saveState', ([], {}), '()\n', (3139, 3141), True, 'import pybullet as p\n'), ((4873, 4912), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (4892, 4912), False, 'import logging\n'), ((1328, 1363), 'igibson.utils.assets_utils.get_ig_model_path', 'get_ig_model_path', (['"""sink"""', '"""sink_1"""'], {}), "('sink', 'sink_1')\n", (1345, 1363), False, 'from igibson.utils.assets_utils import get_ig_model_path\n'), ((2286, 2331), 'igibson.utils.assets_utils.get_ig_model_path', 'get_ig_model_path', (['"""breakfast_table"""', '"""19203"""'], {}), "('breakfast_table', '19203')\n", (2303, 2331), False, 'from igibson.utils.assets_utils import get_ig_model_path\n'), ((2724, 2757), 'igibson.utils.assets_utils.get_ig_model_path', 'get_ig_model_path', (['"""bowl"""', '"""68_0"""'], {}), "('bowl', '68_0')\n", (2741, 2757), False, 'from igibson.utils.assets_utils import get_ig_model_path\n'), ((1494, 1519), 'numpy.array', 'np.array', (['[0.8, 0.8, 0.8]'], {}), '([0.8, 0.8, 0.8])\n', (1502, 1519), True, 'import numpy as np\n'), ((2471, 2496), 'numpy.array', 'np.array', (['[0.8, 0.8, 0.8]'], {}), '([0.8, 0.8, 0.8])\n', (2479, 2496), True, 'import numpy as np\n'), ((4474, 4504), 'igibson.utils.utils.restoreState', 'restoreState', (['pb_initial_state'], {}), '(pb_initial_state)\n', (4486, 4504), False, 'from igibson.utils.utils import restoreState\n')] |
# coding=utf-8
# Copyright 2020 RigL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module has helper functions for the interpolation experiments."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
from rigl import str_sparsities
import tensorflow.compat.v1 as tf
from google_research.micronet_challenge import counting
DEFAULT_ERK_SCALE = 1.0
def mask_extract_name_fn(mask_name):
return re.findall('(.+)/mask:0', mask_name)[0]
def get_n_zeros(size, sparsity):
return int(np.floor(sparsity * size))
def calculate_sparsity(masks):
dense_params = tf.constant(0.)
sparse_params = tf.constant(0.)
for mask in masks:
dense_params += tf.cast(tf.size(mask), dtype=dense_params.dtype)
sparse_params += tf.cast(tf.reduce_sum(mask), dtype=sparse_params.dtype)
return 1. - sparse_params / dense_params
def get_mask_random_numpy(mask_shape, sparsity, random_state=None):
"""Creates a random sparse mask with deterministic sparsity.
Args:
mask_shape: list, used to obtain shape of the random mask.
sparsity: float, between 0 and 1.
random_state: np.random.RandomState, if given the shuffle call is made using
the RandomState
Returns:
numpy.ndarray
"""
flat_ones = np.ones(mask_shape).flatten()
n_zeros = get_n_zeros(flat_ones.size, sparsity)
flat_ones[:n_zeros] = 0
if random_state:
random_state.shuffle(flat_ones)
else:
np.random.shuffle(flat_ones)
new_mask = flat_ones.reshape(mask_shape)
return new_mask
def get_mask_random(mask, sparsity, dtype, random_state=None):
"""Creates a random sparse mask with deterministic sparsity.
Args:
mask: tf.Tensor, used to obtain shape of the random mask.
sparsity: float, between 0 and 1.
dtype: tf.dtype, type of the return value.
random_state: np.random.RandomState, if given the shuffle call is made using
the RandomState
Returns:
tf.Tensor
"""
new_mask_numpy = get_mask_random_numpy(
mask.shape.as_list(), sparsity, random_state=random_state)
new_mask = tf.constant(new_mask_numpy, dtype=dtype)
return new_mask
def get_sparsities_erdos_renyi(all_masks,
default_sparsity,
custom_sparsity_map,
include_kernel,
extract_name_fn=mask_extract_name_fn,
erk_power_scale=DEFAULT_ERK_SCALE):
"""Given the method, returns the sparsity of individual layers as a dict.
It ensures that the non-custom layers have a total parameter count as the one
with uniform sparsities. In other words for the layers which are not in the
custom_sparsity_map the following equation should be satisfied.
# eps * (p_1 * N_1 + p_2 * N_2) = (1 - default_sparsity) * (N_1 + N_2)
Args:
all_masks: list, of all mask Variables.
default_sparsity: float, between 0 and 1.
custom_sparsity_map: dict, <str, float> key/value pairs where the mask
correspond whose name is '{key}/mask:0' is set to the corresponding
sparsity value.
include_kernel: bool, if True kernel dimension are included in the scaling.
extract_name_fn: function, extracts the variable name.
erk_power_scale: float, if given used to take power of the ratio. Use
scale<1 to make the erdos_renyi softer.
Returns:
sparsities, dict of where keys() are equal to all_masks and individiual
masks are mapped to the their sparsities.
"""
# We have to enforce custom sparsities and then find the correct scaling
# factor.
is_eps_valid = False
# # The following loop will terminate worst case when all masks are in the
# custom_sparsity_map. This should probably never happen though, since once
# we have a single variable or more with the same constant, we have a valid
# epsilon. Note that for each iteration we add at least one variable to the
# custom_sparsity_map and therefore this while loop should terminate.
dense_layers = set()
while not is_eps_valid:
# We will start with all layers and try to find right epsilon. However if
# any probablity exceeds 1, we will make that layer dense and repeat the
# process (finding epsilon) with the non-dense layers.
# We want the total number of connections to be the same. Let say we have
# for layers with N_1, ..., N_4 parameters each. Let say after some
# iterations probability of some dense layers (3, 4) exceeded 1 and
# therefore we added them to the dense_layers set. Those layers will not
# scale with erdos_renyi, however we need to count them so that target
# paratemeter count is achieved. See below.
# eps * (p_1 * N_1 + p_2 * N_2) + (N_3 + N_4) =
# (1 - default_sparsity) * (N_1 + N_2 + N_3 + N_4)
# eps * (p_1 * N_1 + p_2 * N_2) =
# (1 - default_sparsity) * (N_1 + N_2) - default_sparsity * (N_3 + N_4)
# eps = rhs / (\sum_i p_i * N_i) = rhs / divisor.
divisor = 0
rhs = 0
raw_probabilities = {}
for mask in all_masks:
var_name = extract_name_fn(mask.name)
shape_list = mask.shape.as_list()
n_param = np.prod(shape_list)
n_zeros = get_n_zeros(n_param, default_sparsity)
if var_name in dense_layers:
# See `- default_sparsity * (N_3 + N_4)` part of the equation above.
rhs -= n_zeros
elif var_name in custom_sparsity_map:
# We ignore custom_sparsities in erdos-renyi calculations.
pass
else:
# Corresponds to `(1 - default_sparsity) * (N_1 + N_2)` part of the
# equation above.
n_ones = n_param - n_zeros
rhs += n_ones
# Erdos-Renyi probability: epsilon * (n_in + n_out / n_in * n_out).
if include_kernel:
raw_probabilities[mask.name] = (np.sum(shape_list) /
np.prod(shape_list))**erk_power_scale
else:
n_in, n_out = shape_list[-2:]
raw_probabilities[mask.name] = (n_in + n_out) / (n_in * n_out)
# Note that raw_probabilities[mask] * n_param gives the individual
# elements of the divisor.
divisor += raw_probabilities[mask.name] * n_param
# By multipliying individual probabilites with epsilon, we should get the
# number of parameters per layer correctly.
eps = rhs / divisor
# If eps * raw_probabilities[mask.name] > 1. We set the sparsities of that
# mask to 0., so they become part of dense_layers sets.
max_prob = np.max(list(raw_probabilities.values()))
max_prob_one = max_prob * eps
if max_prob_one > 1:
is_eps_valid = False
for mask_name, mask_raw_prob in raw_probabilities.items():
if mask_raw_prob == max_prob:
var_name = extract_name_fn(mask_name)
tf.logging.info('Sparsity of var: %s had to be set to 0.', var_name)
dense_layers.add(var_name)
else:
is_eps_valid = True
sparsities = {}
# With the valid epsilon, we can set sparsities of the remaning layers.
for mask in all_masks:
var_name = extract_name_fn(mask.name)
shape_list = mask.shape.as_list()
n_param = np.prod(shape_list)
if var_name in custom_sparsity_map:
sparsities[mask.name] = custom_sparsity_map[var_name]
tf.logging.info('layer: %s has custom sparsity: %f', var_name,
sparsities[mask.name])
elif var_name in dense_layers:
sparsities[mask.name] = 0.
else:
probability_one = eps * raw_probabilities[mask.name]
sparsities[mask.name] = 1. - probability_one
tf.logging.info('layer: %s, shape: %s, sparsity: %f', var_name, mask.shape,
sparsities[mask.name])
return sparsities
def get_sparsities_uniform(all_masks,
default_sparsity,
custom_sparsity_map,
extract_name_fn=mask_extract_name_fn):
"""Given the method, returns the sparsity of individual layers as a dict.
Args:
all_masks: list, of all mask Variables.
default_sparsity: float, between 0 and 1.
custom_sparsity_map: dict, <str, float> key/value pairs where the mask
correspond whose name is '{key}/mask:0' is set to the corresponding
sparsity value.
extract_name_fn: function, extracts the variable name.
Returns:
sparsities, dict of where keys() are equal to all_masks and individiual
masks are mapped to the their sparsities.
"""
sparsities = {}
for mask in all_masks:
var_name = extract_name_fn(mask.name)
if var_name in custom_sparsity_map:
sparsities[mask.name] = custom_sparsity_map[var_name]
else:
sparsities[mask.name] = default_sparsity
return sparsities
def get_sparsities_str(all_masks, default_sparsity):
"""Given the method, returns the sparsity of individual layers as a dict.
Args:
all_masks: list, of all mask Variables.
default_sparsity: float, between 0 and 1.
Returns:
sparsities, dict of where keys() are equal to all_masks and individiual
masks are mapped to the their sparsities.
"""
str_sparsities_parsed = str_sparsities.read_all()
if default_sparsity in str_sparsities_parsed:
sprsts = str_sparsities_parsed[default_sparsity]
sparsities = {mask.name: sprsts[mask.name] for mask in all_masks}
else:
raise ValueError('sparsity: %f is not defined' % default_sparsity)
return sparsities
def get_sparsities(all_masks,
method,
default_sparsity,
custom_sparsity_map,
extract_name_fn=mask_extract_name_fn,
erk_power_scale=DEFAULT_ERK_SCALE):
"""Given the method, returns the sparsity of individual layers as a dict.
Args:
all_masks: list, of all mask Variables.
method: str, 'random' or 'erdos_renyi'.
default_sparsity: float, between 0 and 1.
custom_sparsity_map: dict, <str, float> key/value pairs where the mask
correspond whose name is '{key}/mask:0' is set to the corresponding
sparsity value.
extract_name_fn: function, extracts the variable name.
erk_power_scale: float, passed to the erdos_renyi function.
Returns:
sparsities, dict of where keys() are equal to all_masks and individiual
masks are mapped to the their sparsities.
Raises:
ValueError: when a key from custom_sparsity not found in all_masks.
ValueError: when an invalid initialization option is given.
"""
# (1) Ensure all keys are valid and processed.
keys_found = set()
for mask in all_masks:
var_name = extract_name_fn(mask.name)
if var_name in custom_sparsity_map:
keys_found.add(var_name)
keys_given = set(custom_sparsity_map.keys())
if keys_found != keys_given:
diff = keys_given - keys_found
raise ValueError('No masks are found for the following names: %s' %
str(diff))
if method in ('erdos_renyi', 'erdos_renyi_kernel'):
include_kernel = method == 'erdos_renyi_kernel'
sparsities = get_sparsities_erdos_renyi(
all_masks,
default_sparsity,
custom_sparsity_map,
include_kernel=include_kernel,
extract_name_fn=extract_name_fn,
erk_power_scale=erk_power_scale)
elif method == 'random':
sparsities = get_sparsities_uniform(
all_masks,
default_sparsity,
custom_sparsity_map,
extract_name_fn=extract_name_fn)
elif method == 'str':
sparsities = get_sparsities_str(all_masks, default_sparsity)
else:
raise ValueError('Method: %s is not valid mask initialization method' %
method)
return sparsities
def get_mask_init_fn(all_masks,
method,
default_sparsity,
custom_sparsity_map,
mask_fn=get_mask_random,
erk_power_scale=DEFAULT_ERK_SCALE,
extract_name_fn=mask_extract_name_fn):
"""Returns a function for initializing masks randomly.
Args:
all_masks: list, of all masks to be updated.
method: str, method to initialize the masks, passed to the
sparse_utils.get_mask() function.
default_sparsity: float, if 0 mask left intact, if greater than one, a
fraction of the ones in each mask is flipped to 0.
custom_sparsity_map: dict, sparsity of individual variables can be
overridden here. Key should point to the correct variable name, and value
should be in [0, 1].
mask_fn: function, to initialize masks with given sparsity.
erk_power_scale: float, passed to get_sparsities.
extract_name_fn: function, used to grab names from the variable.
Returns:
A callable to run after an init op. See `init_fn` of
`tf.train.Scaffold`. Returns None if no `preinitialize_checkpoint` field
is set in `RunnerSpec`.
Raise:
ValueError: when there is no mask corresponding to a key in the
custom_sparsity_map.
"""
sparsities = get_sparsities(
all_masks,
method,
default_sparsity,
custom_sparsity_map,
erk_power_scale=erk_power_scale,
extract_name_fn=extract_name_fn)
tf.logging.info('Per layer sparsities are like the following: %s',
str(sparsities))
assign_ops = []
for mask in all_masks:
new_mask = mask_fn(mask, sparsities[mask.name], mask.dtype)
assign_op = tf.assign(mask, new_mask)
assign_ops.append(assign_op)
return tf.group(assign_ops)
## Calculating flops and parameters using a list of Keras layers.
def _get_kernel(layer):
"""Given the Keras layer returns the weights."""
if isinstance(layer, tf.keras.layers.DepthwiseConv2D):
return layer.depthwise_kernel
else:
return layer.kernel
def get_stats(masked_layers,
default_sparsity=0.8,
method='erdos_renyi',
custom_sparsities=None,
is_debug=False,
width=1.,
first_layer_name='conv1',
last_layer_name='conv_preds',
param_size=32,
erk_power_scale=DEFAULT_ERK_SCALE):
"""Given the Keras layer returns the size and FLOPS of the model.
Args:
masked_layers: list, of tf.keras.Layer.
default_sparsity: float, if 0 mask left intact, if greater than one, a
fraction of the ones in each mask is flipped to 0.
method: str, passed to the `.get_sparsities()` functions.
custom_sparsities: dictor None, sparsity of individual variables can be
overridden here. Key should point to the correct variable name, and value
should be in [0, 1].
is_debug: bool, if True prints individual stats for given layers.
width: float, multiplier for the individual layer widths.
first_layer_name: str, to scale the width correctly.
last_layer_name: str, to scale the width correctly.
param_size: int, number of bits to represent a single parameter.
erk_power_scale: float, passed to the get_sparsities function.
Returns:
total_flops, sum of multiply and add operations.
total_param_bits, total bits to represent the model during the inference.
real_sparsity, calculated independently omitting bias parameters.
"""
if custom_sparsities is None:
custom_sparsities = {}
sparsities = get_sparsities([_get_kernel(l) for l in masked_layers],
method,
default_sparsity,
custom_sparsities,
lambda a: a,
erk_power_scale=erk_power_scale)
total_flops = 0
total_param_bits = 0
total_params = 0.
n_zeros = 0.
for layer in masked_layers:
kernel = _get_kernel(layer)
k_shape = kernel.shape.as_list()
d_in, d_out = 2, 3
# If fully connected change indices.
if len(k_shape) == 2:
d_in, d_out = 0, 1
# and k_shape[d_in] != 1 since depthwise
if not kernel.name.startswith(first_layer_name) and k_shape[d_in] != 1:
k_shape[d_in] = int(k_shape[d_in] * width)
if not kernel.name.startswith(last_layer_name) and k_shape[d_out] != 1:
k_shape[d_out] = int(k_shape[d_out] * width)
if is_debug:
print(kernel.name, layer.input_shape, k_shape, sparsities[kernel.name])
if isinstance(layer, tf.keras.layers.Conv2D):
layer_op = counting.Conv2D(layer.input_shape[1], k_shape, layer.strides,
'same', True, 'relu')
elif isinstance(layer, tf.keras.layers.DepthwiseConv2D):
layer_op = counting.DepthWiseConv2D(layer.input_shape[1], k_shape,
layer.strides, 'same', True, 'relu')
elif isinstance(layer, tf.keras.layers.Dense):
layer_op = counting.FullyConnected(k_shape, True, 'relu')
else:
raise ValueError('Should not happen.')
param_count, n_mults, n_adds = counting.count_ops(layer_op,
sparsities[kernel.name],
param_size)
total_param_bits += param_count
total_flops += n_mults + n_adds
n_param = np.prod(k_shape)
total_params += n_param
n_zeros += int(n_param * sparsities[kernel.name])
return total_flops, total_param_bits, n_zeros / total_params
| [
"tensorflow.compat.v1.size",
"numpy.random.shuffle",
"numpy.sum",
"tensorflow.compat.v1.constant",
"numpy.floor",
"numpy.ones",
"numpy.prod",
"tensorflow.compat.v1.logging.info",
"tensorflow.compat.v1.assign",
"re.findall",
"google_research.micronet_challenge.counting.Conv2D",
"tensorflow.comp... | [((1167, 1183), 'tensorflow.compat.v1.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (1178, 1183), True, 'import tensorflow.compat.v1 as tf\n'), ((1201, 1217), 'tensorflow.compat.v1.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (1212, 1217), True, 'import tensorflow.compat.v1 as tf\n'), ((2625, 2665), 'tensorflow.compat.v1.constant', 'tf.constant', (['new_mask_numpy'], {'dtype': 'dtype'}), '(new_mask_numpy, dtype=dtype)\n', (2636, 2665), True, 'import tensorflow.compat.v1 as tf\n'), ((9667, 9692), 'rigl.str_sparsities.read_all', 'str_sparsities.read_all', ([], {}), '()\n', (9690, 9692), False, 'from rigl import str_sparsities\n'), ((13984, 14004), 'tensorflow.compat.v1.group', 'tf.group', (['assign_ops'], {}), '(assign_ops)\n', (13992, 14004), True, 'import tensorflow.compat.v1 as tf\n'), ((1002, 1038), 're.findall', 're.findall', (['"""(.+)/mask:0"""', 'mask_name'], {}), "('(.+)/mask:0', mask_name)\n", (1012, 1038), False, 'import re\n'), ((1090, 1115), 'numpy.floor', 'np.floor', (['(sparsity * size)'], {}), '(sparsity * size)\n', (1098, 1115), True, 'import numpy as np\n'), ((1996, 2024), 'numpy.random.shuffle', 'np.random.shuffle', (['flat_ones'], {}), '(flat_ones)\n', (2013, 2024), True, 'import numpy as np\n'), ((7694, 7713), 'numpy.prod', 'np.prod', (['shape_list'], {}), '(shape_list)\n', (7701, 7713), True, 'import numpy as np\n'), ((8120, 8222), 'tensorflow.compat.v1.logging.info', 'tf.logging.info', (['"""layer: %s, shape: %s, sparsity: %f"""', 'var_name', 'mask.shape', 'sparsities[mask.name]'], {}), "('layer: %s, shape: %s, sparsity: %f', var_name, mask.shape,\n sparsities[mask.name])\n", (8135, 8222), True, 'import tensorflow.compat.v1 as tf\n'), ((13915, 13940), 'tensorflow.compat.v1.assign', 'tf.assign', (['mask', 'new_mask'], {}), '(mask, new_mask)\n', (13924, 13940), True, 'import tensorflow.compat.v1 as tf\n'), ((17384, 17449), 'google_research.micronet_challenge.counting.count_ops', 'counting.count_ops', (['layer_op', 'sparsities[kernel.name]', 'param_size'], {}), '(layer_op, sparsities[kernel.name], param_size)\n', (17402, 17449), False, 'from google_research.micronet_challenge import counting\n'), ((17644, 17660), 'numpy.prod', 'np.prod', (['k_shape'], {}), '(k_shape)\n', (17651, 17660), True, 'import numpy as np\n'), ((1266, 1279), 'tensorflow.compat.v1.size', 'tf.size', (['mask'], {}), '(mask)\n', (1273, 1279), True, 'import tensorflow.compat.v1 as tf\n'), ((1336, 1355), 'tensorflow.compat.v1.reduce_sum', 'tf.reduce_sum', (['mask'], {}), '(mask)\n', (1349, 1355), True, 'import tensorflow.compat.v1 as tf\n'), ((1823, 1842), 'numpy.ones', 'np.ones', (['mask_shape'], {}), '(mask_shape)\n', (1830, 1842), True, 'import numpy as np\n'), ((5702, 5721), 'numpy.prod', 'np.prod', (['shape_list'], {}), '(shape_list)\n', (5709, 5721), True, 'import numpy as np\n'), ((7820, 7910), 'tensorflow.compat.v1.logging.info', 'tf.logging.info', (['"""layer: %s has custom sparsity: %f"""', 'var_name', 'sparsities[mask.name]'], {}), "('layer: %s has custom sparsity: %f', var_name, sparsities[\n mask.name])\n", (7835, 7910), True, 'import tensorflow.compat.v1 as tf\n'), ((16849, 16936), 'google_research.micronet_challenge.counting.Conv2D', 'counting.Conv2D', (['layer.input_shape[1]', 'k_shape', 'layer.strides', '"""same"""', '(True)', '"""relu"""'], {}), "(layer.input_shape[1], k_shape, layer.strides, 'same', True,\n 'relu')\n", (16864, 16936), False, 'from google_research.micronet_challenge import counting\n'), ((17044, 17140), 'google_research.micronet_challenge.counting.DepthWiseConv2D', 'counting.DepthWiseConv2D', (['layer.input_shape[1]', 'k_shape', 'layer.strides', '"""same"""', '(True)', '"""relu"""'], {}), "(layer.input_shape[1], k_shape, layer.strides,\n 'same', True, 'relu')\n", (17068, 17140), False, 'from google_research.micronet_challenge import counting\n'), ((7340, 7408), 'tensorflow.compat.v1.logging.info', 'tf.logging.info', (['"""Sparsity of var: %s had to be set to 0."""', 'var_name'], {}), "('Sparsity of var: %s had to be set to 0.', var_name)\n", (7355, 7408), True, 'import tensorflow.compat.v1 as tf\n'), ((17247, 17293), 'google_research.micronet_challenge.counting.FullyConnected', 'counting.FullyConnected', (['k_shape', '(True)', '"""relu"""'], {}), "(k_shape, True, 'relu')\n", (17270, 17293), False, 'from google_research.micronet_challenge import counting\n'), ((6352, 6370), 'numpy.sum', 'np.sum', (['shape_list'], {}), '(shape_list)\n', (6358, 6370), True, 'import numpy as np\n'), ((6415, 6434), 'numpy.prod', 'np.prod', (['shape_list'], {}), '(shape_list)\n', (6422, 6434), True, 'import numpy as np\n')] |
r"""
Tests for the :mod:`scglue.num` module
"""
# pylint: disable=redefined-outer-name, wildcard-import, unused-wildcard-import
import numpy as np
import pytest
import scglue
from .fixtures import *
def test_sigmoid():
assert scglue.num.sigmoid(0) == 0.5
assert 0 < scglue.num.sigmoid(-1) < 0.5 < scglue.num.sigmoid(1) < 1
def test_col_var(mat, spmat):
_ = scglue.num.col_var(mat)
_ = scglue.num.col_var(spmat)
_ = scglue.num.col_var(mat[:10, :2], spmat[:10, :][:, :2])
with pytest.raises(ValueError):
_ = scglue.num.col_var(mat, spmat)
def test_cov_mat(mat, spmat):
_ = scglue.num.cov_mat(mat)
_ = scglue.num.cov_mat(spmat)
_ = scglue.num.cov_mat(mat[:10], spmat[:10])
with pytest.raises(ValueError):
_ = scglue.num.cov_mat(mat, spmat)
def test_pcc_mat(mat, spmat):
pcc = scglue.num.pcc_mat(mat)
pcc = scglue.num.pcc_mat(mat, mat)
assert np.allclose(np.diag(pcc), 1)
assert not np.allclose(pcc, 1)
pcc = scglue.num.pcc_mat(spmat)
pcc = scglue.num.pcc_mat(spmat, spmat)
assert np.allclose(np.diag(pcc), 1)
assert not np.allclose(pcc, 1)
def test_spr_mat(mat, spmat):
spr = scglue.num.spr_mat(mat)
spr = scglue.num.spr_mat(mat, mat)
assert np.allclose(np.diag(spr), 1)
assert not np.allclose(spr, 1)
spr = scglue.num.spr_mat(spmat)
spr = scglue.num.spr_mat(spmat, spmat)
assert np.allclose(np.diag(spr), 1)
assert not np.allclose(spr, 1)
def test_tfidf(spmat):
assert np.allclose(
scglue.num.tfidf(spmat).toarray(),
scglue.num.tfidf(spmat.toarray())
)
def test_vertex_degrees(eidx, ewt):
degrees = scglue.num.vertex_degrees(eidx, ewt, direction="in")
assert np.allclose(degrees, np.array([1.0, 0.4, 0.8]))
degrees = scglue.num.vertex_degrees(eidx, ewt, direction="out")
assert np.allclose(degrees, np.array([1.0, 0.5, 0.7]))
degrees = scglue.num.vertex_degrees(eidx, ewt, direction="both")
assert np.allclose(degrees, np.array([1.0, 0.5, 0.8]))
def test_normalize_edges(eidx, ewt):
enorm = scglue.num.normalize_edges(eidx, ewt, method="in")
assert np.allclose(enorm, np.array([
1.0 / 1.0, 0.4 / 0.4,
0.7 / 0.8, 0.1 / 0.8
]))
enorm = scglue.num.normalize_edges(eidx, ewt, method="out")
assert np.allclose(enorm, np.array([
1.0 / 1.0, 0.4 / 0.5,
0.7 / 0.7, 0.1 / 0.5
]))
enorm = scglue.num.normalize_edges(eidx, ewt, method="sym")
assert np.allclose(enorm, np.array([
1.0 / np.sqrt(1.0 * 1.0), 0.4 / np.sqrt(0.4 * 0.5),
0.7 / np.sqrt(0.8 * 0.7), 0.1 / np.sqrt(0.8 * 0.5)
]))
enorm = scglue.num.normalize_edges(eidx, ewt, method="keepvar")
assert np.allclose(enorm, np.array([
1.0 / np.sqrt(1.0), 0.4 / np.sqrt(0.4),
0.7 / np.sqrt(0.8), 0.1 / np.sqrt(0.8)
]))
| [
"scglue.num.normalize_edges",
"scglue.num.vertex_degrees",
"scglue.num.tfidf",
"scglue.num.pcc_mat",
"numpy.allclose",
"scglue.num.cov_mat",
"scglue.num.sigmoid",
"scglue.num.col_var",
"pytest.raises",
"scglue.num.spr_mat",
"numpy.array",
"numpy.diag",
"numpy.sqrt"
] | [((377, 400), 'scglue.num.col_var', 'scglue.num.col_var', (['mat'], {}), '(mat)\n', (395, 400), False, 'import scglue\n'), ((409, 434), 'scglue.num.col_var', 'scglue.num.col_var', (['spmat'], {}), '(spmat)\n', (427, 434), False, 'import scglue\n'), ((443, 497), 'scglue.num.col_var', 'scglue.num.col_var', (['mat[:10, :2]', 'spmat[:10, :][:, :2]'], {}), '(mat[:10, :2], spmat[:10, :][:, :2])\n', (461, 497), False, 'import scglue\n'), ((617, 640), 'scglue.num.cov_mat', 'scglue.num.cov_mat', (['mat'], {}), '(mat)\n', (635, 640), False, 'import scglue\n'), ((649, 674), 'scglue.num.cov_mat', 'scglue.num.cov_mat', (['spmat'], {}), '(spmat)\n', (667, 674), False, 'import scglue\n'), ((683, 723), 'scglue.num.cov_mat', 'scglue.num.cov_mat', (['mat[:10]', 'spmat[:10]'], {}), '(mat[:10], spmat[:10])\n', (701, 723), False, 'import scglue\n'), ((845, 868), 'scglue.num.pcc_mat', 'scglue.num.pcc_mat', (['mat'], {}), '(mat)\n', (863, 868), False, 'import scglue\n'), ((879, 907), 'scglue.num.pcc_mat', 'scglue.num.pcc_mat', (['mat', 'mat'], {}), '(mat, mat)\n', (897, 907), False, 'import scglue\n'), ((993, 1018), 'scglue.num.pcc_mat', 'scglue.num.pcc_mat', (['spmat'], {}), '(spmat)\n', (1011, 1018), False, 'import scglue\n'), ((1029, 1061), 'scglue.num.pcc_mat', 'scglue.num.pcc_mat', (['spmat', 'spmat'], {}), '(spmat, spmat)\n', (1047, 1061), False, 'import scglue\n'), ((1179, 1202), 'scglue.num.spr_mat', 'scglue.num.spr_mat', (['mat'], {}), '(mat)\n', (1197, 1202), False, 'import scglue\n'), ((1213, 1241), 'scglue.num.spr_mat', 'scglue.num.spr_mat', (['mat', 'mat'], {}), '(mat, mat)\n', (1231, 1241), False, 'import scglue\n'), ((1327, 1352), 'scglue.num.spr_mat', 'scglue.num.spr_mat', (['spmat'], {}), '(spmat)\n', (1345, 1352), False, 'import scglue\n'), ((1363, 1395), 'scglue.num.spr_mat', 'scglue.num.spr_mat', (['spmat', 'spmat'], {}), '(spmat, spmat)\n', (1381, 1395), False, 'import scglue\n'), ((1663, 1715), 'scglue.num.vertex_degrees', 'scglue.num.vertex_degrees', (['eidx', 'ewt'], {'direction': '"""in"""'}), "(eidx, ewt, direction='in')\n", (1688, 1715), False, 'import scglue\n'), ((1789, 1842), 'scglue.num.vertex_degrees', 'scglue.num.vertex_degrees', (['eidx', 'ewt'], {'direction': '"""out"""'}), "(eidx, ewt, direction='out')\n", (1814, 1842), False, 'import scglue\n'), ((1916, 1970), 'scglue.num.vertex_degrees', 'scglue.num.vertex_degrees', (['eidx', 'ewt'], {'direction': '"""both"""'}), "(eidx, ewt, direction='both')\n", (1941, 1970), False, 'import scglue\n'), ((2081, 2131), 'scglue.num.normalize_edges', 'scglue.num.normalize_edges', (['eidx', 'ewt'], {'method': '"""in"""'}), "(eidx, ewt, method='in')\n", (2107, 2131), False, 'import scglue\n'), ((2252, 2303), 'scglue.num.normalize_edges', 'scglue.num.normalize_edges', (['eidx', 'ewt'], {'method': '"""out"""'}), "(eidx, ewt, method='out')\n", (2278, 2303), False, 'import scglue\n'), ((2424, 2475), 'scglue.num.normalize_edges', 'scglue.num.normalize_edges', (['eidx', 'ewt'], {'method': '"""sym"""'}), "(eidx, ewt, method='sym')\n", (2450, 2475), False, 'import scglue\n'), ((2656, 2711), 'scglue.num.normalize_edges', 'scglue.num.normalize_edges', (['eidx', 'ewt'], {'method': '"""keepvar"""'}), "(eidx, ewt, method='keepvar')\n", (2682, 2711), False, 'import scglue\n'), ((236, 257), 'scglue.num.sigmoid', 'scglue.num.sigmoid', (['(0)'], {}), '(0)\n', (254, 257), False, 'import scglue\n'), ((280, 302), 'scglue.num.sigmoid', 'scglue.num.sigmoid', (['(-1)'], {}), '(-1)\n', (298, 302), False, 'import scglue\n'), ((311, 332), 'scglue.num.sigmoid', 'scglue.num.sigmoid', (['(1)'], {}), '(1)\n', (329, 332), False, 'import scglue\n'), ((507, 532), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (520, 532), False, 'import pytest\n'), ((546, 576), 'scglue.num.col_var', 'scglue.num.col_var', (['mat', 'spmat'], {}), '(mat, spmat)\n', (564, 576), False, 'import scglue\n'), ((733, 758), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (746, 758), False, 'import pytest\n'), ((772, 802), 'scglue.num.cov_mat', 'scglue.num.cov_mat', (['mat', 'spmat'], {}), '(mat, spmat)\n', (790, 802), False, 'import scglue\n'), ((931, 943), 'numpy.diag', 'np.diag', (['pcc'], {}), '(pcc)\n', (938, 943), True, 'import numpy as np\n'), ((963, 982), 'numpy.allclose', 'np.allclose', (['pcc', '(1)'], {}), '(pcc, 1)\n', (974, 982), True, 'import numpy as np\n'), ((1085, 1097), 'numpy.diag', 'np.diag', (['pcc'], {}), '(pcc)\n', (1092, 1097), True, 'import numpy as np\n'), ((1117, 1136), 'numpy.allclose', 'np.allclose', (['pcc', '(1)'], {}), '(pcc, 1)\n', (1128, 1136), True, 'import numpy as np\n'), ((1265, 1277), 'numpy.diag', 'np.diag', (['spr'], {}), '(spr)\n', (1272, 1277), True, 'import numpy as np\n'), ((1297, 1316), 'numpy.allclose', 'np.allclose', (['spr', '(1)'], {}), '(spr, 1)\n', (1308, 1316), True, 'import numpy as np\n'), ((1419, 1431), 'numpy.diag', 'np.diag', (['spr'], {}), '(spr)\n', (1426, 1431), True, 'import numpy as np\n'), ((1451, 1470), 'numpy.allclose', 'np.allclose', (['spr', '(1)'], {}), '(spr, 1)\n', (1462, 1470), True, 'import numpy as np\n'), ((1748, 1773), 'numpy.array', 'np.array', (['[1.0, 0.4, 0.8]'], {}), '([1.0, 0.4, 0.8])\n', (1756, 1773), True, 'import numpy as np\n'), ((1875, 1900), 'numpy.array', 'np.array', (['[1.0, 0.5, 0.7]'], {}), '([1.0, 0.5, 0.7])\n', (1883, 1900), True, 'import numpy as np\n'), ((2003, 2028), 'numpy.array', 'np.array', (['[1.0, 0.5, 0.8]'], {}), '([1.0, 0.5, 0.8])\n', (2011, 2028), True, 'import numpy as np\n'), ((2162, 2216), 'numpy.array', 'np.array', (['[1.0 / 1.0, 0.4 / 0.4, 0.7 / 0.8, 0.1 / 0.8]'], {}), '([1.0 / 1.0, 0.4 / 0.4, 0.7 / 0.8, 0.1 / 0.8])\n', (2170, 2216), True, 'import numpy as np\n'), ((2334, 2388), 'numpy.array', 'np.array', (['[1.0 / 1.0, 0.4 / 0.5, 0.7 / 0.7, 0.1 / 0.5]'], {}), '([1.0 / 1.0, 0.4 / 0.5, 0.7 / 0.7, 0.1 / 0.5])\n', (2342, 2388), True, 'import numpy as np\n'), ((1528, 1551), 'scglue.num.tfidf', 'scglue.num.tfidf', (['spmat'], {}), '(spmat)\n', (1544, 1551), False, 'import scglue\n'), ((2531, 2549), 'numpy.sqrt', 'np.sqrt', (['(1.0 * 1.0)'], {}), '(1.0 * 1.0)\n', (2538, 2549), True, 'import numpy as np\n'), ((2557, 2575), 'numpy.sqrt', 'np.sqrt', (['(0.4 * 0.5)'], {}), '(0.4 * 0.5)\n', (2564, 2575), True, 'import numpy as np\n'), ((2591, 2609), 'numpy.sqrt', 'np.sqrt', (['(0.8 * 0.7)'], {}), '(0.8 * 0.7)\n', (2598, 2609), True, 'import numpy as np\n'), ((2617, 2635), 'numpy.sqrt', 'np.sqrt', (['(0.8 * 0.5)'], {}), '(0.8 * 0.5)\n', (2624, 2635), True, 'import numpy as np\n'), ((2767, 2779), 'numpy.sqrt', 'np.sqrt', (['(1.0)'], {}), '(1.0)\n', (2774, 2779), True, 'import numpy as np\n'), ((2787, 2799), 'numpy.sqrt', 'np.sqrt', (['(0.4)'], {}), '(0.4)\n', (2794, 2799), True, 'import numpy as np\n'), ((2815, 2827), 'numpy.sqrt', 'np.sqrt', (['(0.8)'], {}), '(0.8)\n', (2822, 2827), True, 'import numpy as np\n'), ((2835, 2847), 'numpy.sqrt', 'np.sqrt', (['(0.8)'], {}), '(0.8)\n', (2842, 2847), True, 'import numpy as np\n')] |
"""
This module contains classes to solve and simulate consumption-savings models, of the type
studied in ConsumptionSavingModel.py, with the addition of a discrete, exogenous, stochastic
Markov state (e.g. unemployment).
"""
import sys
sys.path.insert(0,'../')
from copy import deepcopy
import numpy as np
from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType
from HARKutilities import warnings # Because of "patch" to warnings modules
from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp
from HARKutilities import approxMeanOneLognormal, combineIndepDstns, CRRAutility, CRRAutilityP, \
CRRAutilityPP, CRRAutilityP_inv, CRRAutility_invP, CRRAutility_inv, \
CRRAutilityP_invP
utility = CRRAutility
utilityP = CRRAutilityP
utilityPP = CRRAutilityPP
utilityP_inv = CRRAutilityP_inv
utility_invP = CRRAutility_invP
utility_inv = CRRAutility_inv
utilityP_invP = CRRAutilityP_invP
class ConsumptionSavingSolverMarkov(ConsumptionSavingSolverENDG):
'''
A class to solve a single period consumption-saving problem with risky income
and stochastic transitions between discrete states, in a Markov fashion.
Extends ConsumptionSavingSolverENDG, with identical inputs but for a discrete
Markov state, whose transition rule is summarized in MrkvArray. Markov
states can differ in their interest factor, permanent growth factor, and
income distribution, so the inputs Rfree, PermGroFac, and IncomeDstn are
now arrays or lists specifying those values in each (succeeding) Markov state.
'''
def __init__(self,solution_next,IncomeDstn_list,LivPrb,DiscFac,
CRRA,Rfree_list,PermGroFac_list,MrkvArray,BoroCnstArt,
aXtraGrid,vFuncBool,CubicBool):
'''
Constructor for a new solver for a one period problem with risky income
and transitions between discrete Markov states (assume there are N states).
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncomeDstn_list : [[np.array]]
A length N list of income distributions in each succeeding Markov
state. Each income distribution contains three arrays of floats,
representing a discrete approximation to the income process at the
beginning of the succeeding period. Order: event probabilities,
permanent shocks, transitory shocks.
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the succeeding period.
DiscFac : float
Intertemporal discount factor for future utility.
CRRA : float
Coefficient of relative risk aversion.
Rfree_list : np.array
Risk free interest factor on end-of-period assets for each Markov
state in the succeeding period.
PermGroGac_list : float
Expected permanent income growth factor at the end of this period
for each Markov state in the succeeding period.
MrkvArray : numpy.array
An NxN array representing a Markov transition matrix between discrete
states. The i,j-th element of MrkvArray is the probability of
moving from state i in period t to state j in period t+1.
BoroCnstArt: float or None
Borrowing constraint for the minimum allowable assets to end the
period with. If it is less than the natural borrowing constraint,
then it is irrelevant; BoroCnstArt=None indicates no artificial bor-
rowing constraint.
aXtraGrid: np.array
Array of "extra" end-of-period asset values-- assets above the
absolute minimum acceptable level.
vFuncBool: boolean
An indicator for whether the value function should be computed and
included in the reported solution.
CubicBool: boolean
An indicator for whether the solver should use cubic or linear inter-
polation.
Returns
-------
None
'''
# Set basic attributes of the problem
ConsumptionSavingSolverENDG.assignParameters(self,solution_next,np.nan,
LivPrb,DiscFac,CRRA,np.nan,np.nan,
BoroCnstArt,aXtraGrid,vFuncBool,CubicBool)
self.defineUtilityFunctions()
# Set additional attributes specific to the Markov model
self.IncomeDstn_list = IncomeDstn_list
self.Rfree_list = Rfree_list
self.PermGroFac_list = PermGroFac_list
self.StateCount = len(IncomeDstn_list)
self.MrkvArray = MrkvArray
def solve(self):
'''
Solve the one period problem of the consumption-saving model with a Markov state.
Parameters
----------
none
Returns
-------
solution : ConsumerSolution
The solution to the single period consumption-saving problem. Includes
a consumption function cFunc (using cubic or linear splines), a marg-
inal value function vPfunc, a minimum acceptable level of normalized
market resources mNrmMin, normalized human wealth hNrm, and bounding
MPCs MPCmin and MPCmax. It might also have a value function vFunc
and marginal marginal value function vPPfunc. All of these attributes
are lists or arrays, with elements corresponding to the current
Markov state. E.g. solution.cFunc[0] is the consumption function
when in the i=0 Markov state this period.
'''
# Find the natural borrowing constraint in each current state
self.defBoundary()
# Initialize end-of-period (marginal) value functions
self.EndOfPrdvFunc_list = []
self.EndOfPrdvPfunc_list = []
self.ExIncNext = np.zeros(self.StateCount) + np.nan # expected income conditional on the next state
self.WorstIncPrbAll = np.zeros(self.StateCount) + np.nan # probability of getting the worst income shock in each next period state
# Loop through each next-period-state and calculate the end-of-period
# (marginal) value function
for j in range(self.StateCount):
# Condition values on next period's state (and record a couple for later use)
self.conditionOnState(j)
self.ExIncNext[j] = np.dot(self.ShkPrbsNext,
self.PermShkValsNext*self.TranShkValsNext)
self.WorstIncPrbAll[j] = self.WorstIncPrb
# Construct the end-of-period marginal value function conditional
# on next period's state and add it to the list of value functions
EndOfPrdvPfunc_cond = self.makeEndOfPrdvPfuncCond()
self.EndOfPrdvPfunc_list.append(EndOfPrdvPfunc_cond)
# Construct the end-of-period value functional conditional on next
# period's state and add it to the list of value functions
if self.vFuncBool:
EndOfPrdvFunc_cond = self.makeEndOfPrdvFuncCond()
self.EndOfPrdvFunc_list.append(EndOfPrdvFunc_cond)
# EndOfPrdvP_cond is EndOfPrdvP conditional on *next* period's state.
# Take expectations to get EndOfPrdvP conditional on *this* period's state.
self.calcEndOfPrdvP()
# Calculate the bounding MPCs and PDV of human wealth for each state
self.calcHumWealthAndBoundingMPCs()
# Find consumption and market resources corresponding to each end-of-period
# assets point for each state (and add an additional point at the lower bound)
aNrm = np.asarray(self.aXtraGrid)[np.newaxis,:] + np.array(self.BoroCnstNat_list)[:,np.newaxis]
self.getPointsForInterpolation(self.EndOfPrdvP,aNrm)
cNrm = np.hstack((np.zeros((self.StateCount,1)),self.cNrmNow))
mNrm = np.hstack((np.reshape(self.mNrmMin_list,(self.StateCount,1)),self.mNrmNow))
# Package and return the solution for this period
self.BoroCnstNat = self.BoroCnstNat_list
solution = self.makeSolution(cNrm,mNrm)
return solution
def defBoundary(self):
'''
Find the borrowing constraint for each current state and save it as an
attribute of self for use by other methods.
Parameters
----------
none
Returns
-------
none
'''
self.BoroCnstNatAll = np.zeros(self.StateCount) + np.nan
# Find the natural borrowing constraint conditional on next period's state
for j in range(self.StateCount):
PermShkMinNext = np.min(self.IncomeDstn_list[j][1])
TranShkMinNext = np.min(self.IncomeDstn_list[j][2])
self.BoroCnstNatAll[j] = (self.solution_next.mNrmMin[j] - TranShkMinNext)*\
(self.PermGroFac_list[j]*PermShkMinNext)/self.Rfree_list[j]
self.BoroCnstNat_list = np.zeros(self.StateCount) + np.nan
self.mNrmMin_list = np.zeros(self.StateCount) + np.nan
self.BoroCnstDependency = np.zeros((self.StateCount,self.StateCount)) + np.nan
# The natural borrowing constraint in each current state is the *highest*
# among next-state-conditional natural borrowing constraints that could
# occur from this current state.
for i in range(self.StateCount):
possible_next_states = self.MrkvArray[i,:] > 0
self.BoroCnstNat_list[i] = np.max(self.BoroCnstNatAll[possible_next_states])
self.mNrmMin_list[i] = np.max([self.BoroCnstNat_list[i],self.BoroCnstArt])
self.BoroCnstDependency[i,:] = self.BoroCnstNat_list[i] == self.BoroCnstNatAll
# Also creates a Boolean array indicating whether the natural borrowing
# constraint *could* be hit when transitioning from i to j.
def conditionOnState(self,state_index):
'''
Temporarily assume that a particular Markov state will occur in the
succeeding period, and condition solver attributes on this assumption.
Allows the solver to construct the future-state-conditional marginal
value function (etc) for that future state.
Parameters
----------
state_index : int
Index of the future Markov state to condition on.
Returns
-------
none
'''
# Set future-state-conditional values as attributes of self
self.IncomeDstn = self.IncomeDstn_list[state_index]
self.Rfree = self.Rfree_list[state_index]
self.PermGroFac = self.PermGroFac_list[state_index]
self.vPfuncNext = self.solution_next.vPfunc[state_index]
self.mNrmMinNow = self.mNrmMin_list[state_index]
self.BoroCnstNat = self.BoroCnstNatAll[state_index]
self.setAndUpdateValues(self.solution_next,self.IncomeDstn,self.LivPrb,self.DiscFac)
# These lines have to come after setAndUpdateValues to override the definitions there
self.vPfuncNext = self.solution_next.vPfunc[state_index]
if self.CubicBool:
self.vPPfuncNext= self.solution_next.vPPfunc[state_index]
if self.vFuncBool:
self.vFuncNext = self.solution_next.vFunc[state_index]
def getGothicvPP(self):
'''
Calculates end-of-period marginal marginal value using a pre-defined
array of next period market resources in self.mNrmNext.
Parameters
----------
none
Returns
-------
none
'''
EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*self.PermGroFac**(-self.CRRA-1.0)*\
np.sum(self.PermShkVals_temp**(-self.CRRA-1.0)*self.vPPfuncNext(self.mNrmNext)
*self.ShkPrbs_temp,axis=0)
return EndOfPrdvPP
def makeEndOfPrdvFuncCond(self):
'''
Construct the end-of-period value function conditional on next period's
state. NOTE: It might be possible to eliminate this method and replace
it with ConsumptionSavingSolverENDG.makeEndOfPrdvFunc, but the self.X_cond
variables must be renamed.
Parameters
----------
none
Returns
-------
EndofPrdvFunc_cond : ValueFunc
The end-of-period value function conditional on a particular state
occuring in the next period.
'''
VLvlNext = (self.PermShkVals_temp**(1.0-self.CRRA)*
self.PermGroFac**(1.0-self.CRRA))*self.vFuncNext(self.mNrmNext)
EndOfPrdv_cond = self.DiscFacEff*np.sum(VLvlNext*self.ShkPrbs_temp,axis=0)
EndOfPrdvNvrs_cond = self.uinv(EndOfPrdv_cond)
EndOfPrdvNvrsP_cond = self.EndOfPrdvP_cond*self.uinvP(EndOfPrdv_cond)
EndOfPrdvNvrs_cond = np.insert(EndOfPrdvNvrs_cond,0,0.0)
EndOfPrdvNvrsP_cond = np.insert(EndOfPrdvNvrsP_cond,0,EndOfPrdvNvrsP_cond[0])
aNrm_temp = np.insert(self.aNrm_cond,0,self.BoroCnstNat)
EndOfPrdvNvrsFunc_cond = CubicInterp(aNrm_temp,EndOfPrdvNvrs_cond,EndOfPrdvNvrsP_cond)
EndofPrdvFunc_cond = ValueFunc(EndOfPrdvNvrsFunc_cond,self.CRRA)
return EndofPrdvFunc_cond
def makeEndOfPrdvPfuncCond(self):
'''
Construct the end-of-period marginal value function conditional on next
period's state.
Parameters
----------
none
Returns
-------
EndofPrdvPfunc_cond : MargValueFunc
The end-of-period marginal value function conditional on a particular
state occuring in the succeeding period.
'''
# Get data to construct the end-of-period marginal value function (conditional on next state)
self.aNrm_cond = self.prepareToGetGothicvP()
self.EndOfPrdvP_cond= self.getGothicvP()
EndOfPrdvPnvrs_cond = self.uPinv(self.EndOfPrdvP_cond) # "decurved" marginal value
if self.CubicBool:
EndOfPrdvPP_cond = self.getGothicvPP()
EndOfPrdvPnvrsP_cond = EndOfPrdvPP_cond*self.uPinvP(self.EndOfPrdvP_cond) # "decurved" marginal marginal value
# Construct the end-of-period marginal value function conditional on the next state.
if self.CubicBool:
EndOfPrdvPnvrsFunc_cond = CubicInterp(self.aNrm_cond,EndOfPrdvPnvrs_cond,
EndOfPrdvPnvrsP_cond,lower_extrap=True)
else:
EndOfPrdvPnvrsFunc_cond = LinearInterp(self.aNrm_cond,EndOfPrdvPnvrs_cond,
lower_extrap=True)
EndofPrdvPfunc_cond = MargValueFunc(EndOfPrdvPnvrsFunc_cond,self.CRRA) # "recurve" the interpolated marginal value function
return EndofPrdvPfunc_cond
def calcEndOfPrdvP(self):
'''
Calculates end of period marginal value (and marginal marginal) value
at each aXtra gridpoint for each current state, unconditional on the
future Markov state (i.e. weighting conditional end-of-period marginal
value by transition probabilities).
Parameters
----------
none
Returns
-------
none
'''
# Find unique values of minimum acceptable end-of-period assets (and the
# current period states for which they apply).
aNrmMin_unique, state_inverse = np.unique(self.BoroCnstNat_list,return_inverse=True)
self.possible_transitions = self.MrkvArray > 0
# Calculate end-of-period marginal value (and marg marg value) at each
# asset gridpoint for each current period state
EndOfPrdvP = np.zeros((self.StateCount,self.aXtraGrid.size))
EndOfPrdvPP = np.zeros((self.StateCount,self.aXtraGrid.size))
for k in range(aNrmMin_unique.size):
aNrmMin = aNrmMin_unique[k] # minimum assets for this pass
which_states = state_inverse == k # the states for which this minimum applies
aGrid = aNrmMin + self.aXtraGrid # assets grid for this pass
EndOfPrdvP_all = np.zeros((self.StateCount,self.aXtraGrid.size))
EndOfPrdvPP_all = np.zeros((self.StateCount,self.aXtraGrid.size))
for j in range(self.StateCount):
if np.any(np.logical_and(self.possible_transitions[:,j],which_states)): # only consider a future state if one of the relevant states could transition to it
EndOfPrdvP_all[j,:] = self.EndOfPrdvPfunc_list[j](aGrid)
if self.CubicBool: # Add conditional end-of-period (marginal) marginal value to the arrays
EndOfPrdvPP_all[j,:] = self.EndOfPrdvPfunc_list[j].derivative(aGrid)
# Weight conditional marginal (marginal) values by transition probs
# to get unconditional marginal (marginal) value at each gridpoint.
EndOfPrdvP_temp = np.dot(self.MrkvArray,EndOfPrdvP_all)
EndOfPrdvP[which_states,:] = EndOfPrdvP_temp[which_states,:] # only take the states for which this asset minimum applies
if self.CubicBool:
EndOfPrdvPP_temp = np.dot(self.MrkvArray,EndOfPrdvPP_all)
EndOfPrdvPP[which_states,:] = EndOfPrdvPP_temp[which_states,:]
# Store the results as attributes of self
self.EndOfPrdvP = EndOfPrdvP
if self.CubicBool:
self.EndOfPrdvPP = EndOfPrdvPP
def calcHumWealthAndBoundingMPCs(self):
'''
Calculates human wealth and the maximum and minimum MPC for each current
period state, then stores them as attributes of self for use by other methods.
Parameters
----------
none
Returns
-------
none
'''
# Upper bound on MPC at lower m-bound
WorstIncPrb_array = self.BoroCnstDependency*np.tile(np.reshape(self.WorstIncPrbAll,
(1,self.StateCount)),(self.StateCount,1))
temp_array = self.MrkvArray*WorstIncPrb_array
WorstIncPrbNow = np.sum(temp_array,axis=1) # Probability of getting the "worst" income shock and transition from each current state
ExMPCmaxNext = (np.dot(temp_array,self.Rfree_list**(1.0-self.CRRA)*
self.solution_next.MPCmax**(-self.CRRA))/WorstIncPrbNow)**\
(-1.0/self.CRRA)
self.MPCmaxNow = 1.0/(1.0 + ((self.DiscFacEff*WorstIncPrbNow)**
(1.0/self.CRRA))/ExMPCmaxNext)
self.MPCmaxEff = self.MPCmaxNow
self.MPCmaxEff[self.BoroCnstNat_list < self.mNrmMin_list] = 1.0
# State-conditional PDV of human wealth
hNrmPlusIncNext = self.ExIncNext + self.solution_next.hNrm
self.hNrmNow = np.dot(self.MrkvArray,(self.PermGroFac_list/self.Rfree_list)*
hNrmPlusIncNext)
# Lower bound on MPC as m gets arbitrarily large
temp = (self.DiscFacEff*np.dot(self.MrkvArray,self.solution_next.MPCmin**
(-self.CRRA)*self.Rfree_list**(1.0-self.CRRA)))**(1.0/self.CRRA)
self.MPCminNow = 1.0/(1.0 + temp)
def makeSolution(self,cNrm,mNrm):
'''
Construct an object representing the solution to this period's problem.
Parameters
----------
cNrm : np.array
Array of normalized consumption values for interpolation. Each row
corresponds to a Markov state for this period.
mNrm : np.array
Array of normalized market resource values for interpolation. Each
row corresponds to a Markov state for this period.
Returns
-------
solution : ConsumerSolution
The solution to the single period consumption-saving problem. Includes
a consumption function cFunc (using cubic or linear splines), a marg-
inal value function vPfunc, a minimum acceptable level of normalized
market resources mNrmMin, normalized human wealth hNrm, and bounding
MPCs MPCmin and MPCmax. It might also have a value function vFunc
and marginal marginal value function vPPfunc. All of these attributes
are lists or arrays, with elements corresponding to the current
Markov state. E.g. solution.cFunc[0] is the consumption function
when in the i=0 Markov state this period.
'''
solution = ConsumerSolution() # An empty solution to which we'll add state-conditional solutions
# Calculate the MPC at each market resource gridpoint in each state (if desired)
if self.CubicBool:
dcda = self.EndOfPrdvPP/self.uPP(np.array(self.cNrmNow))
MPC = dcda/(dcda+1.0)
self.MPC_temp = np.hstack((np.reshape(self.MPCmaxNow,(self.StateCount,1)),MPC))
interpfunc = self.makeCubiccFunc
else:
interpfunc = self.makeLinearcFunc
# Loop through each current period state and add its solution to the overall solution
for i in range(self.StateCount):
# Set current-period-conditional human wealth and MPC bounds
self.hNrmNow_j = self.hNrmNow[i]
self.MPCminNow_j = self.MPCminNow[i]
if self.CubicBool:
self.MPC_temp_j = self.MPC_temp[i,:]
# Construct the consumption function by combining the constrained and unconstrained portions
self.cFuncNowCnst = LinearInterp([self.mNrmMin_list[i], self.mNrmMin_list[i]+1.0],
[0.0,1.0])
cFuncNowUnc = interpfunc(mNrm[i,:],cNrm[i,:])
cFuncNow = LowerEnvelope(cFuncNowUnc,self.cFuncNowCnst)
# Make the marginal value function and pack up the current-state-conditional solution
vPfuncNow = MargValueFunc(cFuncNow,self.CRRA)
solution_cond = ConsumerSolution(cFunc=cFuncNow, vPfunc=vPfuncNow,
mNrmMin=self.mNrmMinNow)
if self.CubicBool: # Add the state-conditional marginal marginal value function (if desired)
solution_cond = self.addvPPfunc(solution_cond)
# Add the current-state-conditional solution to the overall period solution
solution.appendSolution(solution_cond)
# Add the lower bounds of market resources, MPC limits, human resources,
# and the value functions to the overall solution
solution.mNrmMin = self.mNrmMin_list
solution = self.addMPCandHumanWealth(solution)
if self.vFuncBool:
vFuncNow = self.makevFunc(solution)
solution.vFunc = vFuncNow
# Return the overall solution to this period
return solution
def makeLinearcFunc(self,mNrm,cNrm):
'''
Make a linear interpolation to represent the (unconstrained) consumption
function conditional on the current period state.
Parameters
----------
mNrm : np.array
Array of normalized market resource values for interpolation.
cNrm : np.array
Array of normalized consumption values for interpolation.
Returns
-------
cFuncUnc: an instance of HARKinterpolation.LinearInterp
'''
cFuncUnc = LinearInterp(mNrm,cNrm,self.MPCminNow_j*self.hNrmNow_j,self.MPCminNow_j)
return cFuncUnc
def makeCubiccFunc(self,mNrm,cNrm):
'''
Make a cubic interpolation to represent the (unconstrained) consumption
function conditional on the current period state.
Parameters
----------
mNrm : np.array
Array of normalized market resource values for interpolation.
cNrm : np.array
Array of normalized consumption values for interpolation.
Returns
-------
cFuncUnc: an instance of HARKinterpolation.CubicInterp
'''
cFuncUnc = CubicInterp(mNrm,cNrm,self.MPC_temp_j,self.MPCminNow_j*self.hNrmNow_j,
self.MPCminNow_j)
return cFuncUnc
def makevFunc(self,solution):
'''
Construct the value function for each current state.
Parameters
----------
solution : ConsumerSolution
The solution to the single period consumption-saving problem. Must
have a consumption function cFunc (using cubic or linear splines) as
a list with elements corresponding to the current Markov state. E.g.
solution.cFunc[0] is the consumption function when in the i=0 Markov
state this period.
Returns
-------
vFuncNow : [ValueFunc]
A list of value functions (defined over normalized market resources
m) for each current period Markov state.
'''
vFuncNow = [] # Initialize an empty list of value functions
# Loop over each current period state and construct the value function
for i in range(self.StateCount):
# Make state-conditional grids of market resources and consumption
mNrmMin = self.mNrmMin_list[i]
mGrid = mNrmMin + self.aXtraGrid
cGrid = solution.cFunc[i](mGrid)
aGrid = mGrid - cGrid
# Calculate end-of-period value at each gridpoint
EndOfPrdv_all = np.zeros((self.StateCount,self.aXtraGrid.size))
for j in range(self.StateCount):
if self.possible_transitions[i,j]:
EndOfPrdv_all[j,:] = self.EndOfPrdvFunc_list[j](aGrid)
EndOfPrdv = np.dot(self.MrkvArray[i,:],EndOfPrdv_all)
# Calculate (normalized) value and marginal value at each gridpoint
vNrmNow = self.u(cGrid) + EndOfPrdv
vPnow = self.uP(cGrid)
# Make a "decurved" value function with the inverse utility function
vNvrs = self.uinv(vNrmNow) # value transformed through inverse utility
vNvrsP = vPnow*self.uinvP(vNrmNow)
mNrm_temp = np.insert(mGrid,0,mNrmMin) # add the lower bound
vNvrs = np.insert(vNvrs,0,0.0)
vNvrsP = np.insert(vNvrsP,0,self.MPCmaxEff[i]**(-self.CRRA/(1.0-self.CRRA)))
MPCminNvrs = self.MPCminNow[i]**(-self.CRRA/(1.0-self.CRRA))
vNvrsFunc_i = CubicInterp(mNrm_temp,vNvrs,vNvrsP,MPCminNvrs*self.hNrmNow[i],MPCminNvrs)
# "Recurve" the decurved value function and add it to the list
vFunc_i = ValueFunc(vNvrsFunc_i,self.CRRA)
vFuncNow.append(vFunc_i)
return vFuncNow
def solveConsumptionSavingMarkov(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,PermGroFac,
MrkvArray,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool):
'''
Solves a single period consumption-saving problem with risky income and
stochastic transitions between discrete states, in a Markov fashion. Has
identical inputs as solveConsumptionSavingENDG, except for a discrete
Markov transitionrule MrkvArray. Markov states can differ in their interest
factor, permanent growth factor, and income distribution, so the inputs Rfree, PermGroFac, and
IncomeDstn are arrays or lists specifying those values in each (succeeding) Markov state.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncomeDstn_list : [[np.array]]
A length N list of income distributions in each succeeding Markov
state. Each income distribution contains three arrays of floats,
representing a discrete approximation to the income process at the
beginning of the succeeding period. Order: event probabilities,
permanent shocks, transitory shocks.
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the succeeding period.
DiscFac : float
Intertemporal discount factor for future utility.
CRRA : float
Coefficient of relative risk aversion.
Rfree_list : np.array
Risk free interest factor on end-of-period assets for each Markov
state in the succeeding period.
PermGroGac_list : float
Expected permanent income growth factor at the end of this period
for each Markov state in the succeeding period.
MrkvArray : numpy.array
An NxN array representing a Markov transition matrix between discrete
states. The i,j-th element of MrkvArray is the probability of
moving from state i in period t to state j in period t+1.
BoroCnstArt: float or None
Borrowing constraint for the minimum allowable assets to end the
period with. If it is less than the natural borrowing constraint,
then it is irrelevant; BoroCnstArt=None indicates no artificial bor-
rowing constraint.
aXtraGrid: np.array
Array of "extra" end-of-period asset values-- assets above the
absolute minimum acceptable level.
vFuncBool: boolean
An indicator for whether the value function should be computed and
included in the reported solution.
CubicBool: boolean
An indicator for whether the solver should use cubic or linear inter-
polation.
Returns
-------
solution : ConsumerSolution
The solution to the single period consumption-saving problem. Includes
a consumption function cFunc (using cubic or linear splines), a marg-
inal value function vPfunc, a minimum acceptable level of normalized
market resources mNrmMin, normalized human wealth hNrm, and bounding
MPCs MPCmin and MPCmax. It might also have a value function vFunc
and marginal marginal value function vPPfunc. All of these attributes
are lists or arrays, with elements corresponding to the current
Markov state. E.g. solution.cFunc[0] is the consumption function
when in the i=0 Markov state this period.
'''
solver = ConsumptionSavingSolverMarkov(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rfree,
PermGroFac,MrkvArray,BoroCnstArt,aXtraGrid,vFuncBool,
CubicBool)
solution_now = solver.solve()
return solution_now
####################################################################################################
####################################################################################################
class MarkovConsumerType(IndShockConsumerType):
'''
An agent in the Markov consumption-saving model. His problem is defined by a sequence
of income distributions, survival probabilities, discount factors, and permanent
income growth rates, as well as time invariant values for risk aversion, the
interest rate, the grid of end-of-period assets, and how he is borrowing constrained.
'''
time_inv_ = IndShockConsumerType.time_inv_ + ['MrkvArray']
def __init__(self,cycles=1,time_flow=True,**kwds):
IndShockConsumerType.__init__(self,cycles=1,time_flow=True,**kwds)
self.solveOnePeriod = solveConsumptionSavingMarkov
def makeIncShkHist(self):
'''
Makes histories of simulated income shocks for this consumer type by
drawing from the discrete income distributions, respecting the Markov
state for each agent in each period. Should be run after makeMrkvHist().
Parameters
----------
none
Returns
-------
none
'''
orig_time = self.time_flow
self.timeFwd()
self.resetRNG()
# Initialize the shock histories
N = self.MrkvArray.shape[0]
PermShkHist = np.zeros((self.sim_periods,self.Nagents)) + np.nan
TranShkHist = np.zeros((self.sim_periods,self.Nagents)) + np.nan
PermShkHist[0,:] = 1.0
TranShkHist[0,:] = 1.0
t_idx = 0
# Draw income shocks for each simulated period, respecting the Markov state
for t in range(1,self.sim_periods):
MrkvNow = self.MrkvHist[t,:]
IncomeDstn_list = self.IncomeDstn[t_idx]
PermGroFac_list = self.PermGroFac[t_idx]
for n in range(N):
these = MrkvNow == n
IncomeDstnNow = IncomeDstn_list[n]
PermGroFacNow = PermGroFac_list[n]
Events = np.arange(IncomeDstnNow[0].size) # just a list of integers
Cutoffs = np.round(np.cumsum(IncomeDstnNow[0])*np.sum(these))
top = 0
# Make a list of event indices that closely matches the discrete income distribution
EventList = []
for j in range(Events.size):
bot = top
top = Cutoffs[j]
EventList += (top-bot)*[Events[j]]
# Randomly permute the event indices and store the corresponding results
EventDraws = self.RNG.permutation(EventList)
PermShkHist[t,these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow
TranShkHist[t,these] = IncomeDstnNow[2][EventDraws]
# Advance the time index, looping if we've run out of income distributions
t_idx += 1
if t_idx >= len(self.IncomeDstn):
t_idx = 0
# Store the results as attributes of self and restore time to its original flow
self.PermShkHist = PermShkHist
self.TranShkHist = TranShkHist
if not orig_time:
self.timeRev()
def makeMrkvHist(self):
'''
Makes a history of simulated discrete Markov states, starting from the
initial states in markov_init. Assumes that MrkvArray is constant.
Parameters
----------
none
Returns
-------
none
'''
orig_time = self.time_flow
self.timeFwd()
self.resetRNG()
# Initialize the Markov state history
MrkvHist = np.zeros((self.sim_periods,self.Nagents),dtype=int)
MrkvNow = self.Mrkv_init
MrkvHist[0,:] = MrkvNow
base_draws = np.arange(self.Nagents,dtype=float)/self.Nagents + 1.0/(2*self.Nagents)
# Make an array of Markov transition cutoffs
N = self.MrkvArray.shape[0] # number of states
Cutoffs = np.cumsum(self.MrkvArray,axis=1)
# Draw Markov transitions for each period
for t in range(1,self.sim_periods):
draws_now = self.RNG.permutation(base_draws)
MrkvNext = np.zeros(self.Nagents) + np.nan
for n in range(N):
these = MrkvNow == n
MrkvNext[these] = np.searchsorted(Cutoffs[n,:],draws_now[these])
MrkvHist[t,:] = MrkvNext
MrkvNow = MrkvNext
# Store the results and return time to its original flow
self.MrkvHist = MrkvHist
if not orig_time:
self.timeRev()
def simOnePrd(self):
'''
Simulate a single period of a consumption-saving model with permanent
and transitory income shocks.
Parameters
----------
none
Returns
-------
none
'''
# Unpack objects from self for convenience
aPrev = self.aNow
pPrev = self.pNow
TranShkNow = self.TranShkNow
PermShkNow = self.PermShkNow
RfreeNow = self.RfreeNow[self.MrkvNow]
cFuncNow = self.cFuncNow
# Simulate the period
pNow = pPrev*PermShkNow # Updated permanent income level
ReffNow = RfreeNow/PermShkNow # "effective" interest factor on normalized assets
bNow = ReffNow*aPrev # Bank balances before labor income
mNow = bNow + TranShkNow # Market resources after income
N = self.MrkvArray.shape[0]
cNow = np.zeros_like(mNow)
MPCnow = np.zeros_like(mNow)
for n in range(N):
these = self.MrkvNow == n
cNow[these], MPCnow[these] = cFuncNow[n].eval_with_derivative(mNow[these]) # Consumption and maginal propensity to consume
aNow = mNow - cNow # Assets after all actions are accomplished
# Store the new state and control variables
self.pNow = pNow
self.bNow = bNow
self.mNow = mNow
self.cNow = cNow
self.MPCnow = MPCnow
self.aNow = aNow
def advanceIncShks(self):
'''
Advance the permanent and transitory income shocks to the next period of
the shock history objects.
Parameters
----------
none
Returns
-------
none
'''
self.MrkvNow = self.MrkvHist[self.Shk_idx,:]
IndShockConsumerType.advanceIncShks(self)
def updateSolutionTerminal(self):
'''
Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
none
Returns
-------
none
'''
IndShockConsumerType.updateSolutionTerminal(self)
# Make replicated terminal period solution: consume all resources, no human wealth, minimum m is 0
StateCount = self.MrkvArray.shape[0]
self.solution_terminal.cFunc = StateCount*[self.cFunc_terminal_]
self.solution_terminal.vFunc = StateCount*[self.solution_terminal.vFunc]
self.solution_terminal.vPfunc = StateCount*[self.solution_terminal.vPfunc]
self.solution_terminal.vPPfunc = StateCount*[self.solution_terminal.vPPfunc]
self.solution_terminal.mNrmMin = np.zeros(StateCount)
self.solution_terminal.hRto = np.zeros(StateCount)
self.solution_terminal.MPCmax = np.ones(StateCount)
self.solution_terminal.MPCmin = np.ones(StateCount)
###############################################################################
if __name__ == '__main__':
import ConsumerParameters as Params
from HARKutilities import plotFuncs
from time import clock
from copy import copy
mystr = lambda number : "{:.4f}".format(number)
do_simulation = True
# Define the Markov transition matrix for serially correlated unemployment
unemp_length = 5 # Averange length of unemployment spell
urate_good = 0.05 # Unemployment rate when economy is in good state
urate_bad = 0.12 # Unemployment rate when economy is in bad state
bust_prob = 0.01 # Probability of economy switching from good to bad
recession_length = 20 # Averange length of bad state
p_reemploy =1.0/unemp_length
p_unemploy_good = p_reemploy*urate_good/(1-urate_good)
p_unemploy_bad = p_reemploy*urate_bad/(1-urate_bad)
boom_prob = 1.0/recession_length
MrkvArray = np.array([[(1-p_unemploy_good)*(1-bust_prob),p_unemploy_good*(1-bust_prob),
(1-p_unemploy_good)*bust_prob,p_unemploy_good*bust_prob],
[p_reemploy*(1-bust_prob),(1-p_reemploy)*(1-bust_prob),
p_reemploy*bust_prob,(1-p_reemploy)*bust_prob],
[(1-p_unemploy_bad)*boom_prob,p_unemploy_bad*boom_prob,
(1-p_unemploy_bad)*(1-boom_prob),p_unemploy_bad*(1-boom_prob)],
[p_reemploy*boom_prob,(1-p_reemploy)*boom_prob,
p_reemploy*(1-boom_prob),(1-p_reemploy)*(1-boom_prob)]])
# Make a consumer with serially correlated unemployment, subject to boom and bust cycles
init_serial_unemployment = copy(Params.init_idiosyncratic_shocks)
init_serial_unemployment['MrkvArray'] = MrkvArray
init_serial_unemployment['UnempPrb'] = 0 # to make income distribution when employed
SerialUnemploymentExample = MarkovConsumerType(**init_serial_unemployment)
SerialUnemploymentExample.cycles = 0
SerialUnemploymentExample.vFuncBool = False # for easy toggling here
# Replace the default (lognormal) income distribution with a custom one
employed_income_dist = [np.ones(1),np.ones(1),np.ones(1)] # Definitely get income
unemployed_income_dist = [np.ones(1),np.ones(1),np.zeros(1)] # Definitely don't
SerialUnemploymentExample.IncomeDstn = [[employed_income_dist,unemployed_income_dist,employed_income_dist,
unemployed_income_dist]]
# Interest factor and permanent growth rates are constant arrays
SerialUnemploymentExample.Rfree = np.array(4*[SerialUnemploymentExample.Rfree])
SerialUnemploymentExample.PermGroFac = [np.array(4*SerialUnemploymentExample.PermGroFac)]
# Solve the serial unemployment consumer's problem and display solution
SerialUnemploymentExample.timeFwd()
start_time = clock()
SerialUnemploymentExample.solve()
end_time = clock()
print('Solving a Markov consumer took ' + mystr(end_time-start_time) + ' seconds.')
print('Consumption functions for each discrete state:')
plotFuncs(SerialUnemploymentExample.solution[0].cFunc,0,50)
if SerialUnemploymentExample.vFuncBool:
print('Value functions for each discrete state:')
plotFuncs(SerialUnemploymentExample.solution[0].vFunc,5,50)
# Simulate some data; results stored in cHist, mHist, bHist, aHist, MPChist, and pHist
if do_simulation:
SerialUnemploymentExample.sim_periods = 120
SerialUnemploymentExample.Mrkv_init = np.zeros(SerialUnemploymentExample.Nagents,dtype=int)
SerialUnemploymentExample.makeMrkvHist()
SerialUnemploymentExample.makeIncShkHist()
SerialUnemploymentExample.initializeSim()
SerialUnemploymentExample.simConsHistory()
###############################################################################
# Make a consumer who occasionally gets "unemployment immunity" for a fixed period
UnempPrb = 0.05 # Probability of becoming unemployed each period
ImmunityPrb = 0.01 # Probability of becoming "immune" to unemployment
ImmunityT = 6 # Number of periods of immunity
StateCount = ImmunityT+1 # Total number of Markov states
IncomeDstnReg = [np.array([1-UnempPrb,UnempPrb]), np.array([1.0,1.0]), np.array([1.0/(1.0-UnempPrb),0.0])] # Ordinary income distribution
IncomeDstnImm = [np.array([1.0]), np.array([1.0]), np.array([1.0])] # Income distribution when unemployed
IncomeDstn = [IncomeDstnReg] + ImmunityT*[IncomeDstnImm] # Income distribution for each Markov state, in a list
# Make the Markov transition array. MrkvArray[i,j] is the probability of transitioning
# to state j in period t+1 from state i in period t.
MrkvArray = np.zeros((StateCount,StateCount))
MrkvArray[0,0] = 1.0 - ImmunityPrb # Probability of not becoming immune in ordinary state: stay in ordinary state
MrkvArray[0,ImmunityT] = ImmunityPrb # Probability of becoming immune in ordinary state: begin immunity periods
for j in range(ImmunityT):
MrkvArray[j+1,j] = 1.0 # When immune, have 100% chance of transition to state with one fewer immunity periods remaining
init_unemployment_immunity = copy(Params.init_idiosyncratic_shocks)
init_unemployment_immunity['MrkvArray'] = MrkvArray
ImmunityType = MarkovConsumerType(**init_unemployment_immunity)
ImmunityType.assignParameters(Rfree = np.array(np.array(StateCount*[1.03])), # Interest factor same in all states
PermGroFac = [np.array(StateCount*[1.01])], # Permanent growth factor same in all states
BoroCnstArt = None, # No artificial borrowing constraint
cycles = 0) # Infinite horizon
ImmunityType.IncomeDstn = [IncomeDstn]
# Solve the unemployment immunity problem and display the consumption functions
start_time = clock()
ImmunityType.solve()
end_time = clock()
print('Solving an "unemployment immunity" consumer took ' + mystr(end_time-start_time) + ' seconds.')
print('Consumption functions for each discrete state:')
mNrmMin = np.min([ImmunityType.solution[0].mNrmMin[j] for j in range(StateCount)])
plotFuncs(ImmunityType.solution[0].cFunc,mNrmMin,10)
###############################################################################
# Make a consumer with serially correlated permanent income growth
UnempPrb = 0.05 # Unemployment probability
StateCount = 5 # Number of permanent income growth rates
Persistence = 0.5 # Probability of getting the same permanent income growth rate next period
IncomeDstnReg = [np.array([1-UnempPrb,UnempPrb]), np.array([1.0,1.0]), np.array([1.0,0.0])]
IncomeDstn = StateCount*[IncomeDstnReg] # Same simple income distribution in each state
# Make the state transition array for this type: Persistence probability of remaining in the same state, equiprobable otherwise
MrkvArray = Persistence*np.eye(StateCount) + (1.0/StateCount)*(1.0-Persistence)*np.ones((StateCount,StateCount))
init_serial_growth = copy(Params.init_idiosyncratic_shocks)
init_serial_growth['MrkvArray'] = MrkvArray
SerialGroType = MarkovConsumerType(**init_serial_growth)
SerialGroType.assignParameters(Rfree = np.array(np.array(StateCount*[1.03])), # Same interest factor in each Markov state
PermGroFac = [np.array([0.97,0.99,1.01,1.03,1.05])], # Different permanent growth factor in each Markov state
cycles = 0)
SerialGroType.IncomeDstn = [IncomeDstn]
# Solve the serially correlated permanent growth shock problem and display the consumption functions
start_time = clock()
SerialGroType.solve()
end_time = clock()
print('Solving a serially correlated growth consumer took ' + mystr(end_time-start_time) + ' seconds.')
print('Consumption functions for each discrete state:')
plotFuncs(SerialGroType.solution[0].cFunc,0,10)
###############################################################################
# Make a consumer with serially correlated interest factors
SerialRType = deepcopy(SerialGroType) # Same as the last problem...
SerialRType.assignParameters(PermGroFac = [np.array(StateCount*[1.01])], # ...but now the permanent growth factor is constant...
Rfree = np.array([1.01,1.02,1.03,1.04,1.05])) # ...and the interest factor is what varies across states
# Solve the serially correlated interest rate problem and display the consumption functions
start_time = clock()
SerialRType.solve()
end_time = clock()
print('Solving a serially correlated interest consumer took ' + mystr(end_time-start_time) + ' seconds.')
print('Consumption functions for each discrete state:')
plotFuncs(SerialRType.solution[0].cFunc,0,10)
| [
"numpy.sum",
"numpy.ones",
"ConsumptionSavingModel.IndShockConsumerType.__init__",
"numpy.arange",
"numpy.unique",
"numpy.zeros_like",
"ConsumptionSavingModel.IndShockConsumerType.advanceIncShks",
"time.clock",
"numpy.insert",
"numpy.cumsum",
"numpy.max",
"HARKinterpolation.LinearInterp",
"n... | [((240, 265), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../"""'], {}), "(0, '../')\n", (255, 265), False, 'import sys\n'), ((40603, 41166), 'numpy.array', 'np.array', (['[[(1 - p_unemploy_good) * (1 - bust_prob), p_unemploy_good * (1 - bust_prob\n ), (1 - p_unemploy_good) * bust_prob, p_unemploy_good * bust_prob], [\n p_reemploy * (1 - bust_prob), (1 - p_reemploy) * (1 - bust_prob), \n p_reemploy * bust_prob, (1 - p_reemploy) * bust_prob], [(1 -\n p_unemploy_bad) * boom_prob, p_unemploy_bad * boom_prob, (1 -\n p_unemploy_bad) * (1 - boom_prob), p_unemploy_bad * (1 - boom_prob)], [\n p_reemploy * boom_prob, (1 - p_reemploy) * boom_prob, p_reemploy * (1 -\n boom_prob), (1 - p_reemploy) * (1 - boom_prob)]]'], {}), '([[(1 - p_unemploy_good) * (1 - bust_prob), p_unemploy_good * (1 -\n bust_prob), (1 - p_unemploy_good) * bust_prob, p_unemploy_good *\n bust_prob], [p_reemploy * (1 - bust_prob), (1 - p_reemploy) * (1 -\n bust_prob), p_reemploy * bust_prob, (1 - p_reemploy) * bust_prob], [(1 -\n p_unemploy_bad) * boom_prob, p_unemploy_bad * boom_prob, (1 -\n p_unemploy_bad) * (1 - boom_prob), p_unemploy_bad * (1 - boom_prob)], [\n p_reemploy * boom_prob, (1 - p_reemploy) * boom_prob, p_reemploy * (1 -\n boom_prob), (1 - p_reemploy) * (1 - boom_prob)]])\n', (40611, 41166), True, 'import numpy as np\n'), ((41404, 41442), 'copy.copy', 'copy', (['Params.init_idiosyncratic_shocks'], {}), '(Params.init_idiosyncratic_shocks)\n', (41408, 41442), False, 'from copy import copy\n'), ((42310, 42357), 'numpy.array', 'np.array', (['(4 * [SerialUnemploymentExample.Rfree])'], {}), '(4 * [SerialUnemploymentExample.Rfree])\n', (42318, 42357), True, 'import numpy as np\n'), ((42588, 42595), 'time.clock', 'clock', ([], {}), '()\n', (42593, 42595), False, 'from time import clock\n'), ((42649, 42656), 'time.clock', 'clock', ([], {}), '()\n', (42654, 42656), False, 'from time import clock\n'), ((42809, 42870), 'HARKutilities.plotFuncs', 'plotFuncs', (['SerialUnemploymentExample.solution[0].cFunc', '(0)', '(50)'], {}), '(SerialUnemploymentExample.solution[0].cFunc, 0, 50)\n', (42818, 42870), False, 'from HARKutilities import plotFuncs\n'), ((44497, 44531), 'numpy.zeros', 'np.zeros', (['(StateCount, StateCount)'], {}), '((StateCount, StateCount))\n', (44505, 44531), True, 'import numpy as np\n'), ((44965, 45003), 'copy.copy', 'copy', (['Params.init_idiosyncratic_shocks'], {}), '(Params.init_idiosyncratic_shocks)\n', (44969, 45003), False, 'from copy import copy\n'), ((45739, 45746), 'time.clock', 'clock', ([], {}), '()\n', (45744, 45746), False, 'from time import clock\n'), ((45787, 45794), 'time.clock', 'clock', ([], {}), '()\n', (45792, 45794), False, 'from time import clock\n'), ((46052, 46106), 'HARKutilities.plotFuncs', 'plotFuncs', (['ImmunityType.solution[0].cFunc', 'mNrmMin', '(10)'], {}), '(ImmunityType.solution[0].cFunc, mNrmMin, 10)\n', (46061, 46106), False, 'from HARKutilities import plotFuncs\n'), ((46957, 46995), 'copy.copy', 'copy', (['Params.init_idiosyncratic_shocks'], {}), '(Params.init_idiosyncratic_shocks)\n', (46961, 46995), False, 'from copy import copy\n'), ((47609, 47616), 'time.clock', 'clock', ([], {}), '()\n', (47614, 47616), False, 'from time import clock\n'), ((47658, 47665), 'time.clock', 'clock', ([], {}), '()\n', (47663, 47665), False, 'from time import clock\n'), ((47838, 47887), 'HARKutilities.plotFuncs', 'plotFuncs', (['SerialGroType.solution[0].cFunc', '(0)', '(10)'], {}), '(SerialGroType.solution[0].cFunc, 0, 10)\n', (47847, 47887), False, 'from HARKutilities import plotFuncs\n'), ((48058, 48081), 'copy.deepcopy', 'deepcopy', (['SerialGroType'], {}), '(SerialGroType)\n', (48066, 48081), False, 'from copy import deepcopy\n'), ((48502, 48509), 'time.clock', 'clock', ([], {}), '()\n', (48507, 48509), False, 'from time import clock\n'), ((48549, 48556), 'time.clock', 'clock', ([], {}), '()\n', (48554, 48556), False, 'from time import clock\n'), ((48731, 48778), 'HARKutilities.plotFuncs', 'plotFuncs', (['SerialRType.solution[0].cFunc', '(0)', '(10)'], {}), '(SerialRType.solution[0].cFunc, 0, 10)\n', (48740, 48778), False, 'from HARKutilities import plotFuncs\n'), ((4369, 4535), 'ConsumptionSavingModel.ConsumptionSavingSolverENDG.assignParameters', 'ConsumptionSavingSolverENDG.assignParameters', (['self', 'solution_next', 'np.nan', 'LivPrb', 'DiscFac', 'CRRA', 'np.nan', 'np.nan', 'BoroCnstArt', 'aXtraGrid', 'vFuncBool', 'CubicBool'], {}), '(self, solution_next, np.nan,\n LivPrb, DiscFac, CRRA, np.nan, np.nan, BoroCnstArt, aXtraGrid,\n vFuncBool, CubicBool)\n', (4413, 4535), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((13522, 13559), 'numpy.insert', 'np.insert', (['EndOfPrdvNvrs_cond', '(0)', '(0.0)'], {}), '(EndOfPrdvNvrs_cond, 0, 0.0)\n', (13531, 13559), True, 'import numpy as np\n'), ((13591, 13648), 'numpy.insert', 'np.insert', (['EndOfPrdvNvrsP_cond', '(0)', 'EndOfPrdvNvrsP_cond[0]'], {}), '(EndOfPrdvNvrsP_cond, 0, EndOfPrdvNvrsP_cond[0])\n', (13600, 13648), True, 'import numpy as np\n'), ((13680, 13726), 'numpy.insert', 'np.insert', (['self.aNrm_cond', '(0)', 'self.BoroCnstNat'], {}), '(self.aNrm_cond, 0, self.BoroCnstNat)\n', (13689, 13726), True, 'import numpy as np\n'), ((13758, 13821), 'HARKinterpolation.CubicInterp', 'CubicInterp', (['aNrm_temp', 'EndOfPrdvNvrs_cond', 'EndOfPrdvNvrsP_cond'], {}), '(aNrm_temp, EndOfPrdvNvrs_cond, EndOfPrdvNvrsP_cond)\n', (13769, 13821), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((13853, 13897), 'ConsumptionSavingModel.ValueFunc', 'ValueFunc', (['EndOfPrdvNvrsFunc_cond', 'self.CRRA'], {}), '(EndOfPrdvNvrsFunc_cond, self.CRRA)\n', (13862, 13897), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((15429, 15478), 'ConsumptionSavingModel.MargValueFunc', 'MargValueFunc', (['EndOfPrdvPnvrsFunc_cond', 'self.CRRA'], {}), '(EndOfPrdvPnvrsFunc_cond, self.CRRA)\n', (15442, 15478), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((16201, 16254), 'numpy.unique', 'np.unique', (['self.BoroCnstNat_list'], {'return_inverse': '(True)'}), '(self.BoroCnstNat_list, return_inverse=True)\n', (16210, 16254), True, 'import numpy as np\n'), ((16497, 16545), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.aXtraGrid.size)'], {}), '((self.StateCount, self.aXtraGrid.size))\n', (16505, 16545), True, 'import numpy as np\n'), ((16585, 16633), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.aXtraGrid.size)'], {}), '((self.StateCount, self.aXtraGrid.size))\n', (16593, 16633), True, 'import numpy as np\n'), ((18963, 18989), 'numpy.sum', 'np.sum', (['temp_array'], {'axis': '(1)'}), '(temp_array, axis=1)\n', (18969, 18989), True, 'import numpy as np\n'), ((19686, 19771), 'numpy.dot', 'np.dot', (['self.MrkvArray', '(self.PermGroFac_list / self.Rfree_list * hNrmPlusIncNext)'], {}), '(self.MrkvArray, self.PermGroFac_list / self.Rfree_list * hNrmPlusIncNext\n )\n', (19692, 19771), True, 'import numpy as np\n'), ((21396, 21414), 'ConsumptionSavingModel.ConsumerSolution', 'ConsumerSolution', ([], {}), '()\n', (21412, 21414), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((24416, 24493), 'HARKinterpolation.LinearInterp', 'LinearInterp', (['mNrm', 'cNrm', '(self.MPCminNow_j * self.hNrmNow_j)', 'self.MPCminNow_j'], {}), '(mNrm, cNrm, self.MPCminNow_j * self.hNrmNow_j, self.MPCminNow_j)\n', (24428, 24493), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((25087, 25184), 'HARKinterpolation.CubicInterp', 'CubicInterp', (['mNrm', 'cNrm', 'self.MPC_temp_j', '(self.MPCminNow_j * self.hNrmNow_j)', 'self.MPCminNow_j'], {}), '(mNrm, cNrm, self.MPC_temp_j, self.MPCminNow_j * self.hNrmNow_j,\n self.MPCminNow_j)\n', (25098, 25184), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((32451, 32520), 'ConsumptionSavingModel.IndShockConsumerType.__init__', 'IndShockConsumerType.__init__', (['self'], {'cycles': '(1)', 'time_flow': '(True)'}), '(self, cycles=1, time_flow=True, **kwds)\n', (32480, 32520), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((35567, 35620), 'numpy.zeros', 'np.zeros', (['(self.sim_periods, self.Nagents)'], {'dtype': 'int'}), '((self.sim_periods, self.Nagents), dtype=int)\n', (35575, 35620), True, 'import numpy as np\n'), ((35921, 35954), 'numpy.cumsum', 'np.cumsum', (['self.MrkvArray'], {'axis': '(1)'}), '(self.MrkvArray, axis=1)\n', (35930, 35954), True, 'import numpy as np\n'), ((37552, 37571), 'numpy.zeros_like', 'np.zeros_like', (['mNow'], {}), '(mNow)\n', (37565, 37571), True, 'import numpy as np\n'), ((37589, 37608), 'numpy.zeros_like', 'np.zeros_like', (['mNow'], {}), '(mNow)\n', (37602, 37608), True, 'import numpy as np\n'), ((38466, 38507), 'ConsumptionSavingModel.IndShockConsumerType.advanceIncShks', 'IndShockConsumerType.advanceIncShks', (['self'], {}), '(self)\n', (38501, 38507), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((38827, 38876), 'ConsumptionSavingModel.IndShockConsumerType.updateSolutionTerminal', 'IndShockConsumerType.updateSolutionTerminal', (['self'], {}), '(self)\n', (38870, 38876), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((39406, 39426), 'numpy.zeros', 'np.zeros', (['StateCount'], {}), '(StateCount)\n', (39414, 39426), True, 'import numpy as np\n'), ((39468, 39488), 'numpy.zeros', 'np.zeros', (['StateCount'], {}), '(StateCount)\n', (39476, 39488), True, 'import numpy as np\n'), ((39530, 39549), 'numpy.ones', 'np.ones', (['StateCount'], {}), '(StateCount)\n', (39537, 39549), True, 'import numpy as np\n'), ((39591, 39610), 'numpy.ones', 'np.ones', (['StateCount'], {}), '(StateCount)\n', (39598, 39610), True, 'import numpy as np\n'), ((41890, 41900), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (41897, 41900), True, 'import numpy as np\n'), ((41901, 41911), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (41908, 41911), True, 'import numpy as np\n'), ((41912, 41922), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (41919, 41922), True, 'import numpy as np\n'), ((41978, 41988), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (41985, 41988), True, 'import numpy as np\n'), ((41989, 41999), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (41996, 41999), True, 'import numpy as np\n'), ((42000, 42011), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (42008, 42011), True, 'import numpy as np\n'), ((42400, 42450), 'numpy.array', 'np.array', (['(4 * SerialUnemploymentExample.PermGroFac)'], {}), '(4 * SerialUnemploymentExample.PermGroFac)\n', (42408, 42450), True, 'import numpy as np\n'), ((42979, 43040), 'HARKutilities.plotFuncs', 'plotFuncs', (['SerialUnemploymentExample.solution[0].vFunc', '(5)', '(50)'], {}), '(SerialUnemploymentExample.solution[0].vFunc, 5, 50)\n', (42988, 43040), False, 'from HARKutilities import plotFuncs\n'), ((43255, 43309), 'numpy.zeros', 'np.zeros', (['SerialUnemploymentExample.Nagents'], {'dtype': 'int'}), '(SerialUnemploymentExample.Nagents, dtype=int)\n', (43263, 43309), True, 'import numpy as np\n'), ((43980, 44014), 'numpy.array', 'np.array', (['[1 - UnempPrb, UnempPrb]'], {}), '([1 - UnempPrb, UnempPrb])\n', (43988, 44014), True, 'import numpy as np\n'), ((44013, 44033), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (44021, 44033), True, 'import numpy as np\n'), ((44034, 44073), 'numpy.array', 'np.array', (['[1.0 / (1.0 - UnempPrb), 0.0]'], {}), '([1.0 / (1.0 - UnempPrb), 0.0])\n', (44042, 44073), True, 'import numpy as np\n'), ((44122, 44137), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (44130, 44137), True, 'import numpy as np\n'), ((44139, 44154), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (44147, 44154), True, 'import numpy as np\n'), ((44156, 44171), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (44164, 44171), True, 'import numpy as np\n'), ((46506, 46540), 'numpy.array', 'np.array', (['[1 - UnempPrb, UnempPrb]'], {}), '([1 - UnempPrb, UnempPrb])\n', (46514, 46540), True, 'import numpy as np\n'), ((46539, 46559), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (46547, 46559), True, 'import numpy as np\n'), ((46560, 46580), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (46568, 46580), True, 'import numpy as np\n'), ((6240, 6265), 'numpy.zeros', 'np.zeros', (['self.StateCount'], {}), '(self.StateCount)\n', (6248, 6265), True, 'import numpy as np\n'), ((6358, 6383), 'numpy.zeros', 'np.zeros', (['self.StateCount'], {}), '(self.StateCount)\n', (6366, 6383), True, 'import numpy as np\n'), ((6787, 6856), 'numpy.dot', 'np.dot', (['self.ShkPrbsNext', '(self.PermShkValsNext * self.TranShkValsNext)'], {}), '(self.ShkPrbsNext, self.PermShkValsNext * self.TranShkValsNext)\n', (6793, 6856), True, 'import numpy as np\n'), ((8973, 8998), 'numpy.zeros', 'np.zeros', (['self.StateCount'], {}), '(self.StateCount)\n', (8981, 8998), True, 'import numpy as np\n'), ((9169, 9203), 'numpy.min', 'np.min', (['self.IncomeDstn_list[j][1]'], {}), '(self.IncomeDstn_list[j][1])\n', (9175, 9203), True, 'import numpy as np\n'), ((9241, 9275), 'numpy.min', 'np.min', (['self.IncomeDstn_list[j][2]'], {}), '(self.IncomeDstn_list[j][2])\n', (9247, 9275), True, 'import numpy as np\n'), ((9496, 9521), 'numpy.zeros', 'np.zeros', (['self.StateCount'], {}), '(self.StateCount)\n', (9504, 9521), True, 'import numpy as np\n'), ((9565, 9590), 'numpy.zeros', 'np.zeros', (['self.StateCount'], {}), '(self.StateCount)\n', (9573, 9590), True, 'import numpy as np\n'), ((9634, 9678), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.StateCount)'], {}), '((self.StateCount, self.StateCount))\n', (9642, 9678), True, 'import numpy as np\n'), ((10041, 10090), 'numpy.max', 'np.max', (['self.BoroCnstNatAll[possible_next_states]'], {}), '(self.BoroCnstNatAll[possible_next_states])\n', (10047, 10090), True, 'import numpy as np\n'), ((10134, 10186), 'numpy.max', 'np.max', (['[self.BoroCnstNat_list[i], self.BoroCnstArt]'], {}), '([self.BoroCnstNat_list[i], self.BoroCnstArt])\n', (10140, 10186), True, 'import numpy as np\n'), ((13307, 13351), 'numpy.sum', 'np.sum', (['(VLvlNext * self.ShkPrbs_temp)'], {'axis': '(0)'}), '(VLvlNext * self.ShkPrbs_temp, axis=0)\n', (13313, 13351), True, 'import numpy as np\n'), ((15078, 15171), 'HARKinterpolation.CubicInterp', 'CubicInterp', (['self.aNrm_cond', 'EndOfPrdvPnvrs_cond', 'EndOfPrdvPnvrsP_cond'], {'lower_extrap': '(True)'}), '(self.aNrm_cond, EndOfPrdvPnvrs_cond, EndOfPrdvPnvrsP_cond,\n lower_extrap=True)\n', (15089, 15171), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((15268, 15336), 'HARKinterpolation.LinearInterp', 'LinearInterp', (['self.aNrm_cond', 'EndOfPrdvPnvrs_cond'], {'lower_extrap': '(True)'}), '(self.aNrm_cond, EndOfPrdvPnvrs_cond, lower_extrap=True)\n', (15280, 15336), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((16960, 17008), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.aXtraGrid.size)'], {}), '((self.StateCount, self.aXtraGrid.size))\n', (16968, 17008), True, 'import numpy as np\n'), ((17038, 17086), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.aXtraGrid.size)'], {}), '((self.StateCount, self.aXtraGrid.size))\n', (17046, 17086), True, 'import numpy as np\n'), ((17774, 17812), 'numpy.dot', 'np.dot', (['self.MrkvArray', 'EndOfPrdvP_all'], {}), '(self.MrkvArray, EndOfPrdvP_all)\n', (17780, 17812), True, 'import numpy as np\n'), ((22489, 22565), 'HARKinterpolation.LinearInterp', 'LinearInterp', (['[self.mNrmMin_list[i], self.mNrmMin_list[i] + 1.0]', '[0.0, 1.0]'], {}), '([self.mNrmMin_list[i], self.mNrmMin_list[i] + 1.0], [0.0, 1.0])\n', (22501, 22565), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((22704, 22749), 'HARKinterpolation.LowerEnvelope', 'LowerEnvelope', (['cFuncNowUnc', 'self.cFuncNowCnst'], {}), '(cFuncNowUnc, self.cFuncNowCnst)\n', (22717, 22749), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((22876, 22910), 'ConsumptionSavingModel.MargValueFunc', 'MargValueFunc', (['cFuncNow', 'self.CRRA'], {}), '(cFuncNow, self.CRRA)\n', (22889, 22910), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((22938, 23013), 'ConsumptionSavingModel.ConsumerSolution', 'ConsumerSolution', ([], {'cFunc': 'cFuncNow', 'vPfunc': 'vPfuncNow', 'mNrmMin': 'self.mNrmMinNow'}), '(cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=self.mNrmMinNow)\n', (22954, 23013), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((26574, 26622), 'numpy.zeros', 'np.zeros', (['(self.StateCount, self.aXtraGrid.size)'], {}), '((self.StateCount, self.aXtraGrid.size))\n', (26582, 26622), True, 'import numpy as np\n'), ((26821, 26864), 'numpy.dot', 'np.dot', (['self.MrkvArray[i, :]', 'EndOfPrdv_all'], {}), '(self.MrkvArray[i, :], EndOfPrdv_all)\n', (26827, 26864), True, 'import numpy as np\n'), ((27317, 27345), 'numpy.insert', 'np.insert', (['mGrid', '(0)', 'mNrmMin'], {}), '(mGrid, 0, mNrmMin)\n', (27326, 27345), True, 'import numpy as np\n'), ((27393, 27417), 'numpy.insert', 'np.insert', (['vNvrs', '(0)', '(0.0)'], {}), '(vNvrs, 0, 0.0)\n', (27402, 27417), True, 'import numpy as np\n'), ((27443, 27518), 'numpy.insert', 'np.insert', (['vNvrsP', '(0)', '(self.MPCmaxEff[i] ** (-self.CRRA / (1.0 - self.CRRA)))'], {}), '(vNvrsP, 0, self.MPCmaxEff[i] ** (-self.CRRA / (1.0 - self.CRRA)))\n', (27452, 27518), True, 'import numpy as np\n'), ((27613, 27692), 'HARKinterpolation.CubicInterp', 'CubicInterp', (['mNrm_temp', 'vNvrs', 'vNvrsP', '(MPCminNvrs * self.hNrmNow[i])', 'MPCminNvrs'], {}), '(mNrm_temp, vNvrs, vNvrsP, MPCminNvrs * self.hNrmNow[i], MPCminNvrs)\n', (27624, 27692), False, 'from HARKinterpolation import CubicInterp, LowerEnvelope, LinearInterp\n'), ((27801, 27834), 'ConsumptionSavingModel.ValueFunc', 'ValueFunc', (['vNvrsFunc_i', 'self.CRRA'], {}), '(vNvrsFunc_i, self.CRRA)\n', (27810, 27834), False, 'from ConsumptionSavingModel import ConsumptionSavingSolverENDG, ValueFunc, MargValueFunc, ConsumerSolution, IndShockConsumerType\n'), ((33173, 33215), 'numpy.zeros', 'np.zeros', (['(self.sim_periods, self.Nagents)'], {}), '((self.sim_periods, self.Nagents))\n', (33181, 33215), True, 'import numpy as np\n'), ((33246, 33288), 'numpy.zeros', 'np.zeros', (['(self.sim_periods, self.Nagents)'], {}), '((self.sim_periods, self.Nagents))\n', (33254, 33288), True, 'import numpy as np\n'), ((46838, 46856), 'numpy.eye', 'np.eye', (['StateCount'], {}), '(StateCount)\n', (46844, 46856), True, 'import numpy as np\n'), ((46894, 46927), 'numpy.ones', 'np.ones', (['(StateCount, StateCount)'], {}), '((StateCount, StateCount))\n', (46901, 46927), True, 'import numpy as np\n'), ((48288, 48328), 'numpy.array', 'np.array', (['[1.01, 1.02, 1.03, 1.04, 1.05]'], {}), '([1.01, 1.02, 1.03, 1.04, 1.05])\n', (48296, 48328), True, 'import numpy as np\n'), ((8129, 8155), 'numpy.asarray', 'np.asarray', (['self.aXtraGrid'], {}), '(self.aXtraGrid)\n', (8139, 8155), True, 'import numpy as np\n'), ((8172, 8203), 'numpy.array', 'np.array', (['self.BoroCnstNat_list'], {}), '(self.BoroCnstNat_list)\n', (8180, 8203), True, 'import numpy as np\n'), ((8305, 8335), 'numpy.zeros', 'np.zeros', (['(self.StateCount, 1)'], {}), '((self.StateCount, 1))\n', (8313, 8335), True, 'import numpy as np\n'), ((8376, 8427), 'numpy.reshape', 'np.reshape', (['self.mNrmMin_list', '(self.StateCount, 1)'], {}), '(self.mNrmMin_list, (self.StateCount, 1))\n', (8386, 8427), True, 'import numpy as np\n'), ((18011, 18050), 'numpy.dot', 'np.dot', (['self.MrkvArray', 'EndOfPrdvPP_all'], {}), '(self.MrkvArray, EndOfPrdvPP_all)\n', (18017, 18050), True, 'import numpy as np\n'), ((18772, 18825), 'numpy.reshape', 'np.reshape', (['self.WorstIncPrbAll', '(1, self.StateCount)'], {}), '(self.WorstIncPrbAll, (1, self.StateCount))\n', (18782, 18825), True, 'import numpy as np\n'), ((19107, 19210), 'numpy.dot', 'np.dot', (['temp_array', '(self.Rfree_list ** (1.0 - self.CRRA) * self.solution_next.MPCmax ** -self.CRRA\n )'], {}), '(temp_array, self.Rfree_list ** (1.0 - self.CRRA) * self.\n solution_next.MPCmax ** -self.CRRA)\n', (19113, 19210), True, 'import numpy as np\n'), ((19895, 20002), 'numpy.dot', 'np.dot', (['self.MrkvArray', '(self.solution_next.MPCmin ** -self.CRRA * self.Rfree_list ** (1.0 - self.CRRA)\n )'], {}), '(self.MrkvArray, self.solution_next.MPCmin ** -self.CRRA * self.\n Rfree_list ** (1.0 - self.CRRA))\n', (19901, 20002), True, 'import numpy as np\n'), ((33872, 33904), 'numpy.arange', 'np.arange', (['IncomeDstnNow[0].size'], {}), '(IncomeDstnNow[0].size)\n', (33881, 33904), True, 'import numpy as np\n'), ((35714, 35750), 'numpy.arange', 'np.arange', (['self.Nagents'], {'dtype': 'float'}), '(self.Nagents, dtype=float)\n', (35723, 35750), True, 'import numpy as np\n'), ((36137, 36159), 'numpy.zeros', 'np.zeros', (['self.Nagents'], {}), '(self.Nagents)\n', (36145, 36159), True, 'import numpy as np\n'), ((36271, 36319), 'numpy.searchsorted', 'np.searchsorted', (['Cutoffs[n, :]', 'draws_now[these]'], {}), '(Cutoffs[n, :], draws_now[these])\n', (36286, 36319), True, 'import numpy as np\n'), ((45179, 45208), 'numpy.array', 'np.array', (['(StateCount * [1.03])'], {}), '(StateCount * [1.03])\n', (45187, 45208), True, 'import numpy as np\n'), ((45294, 45323), 'numpy.array', 'np.array', (['(StateCount * [1.01])'], {}), '(StateCount * [1.01])\n', (45302, 45323), True, 'import numpy as np\n'), ((47157, 47186), 'numpy.array', 'np.array', (['(StateCount * [1.03])'], {}), '(StateCount * [1.03])\n', (47165, 47186), True, 'import numpy as np\n'), ((47286, 47326), 'numpy.array', 'np.array', (['[0.97, 0.99, 1.01, 1.03, 1.05]'], {}), '([0.97, 0.99, 1.01, 1.03, 1.05])\n', (47294, 47326), True, 'import numpy as np\n'), ((48159, 48188), 'numpy.array', 'np.array', (['(StateCount * [1.01])'], {}), '(StateCount * [1.01])\n', (48167, 48188), True, 'import numpy as np\n'), ((17157, 17218), 'numpy.logical_and', 'np.logical_and', (['self.possible_transitions[:, j]', 'which_states'], {}), '(self.possible_transitions[:, j], which_states)\n', (17171, 17218), True, 'import numpy as np\n'), ((21652, 21674), 'numpy.array', 'np.array', (['self.cNrmNow'], {}), '(self.cNrmNow)\n', (21660, 21674), True, 'import numpy as np\n'), ((21759, 21807), 'numpy.reshape', 'np.reshape', (['self.MPCmaxNow', '(self.StateCount, 1)'], {}), '(self.MPCmaxNow, (self.StateCount, 1))\n', (21769, 21807), True, 'import numpy as np\n'), ((33975, 34002), 'numpy.cumsum', 'np.cumsum', (['IncomeDstnNow[0]'], {}), '(IncomeDstnNow[0])\n', (33984, 34002), True, 'import numpy as np\n'), ((34003, 34016), 'numpy.sum', 'np.sum', (['these'], {}), '(these)\n', (34009, 34016), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#
import numpy
import pytest
import quadpy
from quadpy.nsimplex.helpers import integrate_monomial_over_unit_simplex
from helpers import check_degree
@pytest.mark.parametrize(
"scheme",
[quadpy.nsimplex.GrundmannMoeller(dim, k) for dim in range(3, 7) for k in range(5)]
#
+ [
quadpy.nsimplex.Stroud(dim, index)
for dim in range(3, 7)
for index in [
"Tn 1-1",
"Tn 1-2",
"Tn 2-1a",
"Tn 2-1b",
"Tn 2-2",
"Tn 3-1",
"Tn 3-2",
"Tn 3-3",
"Tn 3-4",
"Tn 3-5",
"Tn 3-6a",
"Tn 3-6b",
"Tn 3-7",
"Tn 3-8",
"Tn 3-9",
"Tn 4-1",
"Tn 5-1",
]
]
+ [
quadpy.nsimplex.Stroud(dim, index)
for dim in [3, 4, 6, 7]
for index in ["Tn 3-10", "Tn 3-11"]
]
+ [
quadpy.nsimplex.Stroud(dim, index)
for dim in range(4, 8)
for index in ["Tn 5-2"]
]
#
+ [quadpy.nsimplex.Walkington(3, k) for k in [1, 2, 3, 5, 7]]
+ [quadpy.nsimplex.Walkington(4, k) for dim in range(4, 7) for k in [1, 2, 3]],
)
def test_scheme(scheme):
assert scheme.points.dtype in [numpy.float64, numpy.int64], scheme.name
assert scheme.weights.dtype in [numpy.float64, numpy.int64], scheme.name
n = scheme.dim
simplex = numpy.zeros((n + 1, n))
for k in range(n):
simplex[k + 1, k] = 1.0
degree = check_degree(
lambda poly: quadpy.nsimplex.integrate(poly, simplex, scheme),
integrate_monomial_over_unit_simplex,
n,
scheme.degree + 1,
)
assert degree >= scheme.degree, "Observed: {}, expected: {}".format(
degree, scheme.degree
)
return
if __name__ == "__main__":
n_ = 3
scheme_ = quadpy.nsimplex.Stroud(n_, "Tn 5-1")
test_scheme(scheme_)
| [
"quadpy.nsimplex.GrundmannMoeller",
"quadpy.nsimplex.Stroud",
"numpy.zeros",
"quadpy.nsimplex.integrate",
"quadpy.nsimplex.Walkington"
] | [((1432, 1455), 'numpy.zeros', 'numpy.zeros', (['(n + 1, n)'], {}), '((n + 1, n))\n', (1443, 1455), False, 'import numpy\n'), ((1873, 1909), 'quadpy.nsimplex.Stroud', 'quadpy.nsimplex.Stroud', (['n_', '"""Tn 5-1"""'], {}), "(n_, 'Tn 5-1')\n", (1895, 1909), False, 'import quadpy\n'), ((1559, 1607), 'quadpy.nsimplex.integrate', 'quadpy.nsimplex.integrate', (['poly', 'simplex', 'scheme'], {}), '(poly, simplex, scheme)\n', (1584, 1607), False, 'import quadpy\n'), ((1141, 1173), 'quadpy.nsimplex.Walkington', 'quadpy.nsimplex.Walkington', (['(4)', 'k'], {}), '(4, k)\n', (1167, 1173), False, 'import quadpy\n'), ((1075, 1107), 'quadpy.nsimplex.Walkington', 'quadpy.nsimplex.Walkington', (['(3)', 'k'], {}), '(3, k)\n', (1101, 1107), False, 'import quadpy\n'), ((958, 992), 'quadpy.nsimplex.Stroud', 'quadpy.nsimplex.Stroud', (['dim', 'index'], {}), '(dim, index)\n', (980, 992), False, 'import quadpy\n'), ((825, 859), 'quadpy.nsimplex.Stroud', 'quadpy.nsimplex.Stroud', (['dim', 'index'], {}), '(dim, index)\n', (847, 859), False, 'import quadpy\n'), ((221, 261), 'quadpy.nsimplex.GrundmannMoeller', 'quadpy.nsimplex.GrundmannMoeller', (['dim', 'k'], {}), '(dim, k)\n', (253, 261), False, 'import quadpy\n'), ((326, 360), 'quadpy.nsimplex.Stroud', 'quadpy.nsimplex.Stroud', (['dim', 'index'], {}), '(dim, index)\n', (348, 360), False, 'import quadpy\n')] |
import numpy as np
from collections import Counter
# from sklearn.utils.linear_assignment_ import linear_assignment
# replaced with source code from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/linear_assignment_.py
"""
Mostly borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py
"""
def f1(p_num, p_den, r_num, r_den, beta=1):
p = 0 if p_den == 0 else p_num / float(p_den)
r = 0 if r_den == 0 else r_num / float(r_den)
return 0 if p + r == 0 else (1 + beta * beta) * p * r / (beta * beta * p + r)
class CorefEvaluator(object):
def __init__(self):
self.evaluators = [Evaluator(m) for m in (muc, b_cubed, ceafe)]
def update(self, predicted, gold, mention_to_predicted, mention_to_gold):
for e in self.evaluators:
e.update(predicted, gold, mention_to_predicted, mention_to_gold)
def get_f1(self):
return sum(e.get_f1() for e in self.evaluators) / len(self.evaluators)
def get_recall(self):
return sum(e.get_recall() for e in self.evaluators) / len(self.evaluators)
def get_precision(self):
return sum(e.get_precision() for e in self.evaluators) / len(self.evaluators)
def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1()
class Evaluator(object):
def __init__(self, metric, beta=1):
self.p_num = 0
self.p_den = 0
self.r_num = 0
self.r_den = 0
self.metric = metric
self.beta = beta
def update(self, predicted, gold, mention_to_predicted, mention_to_gold):
if self.metric == ceafe:
pn, pd, rn, rd = self.metric(predicted, gold)
else:
pn, pd = self.metric(predicted, mention_to_gold)
rn, rd = self.metric(gold, mention_to_predicted)
self.p_num += pn
self.p_den += pd
self.r_num += rn
self.r_den += rd
def get_f1(self):
return f1(self.p_num, self.p_den, self.r_num, self.r_den, beta=self.beta)
def get_recall(self):
return 0 if self.r_num == 0 else self.r_num / float(self.r_den)
def get_precision(self):
return 0 if self.p_num == 0 else self.p_num / float(self.p_den)
def get_prf(self):
return self.get_precision(), self.get_recall(), self.get_f1()
def get_counts(self):
return self.p_num, self.p_den, self.r_num, self.r_den
def evaluate_documents(documents, metric, beta=1):
evaluator = Evaluator(metric, beta=beta)
for document in documents:
evaluator.update(document)
return evaluator.get_precision(), evaluator.get_recall(), evaluator.get_f1()
def b_cubed(clusters, mention_to_gold):
num, dem = 0, 0
for c in clusters:
if len(c) == 1:
continue
gold_counts = Counter()
correct = 0
for m in c:
if m in mention_to_gold:
gold_counts[tuple(mention_to_gold[m])] += 1
for c2, count in gold_counts.iteritems():
if len(c2) != 1:
correct += count * count
num += correct / float(len(c))
dem += len(c)
return num, dem
def muc(clusters, mention_to_gold):
tp, p = 0, 0
for c in clusters:
p += len(c) - 1
tp += len(c)
linked = set()
for m in c:
if m in mention_to_gold:
linked.add(mention_to_gold[m])
else:
tp -= 1
tp -= len(linked)
return tp, p
def phi4(c1, c2):
return 2 * len([m for m in c1 if m in c2]) / float(len(c1) + len(c2))
def ceafe(clusters, gold_clusters):
clusters = [c for c in clusters if len(c) != 1]
scores = np.zeros((len(gold_clusters), len(clusters)))
for i in range(len(gold_clusters)):
for j in range(len(clusters)):
scores[i, j] = phi4(gold_clusters[i], clusters[j])
matching = linear_assignment(-scores)
similarity = sum(scores[matching[:, 0], matching[:, 1]])
return similarity, len(clusters), similarity, len(gold_clusters)
def lea(clusters, mention_to_gold):
num, dem = 0, 0
for c in clusters:
if len(c) == 1:
continue
common_links = 0
all_links = len(c) * (len(c) - 1) / 2.0
for i, m in enumerate(c):
if m in mention_to_gold:
for m2 in c[i + 1:]:
if m2 in mention_to_gold and mention_to_gold[m] == mention_to_gold[m2]:
common_links += 1
num += len(c) * common_links / float(all_links)
dem += len(c)
return num, dem
"""
Solve the unique lowest-cost assignment problem using the
Hungarian algorithm (also known as Munkres algorithm).
"""
# Based on original code by <NAME>, adapted to NumPy by <NAME>.
# Heavily refactored by <NAME>.
#
# TODO: a version of this algorithm has been incorporated in SciPy; use that
# when SciPy 0.17 is released.
# Copyright (c) 2008 <NAME> <<EMAIL>>, <NAME>
# Author: <NAME>, <NAME>
# LICENSE: BSD
def linear_assignment(X):
"""Solve the linear assignment problem using the Hungarian algorithm.
The problem is also known as maximum weight matching in bipartite graphs.
The method is also known as the Munkres or Kuhn-Munkres algorithm.
Parameters
----------
X : array
The cost matrix of the bipartite graph
Returns
-------
indices : array
The pairs of (row, col) indices in the original array giving
the original ordering.
References
----------
1. http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html
2. <NAME>. The Hungarian Method for the assignment problem.
*Naval Research Logistics Quarterly*, 2:83-97, 1955.
3. <NAME>. Variants of the Hungarian method for assignment
problems. *Naval Research Logistics Quarterly*, 3: 253-258, 1956.
4. Munkres, J. Algorithms for the Assignment and Transportation Problems.
*Journal of the Society of Industrial and Applied Mathematics*,
5(1):32-38, March, 1957.
5. https://en.wikipedia.org/wiki/Hungarian_algorithm
"""
indices = _hungarian(X).tolist()
indices.sort()
# Re-force dtype to ints in case of empty list
indices = np.array(indices, dtype=int)
# Make sure the array is 2D with 2 columns.
# This is needed when dealing with an empty list
indices.shape = (-1, 2)
return indices
class _HungarianState(object):
"""State of one execution of the Hungarian algorithm.
Parameters
----------
cost_matrix : 2D matrix
The cost matrix. Does not have to be square.
"""
def __init__(self, cost_matrix):
cost_matrix = np.atleast_2d(cost_matrix)
# If there are more rows (n) than columns (m), then the algorithm
# will not be able to work correctly. Therefore, we
# transpose the cost function when needed. Just have to
# remember to swap the result columns back later.
transposed = (cost_matrix.shape[1] < cost_matrix.shape[0])
if transposed:
self.C = (cost_matrix.T).copy()
else:
self.C = cost_matrix.copy()
self.transposed = transposed
# At this point, m >= n.
n, m = self.C.shape
self.row_uncovered = np.ones(n, dtype=np.bool)
self.col_uncovered = np.ones(m, dtype=np.bool)
self.Z0_r = 0
self.Z0_c = 0
self.path = np.zeros((n + m, 2), dtype=int)
self.marked = np.zeros((n, m), dtype=int)
def _find_prime_in_row(self, row):
"""
Find the first prime element in the specified row. Returns
the column index, or -1 if no starred element was found.
"""
col = np.argmax(self.marked[row] == 2)
if self.marked[row, col] != 2:
col = -1
return col
def _clear_covers(self):
"""Clear all covered matrix cells"""
self.row_uncovered[:] = True
self.col_uncovered[:] = True
def _hungarian(cost_matrix):
"""The Hungarian algorithm.
Calculate the Munkres solution to the classical assignment problem and
return the indices for the lowest-cost pairings.
Parameters
----------
cost_matrix : 2D matrix
The cost matrix. Does not have to be square.
Returns
-------
indices : 2D array of indices
The pairs of (row, col) indices in the original array giving
the original ordering.
"""
state = _HungarianState(cost_matrix)
# No need to bother with assignments if one of the dimensions
# of the cost matrix is zero-length.
step = None if 0 in cost_matrix.shape else _step1
while step is not None:
step = step(state)
# Look for the starred columns
results = np.array(np.where(state.marked == 1)).T
# We need to swap the columns because we originally
# did a transpose on the input cost matrix.
if state.transposed:
results = results[:, ::-1]
return results
# Individual steps of the algorithm follow, as a state machine: they return
# the next step to be taken (function to be called), if any.
def _step1(state):
"""Steps 1 and 2 in the Wikipedia page."""
# Step1: For each row of the matrix, find the smallest element and
# subtract it from every element in its row.
state.C -= state.C.min(axis=1)[:, np.newaxis]
# Step2: Find a zero (Z) in the resulting matrix. If there is no
# starred zero in its row or column, star Z. Repeat for each element
# in the matrix.
for i, j in zip(*np.where(state.C == 0)):
if state.col_uncovered[j] and state.row_uncovered[i]:
state.marked[i, j] = 1
state.col_uncovered[j] = False
state.row_uncovered[i] = False
state._clear_covers()
return _step3
def _step3(state):
"""
Cover each column containing a starred zero. If n columns are covered,
the starred zeros describe a complete set of unique assignments.
In this case, Go to DONE, otherwise, Go to Step 4.
"""
marked = (state.marked == 1)
state.col_uncovered[np.any(marked, axis=0)] = False
if marked.sum() < state.C.shape[0]:
return _step4
def _step4(state):
"""
Find a noncovered zero and prime it. If there is no starred zero
in the row containing this primed zero, Go to Step 5. Otherwise,
cover this row and uncover the column containing the starred
zero. Continue in this manner until there are no uncovered zeros
left. Save the smallest uncovered value and Go to Step 6.
"""
# We convert to int as numpy operations are faster on int
C = (state.C == 0).astype(np.int)
covered_C = C * state.row_uncovered[:, np.newaxis]
covered_C *= state.col_uncovered.astype(dtype=np.int, copy=False)
n = state.C.shape[0]
m = state.C.shape[1]
while True:
# Find an uncovered zero
row, col = np.unravel_index(np.argmax(covered_C), (n, m))
if covered_C[row, col] == 0:
return _step6
else:
state.marked[row, col] = 2
# Find the first starred element in the row
star_col = np.argmax(state.marked[row] == 1)
if not state.marked[row, star_col] == 1:
# Could not find one
state.Z0_r = row
state.Z0_c = col
return _step5
else:
col = star_col
state.row_uncovered[row] = False
state.col_uncovered[col] = True
covered_C[:, col] = C[:, col] * (
state.row_uncovered.astype(dtype=np.int, copy=False))
covered_C[row] = 0
def _step5(state):
"""
Construct a series of alternating primed and starred zeros as follows.
Let Z0 represent the uncovered primed zero found in Step 4.
Let Z1 denote the starred zero in the column of Z0 (if any).
Let Z2 denote the primed zero in the row of Z1 (there will always be one).
Continue until the series terminates at a primed zero that has no starred
zero in its column. Unstar each starred zero of the series, star each
primed zero of the series, erase all primes and uncover every line in the
matrix. Return to Step 3
"""
count = 0
path = state.path
path[count, 0] = state.Z0_r
path[count, 1] = state.Z0_c
while True:
# Find the first starred element in the col defined by
# the path.
row = np.argmax(state.marked[:, path[count, 1]] == 1)
if not state.marked[row, path[count, 1]] == 1:
# Could not find one
break
else:
count += 1
path[count, 0] = row
path[count, 1] = path[count - 1, 1]
# Find the first prime element in the row defined by the
# first path step
col = np.argmax(state.marked[path[count, 0]] == 2)
if state.marked[row, col] != 2:
col = -1
count += 1
path[count, 0] = path[count - 1, 0]
path[count, 1] = col
# Convert paths
for i in range(count + 1):
if state.marked[path[i, 0], path[i, 1]] == 1:
state.marked[path[i, 0], path[i, 1]] = 0
else:
state.marked[path[i, 0], path[i, 1]] = 1
state._clear_covers()
# Erase all prime markings
state.marked[state.marked == 2] = 0
return _step3
def _step6(state):
"""
Add the value found in Step 4 to every element of each covered row,
and subtract it from every element of each uncovered column.
Return to Step 4 without altering any stars, primes, or covered lines.
"""
# the smallest uncovered value in the matrix
if np.any(state.row_uncovered) and np.any(state.col_uncovered):
minval = np.min(state.C[state.row_uncovered], axis=0)
minval = np.min(minval[state.col_uncovered])
state.C[np.logical_not(state.row_uncovered)] += minval
state.C[:, state.col_uncovered] -= minval
return _step4
| [
"numpy.argmax",
"numpy.logical_not",
"numpy.zeros",
"numpy.ones",
"numpy.any",
"numpy.min",
"numpy.where",
"numpy.array",
"collections.Counter",
"numpy.atleast_2d"
] | [((6443, 6471), 'numpy.array', 'np.array', (['indices'], {'dtype': 'int'}), '(indices, dtype=int)\n', (6451, 6471), True, 'import numpy as np\n'), ((2900, 2909), 'collections.Counter', 'Counter', ([], {}), '()\n', (2907, 2909), False, 'from collections import Counter\n'), ((6908, 6934), 'numpy.atleast_2d', 'np.atleast_2d', (['cost_matrix'], {}), '(cost_matrix)\n', (6921, 6934), True, 'import numpy as np\n'), ((7523, 7548), 'numpy.ones', 'np.ones', (['n'], {'dtype': 'np.bool'}), '(n, dtype=np.bool)\n', (7530, 7548), True, 'import numpy as np\n'), ((7579, 7604), 'numpy.ones', 'np.ones', (['m'], {'dtype': 'np.bool'}), '(m, dtype=np.bool)\n', (7586, 7604), True, 'import numpy as np\n'), ((7672, 7703), 'numpy.zeros', 'np.zeros', (['(n + m, 2)'], {'dtype': 'int'}), '((n + m, 2), dtype=int)\n', (7680, 7703), True, 'import numpy as np\n'), ((7727, 7754), 'numpy.zeros', 'np.zeros', (['(n, m)'], {'dtype': 'int'}), '((n, m), dtype=int)\n', (7735, 7754), True, 'import numpy as np\n'), ((7972, 8004), 'numpy.argmax', 'np.argmax', (['(self.marked[row] == 2)'], {}), '(self.marked[row] == 2)\n', (7981, 8004), True, 'import numpy as np\n'), ((10422, 10444), 'numpy.any', 'np.any', (['marked'], {'axis': '(0)'}), '(marked, axis=0)\n', (10428, 10444), True, 'import numpy as np\n'), ((12853, 12900), 'numpy.argmax', 'np.argmax', (['(state.marked[:, path[count, 1]] == 1)'], {}), '(state.marked[:, path[count, 1]] == 1)\n', (12862, 12900), True, 'import numpy as np\n'), ((13242, 13286), 'numpy.argmax', 'np.argmax', (['(state.marked[path[count, 0]] == 2)'], {}), '(state.marked[path[count, 0]] == 2)\n', (13251, 13286), True, 'import numpy as np\n'), ((14114, 14141), 'numpy.any', 'np.any', (['state.row_uncovered'], {}), '(state.row_uncovered)\n', (14120, 14141), True, 'import numpy as np\n'), ((14146, 14173), 'numpy.any', 'np.any', (['state.col_uncovered'], {}), '(state.col_uncovered)\n', (14152, 14173), True, 'import numpy as np\n'), ((14193, 14237), 'numpy.min', 'np.min', (['state.C[state.row_uncovered]'], {'axis': '(0)'}), '(state.C[state.row_uncovered], axis=0)\n', (14199, 14237), True, 'import numpy as np\n'), ((14256, 14291), 'numpy.min', 'np.min', (['minval[state.col_uncovered]'], {}), '(minval[state.col_uncovered])\n', (14262, 14291), True, 'import numpy as np\n'), ((9060, 9087), 'numpy.where', 'np.where', (['(state.marked == 1)'], {}), '(state.marked == 1)\n', (9068, 9087), True, 'import numpy as np\n'), ((9859, 9881), 'numpy.where', 'np.where', (['(state.C == 0)'], {}), '(state.C == 0)\n', (9867, 9881), True, 'import numpy as np\n'), ((11270, 11290), 'numpy.argmax', 'np.argmax', (['covered_C'], {}), '(covered_C)\n', (11279, 11290), True, 'import numpy as np\n'), ((11501, 11534), 'numpy.argmax', 'np.argmax', (['(state.marked[row] == 1)'], {}), '(state.marked[row] == 1)\n', (11510, 11534), True, 'import numpy as np\n'), ((14309, 14344), 'numpy.logical_not', 'np.logical_not', (['state.row_uncovered'], {}), '(state.row_uncovered)\n', (14323, 14344), True, 'import numpy as np\n')] |
from datetime import datetime
import numpy as np
import os
import pytz
import six
import warnings
class ALL:
"Sentinel used as the default value for stream_name"
pass
if six.PY2:
# http://stackoverflow.com/a/5032238/380231
def ensure_path_exists(path, exist_ok=True):
import errno
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST or not exist_ok:
raise
else:
# technically, this won't work with py3.1, but no one uses that
def ensure_path_exists(path, exist_ok=True):
return os.makedirs(path, exist_ok=exist_ok)
def sanitize_np(val):
"Convert any numpy objects into built-in Python types."
if isinstance(val, (np.generic, np.ndarray)):
if np.isscalar(val):
return val.item()
return val.tolist()
return val
def apply_to_dict_recursively(d, f):
for key, val in d.items():
if hasattr(val, 'items'):
d[key] = apply_to_dict_recursively(val, f)
d[key] = f(val)
def format_time(search_dict, tz):
"""Helper function to format the time arguments in a search dict
Expects 'since' and 'until'
..warning: Does in-place mutation of the search_dict
"""
# The old names of 'since' and 'until' are 'start_time' and 'stop_time'.
if 'since' in search_dict and 'start_time' in search_dict:
raise TypeError("cannot use both 'since' and its deprecated name "
"'start_time'")
if 'until' in search_dict and 'stop_time' in search_dict:
raise TypeError("cannot use both 'until' and its deprecated name "
"'stop_time'")
if 'start_time' in search_dict or 'stop_time' in search_dict:
warnings.warn("The keyword 'start_time' and 'stop_time' have been "
"renamed to 'since' and 'until'. The old names are "
"deprecated.")
time_dict = {}
since = search_dict.pop('since', search_dict.pop('start_time', None))
until = search_dict.pop('until', search_dict.pop('stop_time', None))
if since:
time_dict['$gte'] = normalize_human_friendly_time(since, tz)
if until:
time_dict['$lte'] = normalize_human_friendly_time(until, tz)
if time_dict:
search_dict['time'] = time_dict
# human friendly timestamp formats we'll parse
_TS_FORMATS = [
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M', # these 2 are not as originally doc'd,
'%Y-%m-%d %H', # but match previous pandas behavior
'%Y-%m-%d',
'%Y-%m',
'%Y']
# build a tab indented, '-' bulleted list of supported formats
# to append to the parsing function docstring below
_doc_ts_formats = '\n'.join('\t- {}'.format(_) for _ in _TS_FORMATS)
def normalize_human_friendly_time(val, tz):
"""Given one of :
- string (in one of the formats below)
- datetime (eg. datetime.now()), with or without tzinfo)
- timestamp (eg. time.time())
return a timestamp (seconds since jan 1 1970 UTC).
Non string/datetime values are returned unaltered.
Leading/trailing whitespace is stripped.
Supported formats:
{}
"""
# {} is placeholder for formats; filled in after def...
zone = pytz.timezone(tz) # tz as datetime.tzinfo object
epoch = pytz.UTC.localize(datetime(1970, 1, 1))
check = True
if isinstance(val, six.string_types):
# unix 'date' cmd format '%a %b %d %H:%M:%S %Z %Y' works but
# doesn't get TZ?
# Could cleanup input a bit? remove leading/trailing [ :,-]?
# Yes, leading/trailing whitespace to match pandas behavior...
# Actually, pandas doesn't ignore trailing space, it assumes
# the *current* month/day if they're missing and there's
# trailing space, or the month is a single, non zero-padded digit.?!
val = val.strip()
for fmt in _TS_FORMATS:
try:
ts = datetime.strptime(val, fmt)
break
except ValueError:
pass
try:
if isinstance(ts, datetime):
val = ts
check = False
else:
# what else could the type be here?
raise TypeError('expected datetime,'
' got {:r}'.format(ts))
except NameError:
raise ValueError('failed to parse time: ' + repr(val))
if check and not isinstance(val, datetime):
return val
if val.tzinfo is None:
# is_dst=None raises NonExistent and Ambiguous TimeErrors
# when appropriate, same as pandas
val = zone.localize(val, is_dst=None)
return (val - epoch).total_seconds()
# fill in the placeholder we left in the previous docstring
normalize_human_friendly_time.__doc__ = (
normalize_human_friendly_time.__doc__.format(_doc_ts_formats)
)
| [
"os.makedirs",
"numpy.isscalar",
"datetime.datetime",
"datetime.datetime.strptime",
"pytz.timezone",
"warnings.warn"
] | [((3256, 3273), 'pytz.timezone', 'pytz.timezone', (['tz'], {}), '(tz)\n', (3269, 3273), False, 'import pytz\n'), ((613, 649), 'os.makedirs', 'os.makedirs', (['path'], {'exist_ok': 'exist_ok'}), '(path, exist_ok=exist_ok)\n', (624, 649), False, 'import os\n'), ((795, 811), 'numpy.isscalar', 'np.isscalar', (['val'], {}), '(val)\n', (806, 811), True, 'import numpy as np\n'), ((1778, 1917), 'warnings.warn', 'warnings.warn', (['"""The keyword \'start_time\' and \'stop_time\' have been renamed to \'since\' and \'until\'. The old names are deprecated."""'], {}), '(\n "The keyword \'start_time\' and \'stop_time\' have been renamed to \'since\' and \'until\'. The old names are deprecated."\n )\n', (1791, 1917), False, 'import warnings\n'), ((3336, 3356), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (3344, 3356), False, 'from datetime import datetime\n'), ((334, 351), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (345, 351), False, 'import os\n'), ((3962, 3989), 'datetime.datetime.strptime', 'datetime.strptime', (['val', 'fmt'], {}), '(val, fmt)\n', (3979, 3989), False, 'from datetime import datetime\n')] |
# Machine Learning model 3 (Test w/ some different MAC address + K.Arunan's Echo)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import itertools
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
from sklearn.feature_extraction.text import CountVectorizer
from catboost import CatBoostClassifier,Pool
import os
import time
from sklearn.metrics import make_scorer, accuracy_score
from sklearn.model_selection import train_test_split,GridSearchCV
TRAIN_DATASET = os.path.join(os.path.dirname(os.path.abspath(__file__)), "model3_dataset", "model3_train_paper.csv")
TEST_DATASET = os.path.join(os.path.dirname(os.path.abspath(__file__)), "experiment_dns", "experiment_dns.csv")
MODEL_NAME = os.path.join(os.path.dirname(os.path.abspath(__file__)), "experiment_dns", "experiment_dns.cbm")
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.4f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# Train dataset
headernames = ['ipAddr', 'mac', 'portSrc', 'portDst', 'pktLength', 'deviceName', 'protocol', 'detail' ]
dataset = pd.read_csv(TRAIN_DATASET, names = headernames)
dataset.head()
X_train = dataset.drop(['deviceName'],axis=1)
X_train = X_train.drop(['detail'],axis=1)
y_train = dataset['deviceName']
#########################################################################
# Test dataset
testDataset = pd.read_csv(TEST_DATASET, names = headernames)
testDataset.head()
X_test = testDataset.drop(['deviceName'],axis=1)
X_test = X_test.drop(['detail'],axis=1)
y_test = testDataset['deviceName']
categorical_features_indices = np.where(X_train.dtypes != np.float)[0]
# IMPORTANT! : cannot use two CatBoost pool.
pool = Pool(X_train, y_train,cat_features=categorical_features_indices)
params = {
'iterations': 100,
'learning_rate': 0.59,
'eval_metric': 'Accuracy',
'l2_leaf_reg':3,
'use_best_model': False
}
classifier = CatBoostClassifier(**params)
start = time.time()
classifier.fit(pool)
stop = time.time()
start2 = time.time()
y_pred = classifier.predict(X_test)
stop2 = time.time()
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(cm)
report = classification_report(y_test, y_pred)
print("Classification Report:",)
print (report)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
traningTime = str(stop - start)
print("Training time: " + traningTime)
testingTime = str(stop2 - start2)
print("Testing time: " + testingTime)
feature_importances = classifier.get_feature_importance(pool)
feature_names = X_train.columns
for score, name in sorted(zip(feature_importances, feature_names), reverse=True):
print('{}: {}'.format(name, score))
className = ["Device 0","Device 1","Device 2","Device 3","Device 4","Device 5","Device 6","Device 7"]
plt.figure()
plot_confusion_matrix(cm, classes=className,normalize=True,
title="DNS packets dataset's confusion matrix")
plt.show()
classifier.save_model(MODEL_NAME,format="cbm",export_parameters=None,pool=None)
| [
"matplotlib.pyplot.title",
"pandas.read_csv",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"catboost.CatBoostClassifier",
"matplotlib.pyplot.tight_layout",
"os.path.abspath",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplo... | [((1935, 1980), 'pandas.read_csv', 'pd.read_csv', (['TRAIN_DATASET'], {'names': 'headernames'}), '(TRAIN_DATASET, names=headernames)\n', (1946, 1980), True, 'import pandas as pd\n'), ((2221, 2265), 'pandas.read_csv', 'pd.read_csv', (['TEST_DATASET'], {'names': 'headernames'}), '(TEST_DATASET, names=headernames)\n', (2232, 2265), True, 'import pandas as pd\n'), ((2535, 2600), 'catboost.Pool', 'Pool', (['X_train', 'y_train'], {'cat_features': 'categorical_features_indices'}), '(X_train, y_train, cat_features=categorical_features_indices)\n', (2539, 2600), False, 'from catboost import CatBoostClassifier, Pool\n'), ((2762, 2790), 'catboost.CatBoostClassifier', 'CatBoostClassifier', ([], {}), '(**params)\n', (2780, 2790), False, 'from catboost import CatBoostClassifier, Pool\n'), ((2799, 2810), 'time.time', 'time.time', ([], {}), '()\n', (2808, 2810), False, 'import time\n'), ((2839, 2850), 'time.time', 'time.time', ([], {}), '()\n', (2848, 2850), False, 'import time\n'), ((2861, 2872), 'time.time', 'time.time', ([], {}), '()\n', (2870, 2872), False, 'import time\n'), ((2917, 2928), 'time.time', 'time.time', ([], {}), '()\n', (2926, 2928), False, 'import time\n'), ((3019, 3051), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (3035, 3051), False, 'from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n'), ((3098, 3135), 'sklearn.metrics.classification_report', 'classification_report', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (3119, 3135), False, 'from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n'), ((3195, 3225), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (3209, 3225), False, 'from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n'), ((3716, 3728), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3726, 3728), True, 'import matplotlib.pyplot as plt\n'), ((3859, 3869), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3867, 3869), True, 'import matplotlib.pyplot as plt\n'), ((1223, 1273), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cm'], {'interpolation': '"""nearest"""', 'cmap': 'cmap'}), "(cm, interpolation='nearest', cmap=cmap)\n", (1233, 1273), True, 'import matplotlib.pyplot as plt\n'), ((1278, 1294), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1287, 1294), True, 'import matplotlib.pyplot as plt\n'), ((1299, 1313), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1311, 1313), True, 'import matplotlib.pyplot as plt\n'), ((1359, 1403), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tick_marks', 'classes'], {'rotation': '(45)'}), '(tick_marks, classes, rotation=45)\n', (1369, 1403), True, 'import matplotlib.pyplot as plt\n'), ((1408, 1439), 'matplotlib.pyplot.yticks', 'plt.yticks', (['tick_marks', 'classes'], {}), '(tick_marks, classes)\n', (1418, 1439), True, 'import matplotlib.pyplot as plt\n'), ((1722, 1740), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1738, 1740), True, 'import matplotlib.pyplot as plt\n'), ((1745, 1769), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True label"""'], {}), "('True label')\n", (1755, 1769), True, 'import matplotlib.pyplot as plt\n'), ((1774, 1803), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted label"""'], {}), "('Predicted label')\n", (1784, 1803), True, 'import matplotlib.pyplot as plt\n'), ((2443, 2479), 'numpy.where', 'np.where', (['(X_train.dtypes != np.float)'], {}), '(X_train.dtypes != np.float)\n', (2451, 2479), True, 'import numpy as np\n'), ((527, 552), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (542, 552), False, 'import os\n'), ((643, 668), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (658, 668), False, 'import os\n'), ((753, 778), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (768, 778), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Helpers
@author: thomas
"""
import numpy as np
import random
import os
from shutil import copyfile
from gym import spaces
def stable_normalizer(x,temp):
''' Computes x[i]**temp/sum_i(x[i]**temp) '''
x = (x / np.max(x))**temp
return np.abs(x/np.sum(x))
def argmax(x):
''' assumes a 1D vector x '''
x = x.flatten()
if np.any(np.isnan(x)):
print('Warning: Cannot argmax when vector contains nans, results will be wrong')
try:
winners = np.argwhere(x == np.max(x)).flatten()
winner = random.choice(winners)
except:
winner = np.argmax(x) # numerical instability ?
return winner
def check_space(space):
''' Check the properties of an environment state or action space '''
if isinstance(space,spaces.Box):
dim = space.shape
discrete = False
elif isinstance(space,spaces.Discrete):
dim = space.n
discrete = True
else:
raise NotImplementedError('This type of space is not supported')
return dim, discrete
def store_safely(folder,name,to_store):
''' to prevent losing information due to interruption of process'''
new_name = folder+name+'.npy'
old_name = folder+name+'_old.npy'
if os.path.exists(new_name):
copyfile(new_name,old_name)
np.save(new_name,to_store)
if os.path.exists(old_name):
os.remove(old_name)
### Atari helpers ###
def get_base_env(env):
''' removes all wrappers '''
while hasattr(env,'env'):
env = env.env
return env
def copy_atari_state(env):
env = get_base_env(env)
return env.clone_full_state()
# return env.ale.cloneSystemState()
def restore_atari_state(env,snapshot):
env = get_base_env(env)
env.restore_full_state(snapshot)
# env.ale.restoreSystemState(snapshot)
def is_atari_game(env):
''' Verify whether game uses the Arcade Learning Environment '''
env = get_base_env(env)
return hasattr(env,'ale')
### Database ##
class Database():
''' Database '''
def __init__(self,max_size,batch_size):
self.max_size = max_size
self.batch_size = batch_size
self.clear()
self.sample_array = None
self.sample_index = 0
def clear(self):
self.experience = []
self.insert_index = 0
self.size = 0
def store(self,experience):
if self.size < self.max_size:
self.experience.append(experience)
self.size +=1
else:
self.experience[self.insert_index] = experience
self.insert_index += 1
if self.insert_index >= self.size:
self.insert_index = 0
def store_from_array(self,*args):
for i in range(args[0].shape[0]):
entry = []
for arg in args:
entry.append(arg[i])
self.store(entry)
def reshuffle(self):
self.sample_array = np.arange(self.size)
random.shuffle(self.sample_array)
self.sample_index = 0
def __iter__(self):
return self
def __next__(self):
if (self.sample_index + self.batch_size > self.size) and (not self.sample_index == 0):
self.reshuffle() # Reset for the next epoch
raise(StopIteration)
if (self.sample_index + 2*self.batch_size > self.size):
indices = self.sample_array[self.sample_index:]
batch = [self.experience[i] for i in indices]
else:
indices = self.sample_array[self.sample_index:self.sample_index+self.batch_size]
batch = [self.experience[i] for i in indices]
self.sample_index += self.batch_size
arrays = []
for i in range(len(batch[0])):
to_add = np.array([entry[i] for entry in batch])
arrays.append(to_add)
return tuple(arrays)
next = __next__
### Visualization ##
def symmetric_remove(x,n):
''' removes n items from beginning and end '''
odd = is_odd(n)
half = int(n/2)
if half > 0:
x = x[half:-half]
if odd:
x = x[1:]
return x
def is_odd(number):
''' checks whether number is odd, returns boolean '''
return bool(number & 1)
def smooth(y,window,mode):
''' smooth 1D vectory y '''
return np.convolve(y, np.ones(window)/window, mode=mode) | [
"os.remove",
"numpy.save",
"numpy.sum",
"numpy.argmax",
"random.shuffle",
"os.path.exists",
"random.choice",
"numpy.isnan",
"numpy.ones",
"numpy.max",
"numpy.arange",
"numpy.array",
"shutil.copyfile"
] | [((1283, 1307), 'os.path.exists', 'os.path.exists', (['new_name'], {}), '(new_name)\n', (1297, 1307), False, 'import os\n'), ((1349, 1376), 'numpy.save', 'np.save', (['new_name', 'to_store'], {}), '(new_name, to_store)\n', (1356, 1376), True, 'import numpy as np\n'), ((1383, 1407), 'os.path.exists', 'os.path.exists', (['old_name'], {}), '(old_name)\n', (1397, 1407), False, 'import os\n'), ((400, 411), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (408, 411), True, 'import numpy as np\n'), ((588, 610), 'random.choice', 'random.choice', (['winners'], {}), '(winners)\n', (601, 610), False, 'import random\n'), ((1317, 1345), 'shutil.copyfile', 'copyfile', (['new_name', 'old_name'], {}), '(new_name, old_name)\n', (1325, 1345), False, 'from shutil import copyfile\n'), ((1429, 1448), 'os.remove', 'os.remove', (['old_name'], {}), '(old_name)\n', (1438, 1448), False, 'import os\n'), ((3011, 3031), 'numpy.arange', 'np.arange', (['self.size'], {}), '(self.size)\n', (3020, 3031), True, 'import numpy as np\n'), ((3040, 3073), 'random.shuffle', 'random.shuffle', (['self.sample_array'], {}), '(self.sample_array)\n', (3054, 3073), False, 'import random\n'), ((268, 277), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (274, 277), True, 'import numpy as np\n'), ((305, 314), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (311, 314), True, 'import numpy as np\n'), ((640, 652), 'numpy.argmax', 'np.argmax', (['x'], {}), '(x)\n', (649, 652), True, 'import numpy as np\n'), ((3878, 3917), 'numpy.array', 'np.array', (['[entry[i] for entry in batch]'], {}), '([entry[i] for entry in batch])\n', (3886, 3917), True, 'import numpy as np\n'), ((4443, 4458), 'numpy.ones', 'np.ones', (['window'], {}), '(window)\n', (4450, 4458), True, 'import numpy as np\n'), ((547, 556), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (553, 556), True, 'import numpy as np\n')] |
import pickle
import numpy as np
import argparse
import os
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
from IPython.display import HTML
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
# Load and standardize data
# Original GAN
with open('G_loss_orig', 'rb') as f:
G_losses_orig = pickle.load(f)
f.close()
with open('D_loss_orig', 'rb') as f:
D_losses_orig = pickle.load(f)
f.close()
with open('test_imgs_orig', 'rb') as f:
img_list_orig = pickle.load(f)
f.close()
G_orig_mean = np.mean(G_losses_orig, axis=0)
G_orig_std = np.std(G_losses_orig - G_orig_mean, axis=0)
D_orig_mean = np.mean(D_losses_orig, axis=0)
D_orig_std = np.std(D_losses_orig - D_orig_mean, axis=0)
####################################################
# MAB GAN
stat_reward = False
conf_bound = False
with open('G_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
G_losses_MAB_stat_false_conf_false = pickle.load(f)
f.close()
with open('D_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
D_losses_MAB_stat_false_conf_false = pickle.load(f)
f.close()
with open('test_imgs_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
img_list_MAB_stat_false_conf_false = pickle.load(f)
f.close()
with open('k_list_MAB' + '_stat_' + str(stat_reward) + '_ucb_' + str(conf_bound), 'rb') as f:
k_list_MAB_stat_false_conf_false = pickle.load(f)
f.close()
G_losses_MAB_stat_false_conf_false_mean = np.mean(G_losses_MAB_stat_false_conf_false, axis=0)
G_losses_MAB_stat_false_conf_false_std = np.std(G_losses_MAB_stat_false_conf_false - G_losses_MAB_stat_false_conf_false_mean, axis=0)
D_losses_MAB_stat_false_conf_false_mean = np.mean(D_losses_MAB_stat_false_conf_false, axis=0)
D_losses_MAB_stat_false_conf_false_std = np.std(D_losses_MAB_stat_false_conf_false - D_losses_MAB_stat_false_conf_false_mean, axis=0)
####################################################
stat_reward = True
conf_bound = False
with open('G_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
G_losses_MAB_stat_true_conf_false = pickle.load(f)
with open('D_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
D_losses_MAB_stat_true_conf_false = pickle.load(f)
with open('test_imgs_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
img_list_MAB_stat_true_conf_false = pickle.load(f)
# with open('k_list_MAB' + '_stat_' + str(stat_reward) + '_ucb_' + str(conf_bound), 'rb') as f:
# k_list_MAB_stat_true_conf_false = pickle.load(f)
G_losses_MAB_stat_true_conf_false_mean = np.mean(G_losses_MAB_stat_true_conf_false, axis=0)
G_losses_MAB_stat_true_conf_false_std = np.std(G_losses_MAB_stat_true_conf_false - G_losses_MAB_stat_true_conf_false_mean, axis=0)
D_losses_MAB_stat_true_conf_false_mean = np.mean(D_losses_MAB_stat_true_conf_false, axis=0)
D_losses_MAB_stat_true_conf_false_std = np.std(D_losses_MAB_stat_true_conf_false - D_losses_MAB_stat_true_conf_false_mean, axis=0)
####################################################
stat_reward = False
conf_bound = True
with open('G_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
G_losses_MAB_stat_false_conf_true = pickle.load(f)
f.close()
with open('D_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
D_losses_MAB_stat_false_conf_true = pickle.load(f)
f.close()
with open('test_imgs_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
img_list_MAB_stat_false_conf_true = pickle.load(f)
f.close()
with open('k_list_MAB' + '_stat_' + str(stat_reward) + '_ucb_' + str(conf_bound), 'rb') as f:
k_list_MAB_stat_false_conf_true = pickle.load(f)
f.close()
G_losses_MAB_stat_false_conf_true_mean = np.mean(G_losses_MAB_stat_false_conf_true, axis=0)
G_losses_MAB_stat_false_conf_true_std = np.std(G_losses_MAB_stat_false_conf_true - G_losses_MAB_stat_false_conf_true_mean, axis=0)
D_losses_MAB_stat_false_conf_true_mean = np.mean(D_losses_MAB_stat_false_conf_true, axis=0)
D_losses_MAB_stat_false_conf_true_std = np.std(D_losses_MAB_stat_false_conf_true - D_losses_MAB_stat_false_conf_true_mean, axis=0)
####################################################
stat_reward = True
conf_bound = True
with open('G_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
G_losses_MAB_stat_true_conf_true = pickle.load(f)
f.close()
with open('D_loss_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
D_losses_MAB_stat_true_conf_true = pickle.load(f)
f.close()
with open('test_imgs_MAB'+'_stat_'+str(stat_reward)+'_ucb_'+str(conf_bound), 'rb') as f:
img_list_MAB_stat_true_conf_true = pickle.load(f)
f.close()
with open('k_list_MAB' + '_stat_' + str(stat_reward) + '_ucb_' + str(conf_bound), 'rb') as f:
k_list_MAB_stat_true_conf_true = pickle.load(f)
f.close()
G_losses_MAB_stat_true_conf_true_mean = np.mean(G_losses_MAB_stat_true_conf_true, axis=0)
G_losses_MAB_stat_true_conf_true_std = np.std(G_losses_MAB_stat_true_conf_true - G_losses_MAB_stat_true_conf_true_mean, axis=0)
D_losses_MAB_stat_true_conf_true_mean = np.mean(D_losses_MAB_stat_true_conf_true, axis=0)
D_losses_MAB_stat_true_conf_true_std = np.std(D_losses_MAB_stat_true_conf_true - D_losses_MAB_stat_true_conf_true_mean, axis=0)
####################################################
mpl.rcParams['lines.linewidth'] = .4
# Generator Plots
plt.figure(figsize=(10,5))
plt.title("Generator Loss During Training")
plt.plot(range(len(G_orig_mean)), G_orig_mean, label="Standard GAN")
#plt.fill_between(range(len(G_orig_mean)), y1=G_orig_mean-G_orig_std, y2=G_orig_mean+G_orig_std)
plt.plot(range(len(G_losses_MAB_stat_true_conf_true_mean)), G_losses_MAB_stat_true_conf_true_mean, label="MAB GAN stat. and UCB")
#plt.fill_between(range(len(G_losses_MAB_stat_true_conf_true_mean)),
# y1=G_losses_MAB_stat_true_conf_true_mean-G_losses_MAB_stat_true_conf_true_std,
# y2=G_losses_MAB_stat_true_conf_true_mean+G_losses_MAB_stat_true_conf_true_std)
plt.plot(range(len(G_losses_MAB_stat_false_conf_true_mean)), G_losses_MAB_stat_false_conf_true_mean, label="MAB GAN non-stat. and UCB")
#plt.fill_between(range(len(G_losses_MAB_stat_false_conf_true_mean)),
# y1=G_losses_MAB_stat_false_conf_true_mean-G_losses_MAB_stat_false_conf_true_std,
# y2=G_losses_MAB_stat_false_conf_true_mean+G_losses_MAB_stat_false_conf_true_std)
plt.plot(range(len(G_losses_MAB_stat_true_conf_false_mean)), G_losses_MAB_stat_true_conf_false_mean, label="MAB GAN stat. and no UCB")
#plt.fill_between(range(len(G_losses_MAB_stat_true_conf_false_mean)),
# y1=G_losses_MAB_stat_true_conf_false_mean-G_losses_MAB_stat_true_conf_false_std,
# y2=G_losses_MAB_stat_true_conf_false_mean+G_losses_MAB_stat_true_conf_false_std)
plt.plot(range(len(G_losses_MAB_stat_false_conf_false_mean)), G_losses_MAB_stat_false_conf_false_mean, label="MAB GAN non-stat. and no UCB")
#plt.fill_between(range(len(G_losses_MAB_stat_false_conf_false_mean)),
# y1=G_losses_MAB_stat_false_conf_false_mean-G_losses_MAB_stat_false_conf_false_std,
# y2=G_losses_MAB_stat_false_conf_false_mean+G_losses_MAB_stat_false_conf_false_std)
plt.xlabel("iterations")
plt.ylabel("Generator Loss")
plt.legend()
plt.show()
####################################################
# Discriminator Plots
plt.figure(figsize=(10,5))
plt.title("Discriminator Loss During Training")
plt.plot(range(len(D_orig_mean)), D_orig_mean, label="Standard GAN")
#plt.fill_between(range(len(D_orig_mean)), y1=D_orig_mean-D_orig_std, y2=D_orig_mean+D_orig_std)
plt.plot(range(len(D_losses_MAB_stat_true_conf_true_mean)), D_losses_MAB_stat_true_conf_true_mean, label="MAB GAN stat. and UCB")
#plt.fill_between(range(len(D_losses_MAB_stat_true_conf_true_mean)),
# y1=D_losses_MAB_stat_true_conf_true_mean-D_losses_MAB_stat_true_conf_true_std,
# y2=D_losses_MAB_stat_true_conf_true_mean+D_losses_MAB_stat_true_conf_true_std)
plt.plot(range(len(D_losses_MAB_stat_false_conf_true_mean)), D_losses_MAB_stat_false_conf_true_mean, label="MAB GAN non-stat. and UCB")
#plt.fill_between(range(len(D_losses_MAB_stat_false_conf_true_mean)),
# y1=D_losses_MAB_stat_false_conf_true_mean-D_losses_MAB_stat_false_conf_true_std,
# y2=D_losses_MAB_stat_false_conf_true_mean+D_losses_MAB_stat_false_conf_true_std)
plt.plot(range(len(D_losses_MAB_stat_true_conf_false_mean)), D_losses_MAB_stat_true_conf_false_mean, label="MAB GAN stat. and no UCB")
#plt.fill_between(range(len(D_losses_MAB_stat_true_conf_false_mean)),
# y1=D_losses_MAB_stat_true_conf_false_mean-D_losses_MAB_stat_true_conf_false_std,
# y2=D_losses_MAB_stat_true_conf_false_mean+D_losses_MAB_stat_true_conf_false_std)
plt.plot(range(len(D_losses_MAB_stat_false_conf_false_mean)), D_losses_MAB_stat_false_conf_false_mean, label="MAB GAN non-stat. and no UCB")
#plt.fill_between(range(len(D_losses_MAB_stat_false_conf_false_mean)),
# y1=D_losses_MAB_stat_false_conf_false_mean-D_losses_MAB_stat_false_conf_false_std,
# y2=D_losses_MAB_stat_false_conf_false_mean+D_losses_MAB_stat_false_conf_false_std)
plt.xlabel("iterations")
plt.ylabel("Discriminator Loss")
plt.legend()
plt.show()
####################################################
# Plot the fake images from the last epoch
plt.subplot(1,2,1)
plt.axis("off")
plt.title("Fake Images for Standard GAN")
plt.imshow(np.transpose(img_list_orig[-1],(1,2,0)))
#plt.show()
# Plot the fake images from the last epoch
plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images for MAB GAN")
plt.imshow(np.transpose(img_list_MAB_stat_true_conf_true[-1],(1,2,0)))
plt.show()
print()
#######################################################
mpl.rcParams['lines.linewidth'] = 1
# Plot k
plt.figure(figsize=(10,5))
plt.title("Number of Discriminator Updates per Iteration")
plt.plot(np.ones((len(k_list_MAB_stat_true_conf_true[0]),)), label="Standard GAN")
plt.plot(k_list_MAB_stat_true_conf_true[0], label="MAB GAN")
plt.xlabel("iterations")
plt.legend()
plt.show()
#######################################################
# Plot some training images
# real_batch = next(iter(dataloader))
# plt.figure(figsize=(8,8))
# plt.axis("off")
# plt.title("Training Images")
# plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=2, normalize=True).cpu(),(1,2,0)))
# **Visualization of G’s progression**
#
# Remember how we saved the generator’s output on the fixed_noise batch
# after every epoch of training. Now, we can visualize the training
# progression of G with an animation. Press the play button to start the
# animation.
#
#%%capture
#fig = plt.figure(figsize=(8,8))
#plt.axis("off")
#ims = [[plt.imshow(np.transpose(i,(1,2,0)), animated=True)] for i in img_list]
#ani = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)
#HTML(ani.to_jshtml())
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.std",
"matplotlib.pyplot.legend",
"numpy.transpose",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"numpy.mean",
"pickle.load",
"matplotlib.pyplot.ylabel",
"matplotlib.p... | [((776, 806), 'numpy.mean', 'np.mean', (['G_losses_orig'], {'axis': '(0)'}), '(G_losses_orig, axis=0)\n', (783, 806), True, 'import numpy as np\n'), ((820, 863), 'numpy.std', 'np.std', (['(G_losses_orig - G_orig_mean)'], {'axis': '(0)'}), '(G_losses_orig - G_orig_mean, axis=0)\n', (826, 863), True, 'import numpy as np\n'), ((878, 908), 'numpy.mean', 'np.mean', (['D_losses_orig'], {'axis': '(0)'}), '(D_losses_orig, axis=0)\n', (885, 908), True, 'import numpy as np\n'), ((922, 965), 'numpy.std', 'np.std', (['(D_losses_orig - D_orig_mean)'], {'axis': '(0)'}), '(D_losses_orig - D_orig_mean, axis=0)\n', (928, 965), True, 'import numpy as np\n'), ((1728, 1779), 'numpy.mean', 'np.mean', (['G_losses_MAB_stat_false_conf_false'], {'axis': '(0)'}), '(G_losses_MAB_stat_false_conf_false, axis=0)\n', (1735, 1779), True, 'import numpy as np\n'), ((1821, 1917), 'numpy.std', 'np.std', (['(G_losses_MAB_stat_false_conf_false - G_losses_MAB_stat_false_conf_false_mean)'], {'axis': '(0)'}), '(G_losses_MAB_stat_false_conf_false -\n G_losses_MAB_stat_false_conf_false_mean, axis=0)\n', (1827, 1917), True, 'import numpy as np\n'), ((1956, 2007), 'numpy.mean', 'np.mean', (['D_losses_MAB_stat_false_conf_false'], {'axis': '(0)'}), '(D_losses_MAB_stat_false_conf_false, axis=0)\n', (1963, 2007), True, 'import numpy as np\n'), ((2049, 2145), 'numpy.std', 'np.std', (['(D_losses_MAB_stat_false_conf_false - D_losses_MAB_stat_false_conf_false_mean)'], {'axis': '(0)'}), '(D_losses_MAB_stat_false_conf_false -\n D_losses_MAB_stat_false_conf_false_mean, axis=0)\n', (2055, 2145), True, 'import numpy as np\n'), ((2852, 2902), 'numpy.mean', 'np.mean', (['G_losses_MAB_stat_true_conf_false'], {'axis': '(0)'}), '(G_losses_MAB_stat_true_conf_false, axis=0)\n', (2859, 2902), True, 'import numpy as np\n'), ((2943, 3037), 'numpy.std', 'np.std', (['(G_losses_MAB_stat_true_conf_false - G_losses_MAB_stat_true_conf_false_mean)'], {'axis': '(0)'}), '(G_losses_MAB_stat_true_conf_false -\n G_losses_MAB_stat_true_conf_false_mean, axis=0)\n', (2949, 3037), True, 'import numpy as np\n'), ((3075, 3125), 'numpy.mean', 'np.mean', (['D_losses_MAB_stat_true_conf_false'], {'axis': '(0)'}), '(D_losses_MAB_stat_true_conf_false, axis=0)\n', (3082, 3125), True, 'import numpy as np\n'), ((3166, 3260), 'numpy.std', 'np.std', (['(D_losses_MAB_stat_true_conf_false - D_losses_MAB_stat_true_conf_false_mean)'], {'axis': '(0)'}), '(D_losses_MAB_stat_true_conf_false -\n D_losses_MAB_stat_true_conf_false_mean, axis=0)\n', (3172, 3260), True, 'import numpy as np\n'), ((4003, 4053), 'numpy.mean', 'np.mean', (['G_losses_MAB_stat_false_conf_true'], {'axis': '(0)'}), '(G_losses_MAB_stat_false_conf_true, axis=0)\n', (4010, 4053), True, 'import numpy as np\n'), ((4094, 4188), 'numpy.std', 'np.std', (['(G_losses_MAB_stat_false_conf_true - G_losses_MAB_stat_false_conf_true_mean)'], {'axis': '(0)'}), '(G_losses_MAB_stat_false_conf_true -\n G_losses_MAB_stat_false_conf_true_mean, axis=0)\n', (4100, 4188), True, 'import numpy as np\n'), ((4226, 4276), 'numpy.mean', 'np.mean', (['D_losses_MAB_stat_false_conf_true'], {'axis': '(0)'}), '(D_losses_MAB_stat_false_conf_true, axis=0)\n', (4233, 4276), True, 'import numpy as np\n'), ((4317, 4411), 'numpy.std', 'np.std', (['(D_losses_MAB_stat_false_conf_true - D_losses_MAB_stat_false_conf_true_mean)'], {'axis': '(0)'}), '(D_losses_MAB_stat_false_conf_true -\n D_losses_MAB_stat_false_conf_true_mean, axis=0)\n', (4323, 4411), True, 'import numpy as np\n'), ((5148, 5197), 'numpy.mean', 'np.mean', (['G_losses_MAB_stat_true_conf_true'], {'axis': '(0)'}), '(G_losses_MAB_stat_true_conf_true, axis=0)\n', (5155, 5197), True, 'import numpy as np\n'), ((5237, 5329), 'numpy.std', 'np.std', (['(G_losses_MAB_stat_true_conf_true - G_losses_MAB_stat_true_conf_true_mean)'], {'axis': '(0)'}), '(G_losses_MAB_stat_true_conf_true -\n G_losses_MAB_stat_true_conf_true_mean, axis=0)\n', (5243, 5329), True, 'import numpy as np\n'), ((5366, 5415), 'numpy.mean', 'np.mean', (['D_losses_MAB_stat_true_conf_true'], {'axis': '(0)'}), '(D_losses_MAB_stat_true_conf_true, axis=0)\n', (5373, 5415), True, 'import numpy as np\n'), ((5455, 5547), 'numpy.std', 'np.std', (['(D_losses_MAB_stat_true_conf_true - D_losses_MAB_stat_true_conf_true_mean)'], {'axis': '(0)'}), '(D_losses_MAB_stat_true_conf_true -\n D_losses_MAB_stat_true_conf_true_mean, axis=0)\n', (5461, 5547), True, 'import numpy as np\n'), ((5652, 5679), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (5662, 5679), True, 'import matplotlib.pyplot as plt\n'), ((5679, 5722), 'matplotlib.pyplot.title', 'plt.title', (['"""Generator Loss During Training"""'], {}), "('Generator Loss During Training')\n", (5688, 5722), True, 'import matplotlib.pyplot as plt\n'), ((7503, 7527), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iterations"""'], {}), "('iterations')\n", (7513, 7527), True, 'import matplotlib.pyplot as plt\n'), ((7528, 7556), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Generator Loss"""'], {}), "('Generator Loss')\n", (7538, 7556), True, 'import matplotlib.pyplot as plt\n'), ((7557, 7569), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7567, 7569), True, 'import matplotlib.pyplot as plt\n'), ((7570, 7580), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7578, 7580), True, 'import matplotlib.pyplot as plt\n'), ((7656, 7683), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (7666, 7683), True, 'import matplotlib.pyplot as plt\n'), ((7683, 7730), 'matplotlib.pyplot.title', 'plt.title', (['"""Discriminator Loss During Training"""'], {}), "('Discriminator Loss During Training')\n", (7692, 7730), True, 'import matplotlib.pyplot as plt\n'), ((9511, 9535), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iterations"""'], {}), "('iterations')\n", (9521, 9535), True, 'import matplotlib.pyplot as plt\n'), ((9536, 9568), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Discriminator Loss"""'], {}), "('Discriminator Loss')\n", (9546, 9568), True, 'import matplotlib.pyplot as plt\n'), ((9569, 9581), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (9579, 9581), True, 'import matplotlib.pyplot as plt\n'), ((9582, 9592), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9590, 9592), True, 'import matplotlib.pyplot as plt\n'), ((9690, 9710), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (9701, 9710), True, 'import matplotlib.pyplot as plt\n'), ((9709, 9724), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (9717, 9724), True, 'import matplotlib.pyplot as plt\n'), ((9725, 9766), 'matplotlib.pyplot.title', 'plt.title', (['"""Fake Images for Standard GAN"""'], {}), "('Fake Images for Standard GAN')\n", (9734, 9766), True, 'import matplotlib.pyplot as plt\n'), ((9875, 9895), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (9886, 9895), True, 'import matplotlib.pyplot as plt\n'), ((9894, 9909), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (9902, 9909), True, 'import matplotlib.pyplot as plt\n'), ((9910, 9946), 'matplotlib.pyplot.title', 'plt.title', (['"""Fake Images for MAB GAN"""'], {}), "('Fake Images for MAB GAN')\n", (9919, 9946), True, 'import matplotlib.pyplot as plt\n'), ((10018, 10028), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10026, 10028), True, 'import matplotlib.pyplot as plt\n'), ((10138, 10165), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 5)'}), '(figsize=(10, 5))\n', (10148, 10165), True, 'import matplotlib.pyplot as plt\n'), ((10165, 10223), 'matplotlib.pyplot.title', 'plt.title', (['"""Number of Discriminator Updates per Iteration"""'], {}), "('Number of Discriminator Updates per Iteration')\n", (10174, 10223), True, 'import matplotlib.pyplot as plt\n'), ((10307, 10367), 'matplotlib.pyplot.plot', 'plt.plot', (['k_list_MAB_stat_true_conf_true[0]'], {'label': '"""MAB GAN"""'}), "(k_list_MAB_stat_true_conf_true[0], label='MAB GAN')\n", (10315, 10367), True, 'import matplotlib.pyplot as plt\n'), ((10369, 10393), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iterations"""'], {}), "('iterations')\n", (10379, 10393), True, 'import matplotlib.pyplot as plt\n'), ((10394, 10406), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (10404, 10406), True, 'import matplotlib.pyplot as plt\n'), ((10407, 10417), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10415, 10417), True, 'import matplotlib.pyplot as plt\n'), ((569, 583), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (580, 583), False, 'import pickle\n'), ((651, 665), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (662, 665), False, 'import pickle\n'), ((736, 750), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (747, 750), False, 'import pickle\n'), ((1195, 1209), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1206, 1209), False, 'import pickle\n'), ((1347, 1361), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1358, 1361), False, 'import pickle\n'), ((1502, 1516), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1513, 1516), False, 'import pickle\n'), ((1660, 1674), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1671, 1674), False, 'import pickle\n'), ((2359, 2373), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2370, 2373), False, 'import pickle\n'), ((2500, 2514), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2511, 2514), False, 'import pickle\n'), ((2644, 2658), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2655, 2658), False, 'import pickle\n'), ((3474, 3488), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3485, 3488), False, 'import pickle\n'), ((3625, 3639), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3636, 3639), False, 'import pickle\n'), ((3779, 3793), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3790, 3793), False, 'import pickle\n'), ((3936, 3950), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3947, 3950), False, 'import pickle\n'), ((4623, 4637), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4634, 4637), False, 'import pickle\n'), ((4773, 4787), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4784, 4787), False, 'import pickle\n'), ((4926, 4940), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4937, 4940), False, 'import pickle\n'), ((5082, 5096), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5093, 5096), False, 'import pickle\n'), ((9778, 9820), 'numpy.transpose', 'np.transpose', (['img_list_orig[-1]', '(1, 2, 0)'], {}), '(img_list_orig[-1], (1, 2, 0))\n', (9790, 9820), True, 'import numpy as np\n'), ((9958, 10019), 'numpy.transpose', 'np.transpose', (['img_list_MAB_stat_true_conf_true[-1]', '(1, 2, 0)'], {}), '(img_list_MAB_stat_true_conf_true[-1], (1, 2, 0))\n', (9970, 10019), True, 'import numpy as np\n')] |
# Description: Calculate coherences between daily vorticity terms.
#
# Author: <NAME>
# E-mail: <EMAIL>
# Date: April/2019
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from netCDF4 import Dataset
from xarray import open_dataset
from pandas import Timestamp
from xarray import DataArray
from xarray import Dataset as Datasetx
def lon360to180(lon):
"""
Converts longitude values in the range [0,360]
to longitude values in the range [-180,+180].
"""
lon = np.asanyarray(lon)
return ((lon + 180.) % 360.) - 180.
# Get segment lat/lon limits.
segs_lims = {
'Ross':[165., -130., -79., -68.],
'Amundsen-Bellingshausen':[-130., -75., -75., -68.],
'WAP':[-75., -53., -74., -60.],
'Weddell':[-62., -11., -79., -59.],
'W-EA':[-11., 77., -72., -60.],
'E-EA':[77., 165., -72., -60.],
}
segments = segs_lims.keys()
#---
head = '/ccs/home/apaloczy/analysis/'
headin = '/gpfs/alpine/cli115/proj-shared/apaloczy/vortbdgt_2005-2009daily/'
terms = ['Ibetav', 'Icurlvdiff', 'Icurlhdiff', 'Istretchp', 'Ires', 'Icurlnonl']
fnames = glob(headin+'*.nc')
fnames.sort()
# Get isobath masks.
fouter = head+'data/volmsk2500m.npz'
finner = head+'data/volmsk800m.npz'
fname_ncgrid = head+'data/POP-dzu_dzt_kzit_subsetSO.nc'
cm2m = 1e-2
ncg = Dataset(fname_ncgrid)
latt = ncg.variables['TLAT'][:]
lont = lon360to180(ncg.variables['TLONG'][:])
TAREA = Dataset(head+'data/TAREA.nc')['TAREA'][:501,:]*cm2m**2
d = np.load(fouter)
xo, yo, msko = d['lont'], d['latt'], np.bool8(d['volmsk'])
d = np.load(finner)
xi, yi, mski = d['lont'], d['latt'], np.bool8(d['volmsk'])
msk = np.logical_and(msko, ~mski)
Segments = dict()
for segment in segments:
bbox = segs_lims[segment]
if segment=='Ross':
in_seg = np.logical_or(lont>=bbox[0], lont<bbox[1])
else:
in_seg = np.logical_and(lont>=bbox[0], lont<bbox[1])
mskn = np.logical_and(msk, in_seg)
TAREAn = TAREA[mskn]
An = TAREAn.sum()
# print(An)
# plt.figure()
# plt.imshow(mskn)
t = np.array([])
Cterms = dict()
_ = [Cterms.update({term:np.array([], ndmin=1)}) for term in terms]
for fname in fnames:
date = fname.split('.')[0][-10:]
print(date)
t = np.append(t, Timestamp(date).to_pydatetime())
ds = open_dataset(fname)
for term in terms:
print(np.isnan(ds[term].values[mskn]).sum())
dsterm = ds[term]
dsterm[:,0] = np.nan
dsterm[:,-1] = np.nan
aux = np.nansum(dsterm.values[mskn]*TAREAn)/An # Area-averaging.
Cterms[term] = np.append(Cterms[term], aux)
Segments.update({segment:Cterms})
for segment in segments:
Cterms = Segments[segment]
for term in terms:
Cterms[term] = DataArray(Cterms[term], coords=dict(t=t), dims='t')
fout = head+'data/circulation_terms-%s.nc'%segment
ds = Datasetx(data_vars=Cterms, coords=dict(t=t))
ds.to_netcdf(fout)
| [
"netCDF4.Dataset",
"numpy.load",
"numpy.nansum",
"pandas.Timestamp",
"numpy.logical_and",
"numpy.asanyarray",
"xarray.open_dataset",
"numpy.bool8",
"numpy.isnan",
"numpy.append",
"numpy.array",
"numpy.logical_or",
"glob.glob"
] | [((1069, 1090), 'glob.glob', 'glob', (["(headin + '*.nc')"], {}), "(headin + '*.nc')\n", (1073, 1090), False, 'from glob import glob\n'), ((1273, 1294), 'netCDF4.Dataset', 'Dataset', (['fname_ncgrid'], {}), '(fname_ncgrid)\n', (1280, 1294), False, 'from netCDF4 import Dataset\n'), ((1441, 1456), 'numpy.load', 'np.load', (['fouter'], {}), '(fouter)\n', (1448, 1456), True, 'import numpy as np\n'), ((1520, 1535), 'numpy.load', 'np.load', (['finner'], {}), '(finner)\n', (1527, 1535), True, 'import numpy as np\n'), ((1601, 1628), 'numpy.logical_and', 'np.logical_and', (['msko', '(~mski)'], {}), '(msko, ~mski)\n', (1615, 1628), True, 'import numpy as np\n'), ((506, 524), 'numpy.asanyarray', 'np.asanyarray', (['lon'], {}), '(lon)\n', (519, 524), True, 'import numpy as np\n'), ((1494, 1515), 'numpy.bool8', 'np.bool8', (["d['volmsk']"], {}), "(d['volmsk'])\n", (1502, 1515), True, 'import numpy as np\n'), ((1573, 1594), 'numpy.bool8', 'np.bool8', (["d['volmsk']"], {}), "(d['volmsk'])\n", (1581, 1594), True, 'import numpy as np\n'), ((1846, 1873), 'numpy.logical_and', 'np.logical_and', (['msk', 'in_seg'], {}), '(msk, in_seg)\n', (1860, 1873), True, 'import numpy as np\n'), ((1970, 1982), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1978, 1982), True, 'import numpy as np\n'), ((1733, 1779), 'numpy.logical_or', 'np.logical_or', (['(lont >= bbox[0])', '(lont < bbox[1])'], {}), '(lont >= bbox[0], lont < bbox[1])\n', (1746, 1779), True, 'import numpy as np\n'), ((1794, 1841), 'numpy.logical_and', 'np.logical_and', (['(lont >= bbox[0])', '(lont < bbox[1])'], {}), '(lont >= bbox[0], lont < bbox[1])\n', (1808, 1841), True, 'import numpy as np\n'), ((2199, 2218), 'xarray.open_dataset', 'open_dataset', (['fname'], {}), '(fname)\n', (2211, 2218), False, 'from xarray import open_dataset\n'), ((1381, 1412), 'netCDF4.Dataset', 'Dataset', (["(head + 'data/TAREA.nc')"], {}), "(head + 'data/TAREA.nc')\n", (1388, 1412), False, 'from netCDF4 import Dataset\n'), ((2444, 2472), 'numpy.append', 'np.append', (['Cterms[term]', 'aux'], {}), '(Cterms[term], aux)\n', (2453, 2472), True, 'import numpy as np\n'), ((2026, 2047), 'numpy.array', 'np.array', (['[]'], {'ndmin': '(1)'}), '([], ndmin=1)\n', (2034, 2047), True, 'import numpy as np\n'), ((2367, 2406), 'numpy.nansum', 'np.nansum', (['(dsterm.values[mskn] * TAREAn)'], {}), '(dsterm.values[mskn] * TAREAn)\n', (2376, 2406), True, 'import numpy as np\n'), ((2159, 2174), 'pandas.Timestamp', 'Timestamp', (['date'], {}), '(date)\n', (2168, 2174), False, 'from pandas import Timestamp\n'), ((2249, 2280), 'numpy.isnan', 'np.isnan', (['ds[term].values[mskn]'], {}), '(ds[term].values[mskn])\n', (2257, 2280), True, 'import numpy as np\n')] |
"""
ModelGrid.py
Author: <NAME>
Affiliation: University of Colorado at Boulder
Created on: Thu Dec 5 15:49:16 MST 2013
Description: For working with big model grids. Setting them up, running them,
and analyzing them.
"""
from __future__ import print_function
import os
import gc
import re
import copy
import time
import signal
import subprocess
import numpy as np
from .GridND import GridND
from ..util import ProgressBar
from .ModelFit import ModelFit
from ..analysis import ModelSet
from ..simulations import Global21cm
from ..util.ReadData import concatenate
from ..analysis import Global21cm as _AnalyzeGlobal21cm
from ..util.Pickling import read_pickle_file, write_pickle_file
try:
from mpi4py import MPI
rank = MPI.COMM_WORLD.rank
size = MPI.COMM_WORLD.size
except ImportError:
rank = 0
size = 1
class ModelGrid(ModelFit):
"""Create an object for setting up and running model grids."""
@property
def tol(self):
if not hasattr(self, '_tol'):
if self.grid.structured:
self._tol = 1e-6
else:
self._tol = 1e-3
return self._tol
@property
def phenomenological(self):
if not hasattr(self, '_tanh'):
self._phenomenological = False
if 'tanh_model' in self.base_kwargs:
if self.base_kwargs['tanh_model']:
self._phenomenological = True
if 'gaussian_model' in self.base_kwargs:
if self.base_kwargs['gaussian_model']:
self._phenomenological = True
if 'parametric_model' in self.base_kwargs:
if self.base_kwargs['parametric_model']:
self._phenomenological = True
return self._phenomenological
@property
def simulator(self):
if not hasattr(self, '_simulator'):
self._simulator = Global21cm
return self._simulator
def _read_restart(self, prefix, procid=None):
"""
Figure out which models have already been run.
Note that how this works depends on if the gridding has been changed.
Parameters
----------
prefix : str
File prefix of files ending in *.pkl to be read in.
"""
# Array of ones/zeros: has this model already been done?
# This is only the *new* grid points.
if self.grid.structured:
done = np.zeros(self.grid.shape)
if procid is None:
procid = rank
if os.path.exists('{0!s}.{1!s}.chain.pkl'.format(prefix, str(procid).zfill(3))):
prefix_by_proc = '{0!s}.{1!s}'.format(prefix, str(procid).zfill(3))
else:
return done
#raise ValueError('This shouldn\'t happen anymore.')
# Need to see if we're running with the same number of processors
# We could probably set things up such that this isn't a problem.
#fn_by_proc = lambda proc: '{0!s}.{1!s}.chain.pkl'.format(prefix, str(proc).zfill(3))
#fn_size_p1 = fn_by_proc(size+1)
#if os.path.exists(fn_size_p1):
# raise IOError('Original grid run with more processors!')
#
# proc_id = size + 1
# while os.path.exists(fn_by_proc(proc_id)):
# proc_id += 1
# continue
# Read in current status of model grid, i.e., the old
# grid points.
chain = concatenate(read_pickle_file('{!s}.chain.pkl'.format(\
prefix_by_proc), nloads=None, verbose=False))
# If we said this is a restart, but there are no elements in the
# chain, just run the thing. It probably means the initial run never
# made it to the first checkpoint.
if chain.size == 0:
if rank == 0:
print(("Pre-existing chain file(s) empty for proc #{}. " +\
"Running from beginning.").format(rank))
if not self.grid.structured:
self.done = np.array([0])
return done
# Read parameter info
(axes_names, is_log) = read_pickle_file(\
'{!s}.pinfo.pkl'.format(prefix), nloads=1, verbose=False)
# Prepare for blobs (optional)
if os.path.exists('{!s}.binfo.pkl'.format(prefix)):
self.pf = read_pickle_file('{!s}.binfo.pkl'.format(prefix),\
nloads=1, verbose=False)
elif os.path.exists('{!s}.setup.pkl'.format(prefix)):
self.pf = read_pickle_file('{!s}.setup.pkl'.format(prefix),\
nloads=1, verbose=False)
if len(axes_names) != chain.shape[1]:
raise ValueError('Cannot change dimensionality on restart!')
if self.grid.structured:
if axes_names != self.grid.axes_names:
raise ValueError('Cannot change axes variables on restart!')
else:
for par in axes_names:
if par in self.grid.axes_names:
continue
raise ValueError('Cannot change axes variables on restart!')
# What follows is irrelevant for unstructured grids.
if (not self.grid.structured):
self.done = done = np.array([chain.shape[0]])
return done
# Loop over chain read-in from disk and compare to grid.
# Which models have already been computed?
for link in chain:
# Parameter set from pre-existing chain
kw = {par:link[i] \
for i, par in enumerate(self.grid.axes_names)}
# Its location in *new* grid
kvec = self.grid.locate_entry(kw, tol=self.tol)
if None in kvec:
continue
done[kvec] = 1
if done.sum() != len(chain):
print("WARNING: Some chain elements not found.")
return done
@property
def axes(self):
return self.grid.axes
@axes.setter
def axes(self, kwargs):
"""
Create GridND instance, construct N-D parameter space.
"""
for kwarg in kwargs:
assert kwargs[kwarg].size == np.unique(kwargs[kwarg]).size, \
"Redundant elements detected for parameter={!s}".format(kwarg)
self.grid = GridND()
# Build parameter space
self.grid.build(**kwargs)
# Save for later access
self.kwargs = kwargs
# Shortcut to parameter names
self.parameters = self.grid.axes_names
@property
def priors(self):
# Need to override priors in ModelFit
return {}
def set_models(self, models):
"""
Set all models by hand.
Parameters
----------
models : list
List of models to run. Each entry in the list should be a
dictionary of parameters that define that model. The
base_kwargs will be updated with those values at run-time.
"""
self.grid = GridND()
# Build parameter space
self.grid.all_kwargs = models
self.grid.axes_names = list(models[0].keys())
self.grid.Nd = len(self.grid.axes_names)
# Shortcut to parameter names
if not hasattr(self, 'parameters'):
self.parameters = self.grid.axes_names
def _reshape_assignments(self, assignments):
assign = []
for h, kwargs in enumerate(self.grid.all_kwargs):
# Where does this model live in the grid?
if self.grid.structured:
kvec = self.grid.locate_entry(kwargs, tol=self.tol)
else:
kvec = h
if self.is_restart:
if hasattr(self, 'done'):
if self.done[kvec]:
continue
assign.append(assignments[kvec])
return np.array(assign, dtype=int)
def prep_output_files(self, restart, clobber):
"""
Stick this in utilities folder?
"""
prefix_by_proc = '{0!s}.{1!s}'.format(self.prefix, str(rank).zfill(3))
# Reshape assignments so it's Nlinks long.
if self.grid.structured:
assignments = self._reshape_assignments(self.assignments)
if restart:
if rank == 0:
write_pickle_file(assignments,\
'{!s}.load.pkl'.format(self.prefix), ndumps=1,\
open_mode='a', safe_mode=False, verbose=False)
return
else:
if restart:
return
if rank > 0:
return
super(ModelGrid, self)._prep_from_scratch(clobber, by_proc=True)
if self.grid.structured:
write_pickle_file(assignments,\
'{!s}.load.pkl'.format(self.prefix), ndumps=1, open_mode='w',\
safe_mode=False, verbose=False)
# ModelFit makes this file by default but grids don't use it.
if os.path.exists('{!s}.logL.pkl'.format(self.prefix)) and (rank == 0):
os.remove('{!s}.logL.pkl'.format(self.prefix))
for par in self.grid.axes_names:
if re.search('Tmin', par):
f = open('{!s}.fcoll.pkl'.format(prefix_by_proc), 'wb')
f.close()
break
@property
def blank_blob(self):
if not hasattr(self, '_blank_blob'):
blob_names = self.base_kwargs['blob_names']
if blob_names is None:
self._blank_blob = []
return []
blob_ivars = self.base_kwargs['blob_ivars']
blob_funcs = self.base_kwargs['blob_funcs']
blob_nd = [len(grp) if grp is not None else 0 \
for grp in blob_ivars]
##
# Need to be a little careful with blob ivars due to
# new-ish (ivar name, ivar values) approach.
##
blob_dims = []
for grp in blob_ivars:
if grp is None:
blob_dims.append(None)
continue
dims = []
for element in grp:
ivarn, ivars = element
dims.append(len(ivars))
blob_dims.append(tuple(dims))
self._blank_blob = []
for i, group in enumerate(blob_names):
if blob_ivars[i] is None:
self._blank_blob.append([np.inf] * len(group))
else:
if blob_nd[i] == 0:
self._blank_blob.append([np.inf] * len(group))
elif blob_nd[i] == 1:
arr = np.ones([len(group), blob_dims[i][0]])
self._blank_blob.append(arr * np.inf)
elif blob_nd[i] == 2:
dims = len(group), blob_dims[i][0], \
blob_dims[i][1]
arr = np.ones(dims)
self._blank_blob.append(arr * np.inf)
return self._blank_blob
@property
def simulator(self):
if not hasattr(self, '_simulator'):
from ..simulations import Global21cm
self._simulator = Global21cm
return self._simulator
@property
def reuse_splines(self):
if not hasattr(self, '_reuse_splines'):
self._reuse_splines = True
if 'feedback_LW' in self.base_kwargs:
if self.base_kwargs['feedback_LW']:
self._reuse_splines = False
return self._reuse_splines
@reuse_splines.setter
def reuse_splines(self, value):
self._reuse_splines = value
@property
def tricks(self):
if not hasattr(self, '_tricks'):
self._tricks = []
return self._tricks
@tricks.setter
def tricks(self, value):
if not hasattr(self, '_tricks'):
assert type(value) is tuple
self._tricks = [value]
else:
self._tricks.append(value)
@property
def trick_names(self):
return list(zip(*self.tricks))[0]
@property
def trick_files(self):
return list(zip(*self.tricks))[1]
#@property
#def trick_data(self):
# if not hasattr(self, '_trick_data'):
# self._trick_data = {}
# return self._trick_data
#
#@<EMAIL>
#def trick_data(self, value):
# if not hasattr(self, '_tricks'):
# assert type(value) is dict
# self._tricks = value
# else:
# self._tricks.update(value)
@property
def is_restart(self):
if not hasattr(self, '_is_restart'):
self._is_restart = False
return self._is_restart
@is_restart.setter
def is_restart(self, value):
self._is_restart = value
def _prep_tricks(self): # pragma: no cover
"""
Super non-general at the moment sorry.
"""
if 'guess_popIII_sfrds' in self.trick_names:
i = self.trick_names.index('guess_popIII_sfrds')
fn = self.trick_files[i]
if fn is not None:
anl = ModelSet(fn)
#if not anl.chain:
# return
print("Ready to cheat!")
# HARD CODING FOR NOW
blob_name = 'popIII_Mmin'
Mmin = anl.ExtractData(blob_name)[blob_name]
zarr = anl.get_ivars(blob_name)[0]
def func(**kw):
# First, figure out where (if anywhere) the parameters
# in hand live in the lookup table.
ind = []
for k, par in enumerate(anl.parameters):
if par not in kw:
ind.append(None)
continue
try:
i = list(anl.parameters).index(kw[par])
except ValueError:
i = np.argmin(np.abs(kw[par] - anl.unique_samples[k]))
ind.append(i)
score = 0.0
for k, par in enumerate(anl.parameters):
if ind[k] is None:
continue
vals = anl.chain[:,ind[k]]
print("{0!s} {1!s} {2!s}".format(k, par, kw[par]))
score += np.abs(vals - kw[par])
best = np.argmin(score)
print("{0!s} {1!s} {2!s}".format(zarr.shape, Mmin.shape,\
best))
f = lambda zz: np.interp(zz, zarr, Mmin[best])
return {'pop_Mmin{2}': f}
#if np.min(score) == 0:
self.trick_funcs['guess_popIII_sfrds'] = func
@property
def trick_funcs(self):
if not hasattr(self, '_trick_funcs'):
self._trick_funcs = {}
return self._trick_funcs
@trick_funcs.setter
def trick_funcs(self, value):
if not hasattr(self, '_trick_funcs'):
self._trick_funcs = {}
assert type(value) is dict
self._trick_funcs.update(value)
@property
def _exit_if_fail_streak(self):
if not hasattr(self, '_exit_if_fail_streak_'):
self._exit_if_fail_streak_ = False
return self._exit_if_fail_streak_
@_exit_if_fail_streak.setter
def _exit_if_fail_streak(self, value):
self._exit_if_fail_streak_ = bool(value)
def _run_sim(self, kw, p):
failct = 0
sim = self.simulator(**p)
if self.debug:
sim.run()
blobs = sim.blobs
try:
if not self.debug:
sim.run()
blobs = copy.deepcopy(sim.blobs)
except RuntimeError:
write_pickle_file(kw, '{0!s}.{1!s}.timeout.pkl'.format(\
self.prefix, str(rank).zfill(3)), ndumps=1, open_mode='a',\
safe_mode=False, verbose=False)
blobs = copy.deepcopy(self.blank_blob)
except MemoryError:
raise MemoryError('This cannot be tolerated!')
except:
# For some reason "except Exception" doesn't catch everything...
# Write to "fail" file
write_pickle_file(kw, '{0!s}.{1!s}.fail.pkl'.format(self.prefix,\
str(rank).zfill(3)), ndumps=1, open_mode='a', safe_mode=False,\
verbose=False)
print("FAILURE: Processor #{}.".format(rank))
failct += 1
blobs = copy.deepcopy(self.blank_blob)
if 'feedback_LW_guess' in self.tricks:
try:
self.trick_data['pop_Mmin{2}'] = \
np.interp(sim.pops[2].halos.tab_z,
sim.medium.field._zarr, sim.medium.field._Mmin_now)
except AttributeError:
del self.trick_data['pop_Mmin{2}']
del sim
return blobs, failct
@property
def debug(self):
if not hasattr(self, '_debug'):
self._debug = False
return self._debug
@debug.setter
def debug(self, value):
assert type(value) in [int, bool]
self._debug = value
def run(self, prefix, clobber=False, restart=False, save_freq=500,
use_pb=True, use_checks=True, long_run=False, exit_after=None):
"""
Run model grid, for each realization thru a given turning point.
Parameters
----------
prefix : str
Prefix for all output files.
save_freq : int
Number of steps to take before writing data to disk. Note that if
you're running in parallel, this is the number of steps *each
processor* will take before writing to disk.
clobber : bool
Overwrite pre-existing files of the same prefix if one exists?
restart : bool
Append to pre-existing files of the same prefix if one exists?
Returns
-------
"""
self.prefix = prefix
self.save_freq = save_freq
prefix_by_proc = '{0!s}.{1!s}'.format(prefix, str(rank).zfill(3))
prefix_next_proc = '{0!s}.{1!s}'.format(prefix, str(rank+1).zfill(3))
if rank == 0:
print("Starting {}-element model grid.".format(self.grid.size))
chain_exists = os.path.exists('{!s}.chain.pkl'.format(prefix_by_proc))
# Kill this thing if we're about to delete files and we haven't
# set clobber=True
if chain_exists and (not clobber):
if not restart:
raise IOError(('{!s}*.pkl exists! Remove manually, set ' +\
'clobber=True, or set restart=True to append.').format(\
prefix_by_proc))
restart_actual = True
_restart_actual = np.zeros(size)
if restart and (not chain_exists):
print(("This can't be a restart (for proc #{0}), {1!s}*.pkl " +\
"not found. Starting from scratch...").format(rank, prefix))
# Note: this can occur if restarting with fewer processors
# than we originally ran with.
else:
_restart_actual[rank] = 1
restart_actual = True
# Figure out if we're running with fewer processors than
# pre-restart
fewer_procs = False
if size > 1:
_restart_np1 = np.zeros(size)
if os.path.exists('{!s}.chain.pkl'.format(prefix_next_proc)):
_restart_np1[rank] = 1
_tmp = np.zeros(size)
MPI.COMM_WORLD.Allreduce(_restart_np1, _tmp)
fewer_procs = sum(_tmp) >= size
else:
pass
# Can't have fewer procs than 1!
# Need to communicate results of restart_actual across all procs
if size > 1:
_all_restart = np.zeros(size)
MPI.COMM_WORLD.Allreduce(_restart_actual, _all_restart)
all_restart = bool(sum(_all_restart) == size)
any_restart = bool(sum(_all_restart) > 0)
else:
all_restart = any_restart = _all_restart = _restart_actual
# If user says it's not a restart, it's not a restart.
any_restart *= restart
self.is_restart = any_restart
# Load previous results if this is a restart
if any_restart:
done = self._read_restart(prefix)
if self.grid.structured:
Ndone = int(done[done >= 0].sum())
else:
Ndone = 0
# Important that this goes second, otherwise this processor
# will count the models already run by other processors, which
# will mess up the 'Nleft' calculation below.
# Figure out what models have been run by *any* processor
# in the old grid.
if size > 1:
if self.grid.structured:
tmp = np.zeros(self.grid.shape)
MPI.COMM_WORLD.Allreduce(done, tmp)
self.done = np.minimum(tmp, 1)
else:
# In this case, self.done is just an integer.
# And apparently, we don't need to know which models are done?
tmp = np.array([0])
MPI.COMM_WORLD.Allreduce(done, tmp)
self.done = tmp[0]
else:
self.done = done
# Find outputs from processors beyond those that we're currently
# using.
if fewer_procs:
if rank == 0:
# Determine what the most number of processors to have
# run this grid (at some point) is
fn_by_proc = lambda proc: '{0!s}.{1!s}.chain.pkl'.format(\
prefix, str(proc).zfill(3))
fn_size_p1 = fn_by_proc(size+1)
_done_extra = np.zeros(self.grid.shape)
if os.path.exists(fn_size_p1):
proc_id = size + 1
while os.path.exists(fn_by_proc(proc_id)):
_done_extra += self._read_restart(prefix, proc_id)
proc_id += 1
continue
print(("This grid has been run with as many as {} " +\
"processors previously. Collectively, these " +\
"processors ran {1} models.").format(proc_id,\
_done_extra.sum()))
_done_all = self.done.copy()
_done_all += _done_extra
for i in range(1, size):
MPI.COMM_WORLD.Send(_done_all, dest=i, tag=10*i)
else:
self.done = np.zeros(self.grid.shape)
MPI.COMM_WORLD.Recv(self.done, source=0, tag=10*rank)
else:
Ndone = 0
if any_restart and self.grid.structured:
mine_and_done = np.logical_and(self.assignments == rank,
self.done == 1)
Nleft = self.load[rank] - np.sum(mine_and_done)
else:
Nleft = self.load[rank]
if Nleft == 0:
print("Processor {} is done already!".format(rank))
# Print out how many models we have (left) to compute
if any_restart and self.grid.structured:
if rank == 0:
Ndone = self.done.sum()
Ntot = self.done.size
print(("Update : {0} models down, {1} to " +\
"go.").format(Ndone, Ntot - Ndone))
if size > 1:
MPI.COMM_WORLD.Barrier()
# Is everybody done?
if np.all(self.done == 1):
return
print(("Update (processor #{0}): Running {1} more " +\
"models.").format(rank, Nleft))
elif rank == 0:
if any_restart:
print('Re-starting pre-existing model set ({} models done already).'.format(self.done))
print('Running {} more models.'.format(self.grid.size))
else:
print('Running {}-element model grid.'.format(self.grid.size))
# Make some blank files for data output
self.prep_output_files(any_restart, clobber)
# Dictionary for hmf tables
fcoll = {}
# Initialize progressbar
pb = ProgressBar(Nleft, 'grid', use_pb)
pb.start()
chain_all = []; blobs_all = []
t1 = time.time()
ct = 0
was_done = 0
failct = 0
# Loop over models, use StellarPopulation.update routine
# to speed-up (don't have to re-load HMF spline as many times)
for h, kwargs in enumerate(self.grid.all_kwargs):
# Where does this model live in the grid?
if self.grid.structured:
kvec = self.grid.locate_entry(kwargs, tol=self.tol)
else:
kvec = h
# Skip if it's a restart and we've already run this model
if any_restart and self.grid.structured:
if self.done[kvec]:
was_done += 1
pb.update(ct)
continue
# Skip if this processor isn't assigned to this model
# This could be moved above the previous check
if self.assignments[kvec] != rank:
pb.update(ct)
continue
# Grab Tmin index
if self.Tmin_in_grid and self.LB == 1:
Tmin_ax = self.grid.axes[self.grid.axisnum(self.Tmin_ax_name)]
i_Tmin = Tmin_ax.locate(kwargs[self.Tmin_ax_name])
else:
i_Tmin = 0
# Copy kwargs - may need updating with pre-existing lookup tables
p = self.base_kwargs.copy()
# Log-ify stuff if necessary
kw = {}
for i, par in enumerate(self.parameters):
if self.is_log[i]:
kw[par] = 10**kwargs[par]
else:
kw[par] = kwargs[par]
p.update(kw)
# Create new splines if we haven't hit this Tmin yet in our model grid.
if self.reuse_splines and \
i_Tmin not in fcoll.keys() and (not self.phenomenological):
#raise NotImplementedError('help')
sim = self.simulator(**p)
pops = sim.pops
if hasattr(self, 'Tmin_ax_popid'):
loc = self.Tmin_ax_popid
suffix = '{{{}}}'.format(loc)
else:
if sim.pf.Npops > 1:
loc = 0
suffix = '{0}'
else:
loc = 0
suffix = ''
hmf_pars = {'pop_Tmin{!s}'.format(suffix): sim.pf['pop_Tmin{!s}'.format(suffix)],
'fcoll{!s}'.format(suffix): copy.deepcopy(pops[loc].fcoll),
'dfcolldz{!s}'.format(suffix): copy.deepcopy(pops[loc].dfcolldz)}
# Save for future iterations
fcoll[i_Tmin] = hmf_pars.copy()
p.update(hmf_pars)
# If we already have matching fcoll splines, use them!
elif self.reuse_splines and (not self.phenomenological):
hmf_pars = {'pop_Tmin{!s}'.format(suffix): fcoll[i_Tmin]['pop_Tmin{!s}'.format(suffix)],
'fcoll{!s}'.format(suffix): fcoll[i_Tmin]['fcoll{!s}'.format(suffix)],
'dfcolldz{!s}'.format(suffix): fcoll[i_Tmin]['dfcolldz{!s}'.format(suffix)]}
p.update(hmf_pars)
else:
pass
# Write this set of parameters to disk before running
# so we can troubleshoot later if the run never finishes.
procid = str(rank).zfill(3)
fn = '{0!s}.{1!s}.checkpt.pkl'.format(self.prefix, procid)
write_pickle_file(kw, fn, ndumps=1, open_mode='w',\
safe_mode=False, verbose=False)
fn = '{0!s}.{1!s}.checkpt.txt'.format(self.prefix, procid)
with open(fn, 'w') as f:
print("Simulation began: {!s}".format(time.ctime()), file=f)
# Kill if model gets stuck
if self.timeout is not None:
signal.signal(signal.SIGALRM, self._handler)
signal.alarm(self.timeout)
##
# Run simulation!
##
blobs, _failct = self._run_sim(kw, p)
failct += _failct
# Disable the alarm
if self.timeout is not None:
signal.alarm(0)
# If this is missing from a file, we'll know where things went south.
fn = '{0!s}.{1!s}.checkpt.txt'.format(self.prefix, procid)
with open(fn, 'a') as f:
print("Simulation finished: {!s}".format(time.ctime()), file=f)
chain = np.array([kwargs[key] for key in self.parameters])
chain_all.append(chain)
blobs_all.append(blobs)
ct += 1
##
# File I/O from here on out
##
pb.update(ct)
# Only record results every save_freq steps
if ct % save_freq != 0:
del p, chain, blobs
gc.collect()
continue
# Not all processors will hit the final checkpoint exactly,
# which can make collective I/O difficult. Hence the existence
# of the will_hit_final_checkpoint and wont_hit_final_checkpoint
# attributes
if rank == 0 and use_checks:
print("Checkpoint #{0}: {1!s}".format(ct // save_freq,\
time.ctime()))
# First assemble data from all processors?
# Analogous to assembling data from all walkers in MCMC
write_pickle_file(chain_all,\
'{!s}.chain.pkl'.format(prefix_by_proc), ndumps=1,\
open_mode='a', safe_mode=False, verbose=False)
self.save_blobs(blobs_all, False, prefix_by_proc)
del p, chain, blobs
del chain_all, blobs_all
gc.collect()
chain_all = []; blobs_all = []
# If, after the first checkpoint, we only have 'failed' models,
# raise an error.
if (ct == failct) and self._exit_if_fail_streak:
raise ValueError('Only failed models up to first checkpoint!')
# This is meant to prevent crashes due to memory fragmentation.
# For it to work (when we run for a really long time), we need
# to write a shell script that calls the .py script that
# executes ModelGrid.run many times, with each call setting
# exit_after to 1 or perhaps a few, depending on the amount
# of memory on hand. This is apparently less of an issue in Python 3.3
if exit_after is not None:
if exit_after == (ct // save_freq):
break
pb.finish()
# Need to make sure we write results to disk if we didn't
# hit the last checkpoint
if chain_all:
write_pickle_file(chain_all,\
'{!s}.chain.pkl'.format(prefix_by_proc), ndumps=1,\
open_mode='a', safe_mode=False, verbose=False)
if blobs_all:
self.save_blobs(blobs_all, False, prefix_by_proc)
print("Processor {0}: Wrote {1!s}.*.pkl ({2!s})".format(rank, prefix,\
time.ctime()))
# You. shall. not. pass.
# Maybe unnecessary?
if size > 1:
MPI.COMM_WORLD.Barrier()
t2 = time.time()
##
# FINAL INFO
##
if rank == 0:
print("Calculation complete: {!s}".format(time.ctime()))
dt = t2 - t1
if dt > 3600:
print("Elapsed time (hr) : {0:.3g}".format(dt / 3600.))
else:
print("Elapsed time (min) : {0:.3g}".format(dt / 60.))
@property
def Tmin_in_grid(self):
"""
Determine if Tmin is an axis in our model grid.
"""
if not hasattr(self, '_Tmin_in_grid'):
ct = 0
name = None
self._Tmin_in_grid = False
for par in self.grid.axes_names:
if re.search('Tmin', par):
ct += 1
self._Tmin_in_grid = True
name = par
self.Tmin_ax_name = name
if ct > 1:
raise NotImplemented('Trouble w/ multiple Tmin axes!')
return self._Tmin_in_grid
@property
def nwalkers(self):
# Each processor writes its own data
return 1
@property
def assignments(self):
if not hasattr(self, '_assignments'):
#if hasattr(self, 'grid'):
# if self.grid.structured:
# self._structured_balance(method=0)
# return
self.LoadBalance()
return self._assignments
@assignments.setter
def assignments(self, value):
self._assignments = value
@property
def load(self):
if not hasattr(self, '_load'):
self._load = [np.array(self.assignments == i).sum() \
for i in range(size)]
self._load = np.array(self._load)
return self._load
@property
def LB(self):
if not hasattr(self, '_LB'):
self._LB = 0
return self._LB
@LB.setter
def LB(self, value):
self._LB = value
def _balance_via_grouping(self, par):
pass
def _balance_via_sorting(self, par):
pass
def LoadBalance(self, method=0, par=None):
if self.grid.structured:
self._structured_balance(method=method, par=par)
else:
self._unstructured_balance(method=method, par=par)
def _unstructured_balance(self, method=0, par=None):
if rank == 0:
order = list(np.arange(size))
self._assignments = []
while len(self.assignments) < self.grid.size:
self._assignments.extend(order)
self._assignments = np.array(self._assignments[0:self.grid.size])
if size == 1:
self.LB = 0
return
# Communicate assignments to workers
for i in range(1, size):
MPI.COMM_WORLD.Send(self._assignments, dest=i, tag=10*i)
else:
self._assignments = np.empty(self.grid.size, dtype=np.int)
MPI.COMM_WORLD.Recv(self._assignments, source=0,
tag=10*rank)
self.LB = 0
def _structured_balance(self, method=0, par=None):
"""
Determine which processors are to run which models.
Parameters
----------
method : int
0 : OFF
1 : Minimize the number of values of `par' each processor gets.
Good for, e.g., Tmin.
2 : Maximize the number of values of `par' each processor gets.
Useful if increasing `par' slows down the calculation.
Returns
-------
Nothing. Creates "assignments" attribute, which has the same shape
as the grid, with each element the rank of the processor assigned to
that particular model.
"""
self.LB = method
if size == 1:
self._assignments = np.zeros(self.grid.shape, dtype=int)
return
if method in [1, 2]:
assert par in self.grid.axes_names, \
"Supplied load-balancing parameter {!s} not in grid!".format(par)
par_i = self.grid.axes_names.index(par)
par_ax = self.grid.axes[par_i]
par_N = par_ax.size
else:
par_N = np.inf
if method not in [0, 1, 2, 3]:
raise NotImplementedError('Unrecognized load-balancing method {}'.format(method))
# No load balancing. Equal # of models per processor
if method == 0 or (par_N < size):
k = 0
tmp_assignments = np.zeros(self.grid.shape, dtype=int)
for loc, value in np.ndenumerate(tmp_assignments):
if k % size != rank:
k += 1
continue
tmp_assignments[loc] = rank
k += 1
# Communicate results
self._assignments = np.zeros(self.grid.shape, dtype=int)
MPI.COMM_WORLD.Allreduce(tmp_assignments, self._assignments)
# Load balance over expensive axis
elif method in [1, 2]:
self._assignments = np.zeros(self.grid.shape, dtype=int)
slc = [slice(0,None,1) for i in range(self.grid.Nd)]
k = 0 # only used for method 1
# Disclaimer: there's a probably a much more slick way of doing this
# For each value of the input 'par', split up the work.
# If method == 1, make it so that each processor gets only a
# small subset of values for that parameter (e.g., sensible
# for pop_Tmin), or method == 2 make it so that all processors get
# a variety of values of input parameter, which is useful when
# increasing values of this parameter slow down the calculation.
for i in range(par_N):
# Ellipses in all dimensions except that corresponding to a
# particular value of input 'par'
slc[par_i] = i
if method == 1:
self._assignments[slc] = k \
* np.ones_like(self._assignments[slc], dtype=int)
# Cycle through processor numbers
k += 1
if k == size:
k = 0
elif method == 2:
tmp = np.ones_like(self._assignments[slc], dtype=int)
leftovers = tmp.size % size
assign = np.arange(size)
arr = np.array([assign] * int(tmp.size // size)).ravel()
if leftovers != 0:
# This could be a little more efficient
arr = np.concatenate((arr, assign[0:leftovers]))
self._assignments[slc] = np.reshape(arr, tmp.size)
else:
raise ValueError('No method={}!'.format(method))
elif method == 3:
# Do it randomly. Need to be careful in parallel.
if rank != 0:
buff = np.zeros(self.grid.dims, dtype=int)
else:
# Could do the assignment 100 times and pick the realization
# with the most even distribution of work (as far as we
# can tell a-priori), but eh.
arr = np.random.randint(low=0, high=size, size=self.grid.size)
buff = np.reshape(arr, self.grid.dims)
self._assignments = np.zeros(self.grid.dims, dtype=int)
nothing = MPI.COMM_WORLD.Allreduce(buff, self._assignments)
else:
raise ValueError('No method={}!'.format(method))
| [
"numpy.sum",
"numpy.abs",
"mpi4py.MPI.COMM_WORLD.Recv",
"numpy.empty",
"time.ctime",
"numpy.ones",
"numpy.argmin",
"gc.collect",
"numpy.random.randint",
"numpy.arange",
"numpy.interp",
"mpi4py.MPI.COMM_WORLD.Allreduce",
"numpy.unique",
"os.path.exists",
"numpy.reshape",
"signal.alarm",... | [((7816, 7843), 'numpy.array', 'np.array', (['assign'], {'dtype': 'int'}), '(assign, dtype=int)\n', (7824, 7843), True, 'import numpy as np\n'), ((18849, 18863), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (18857, 18863), True, 'import numpy as np\n'), ((24612, 24623), 'time.time', 'time.time', ([], {}), '()\n', (24621, 24623), False, 'import time\n'), ((31891, 31902), 'time.time', 'time.time', ([], {}), '()\n', (31900, 31902), False, 'import time\n'), ((2435, 2460), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {}), '(self.grid.shape)\n', (2443, 2460), True, 'import numpy as np\n'), ((5203, 5229), 'numpy.array', 'np.array', (['[chain.shape[0]]'], {}), '([chain.shape[0]])\n', (5211, 5229), True, 'import numpy as np\n'), ((9117, 9139), 're.search', 're.search', (['"""Tmin"""', 'par'], {}), "('Tmin', par)\n", (9126, 9139), False, 'import re\n'), ((19425, 19439), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (19433, 19439), True, 'import numpy as np\n'), ((19573, 19587), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (19581, 19587), True, 'import numpy as np\n'), ((19600, 19644), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['_restart_np1', '_tmp'], {}), '(_restart_np1, _tmp)\n', (19624, 19644), False, 'from mpi4py import MPI\n'), ((19887, 19901), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (19895, 19901), True, 'import numpy as np\n'), ((19914, 19969), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['_restart_actual', '_all_restart'], {}), '(_restart_actual, _all_restart)\n', (19938, 19969), False, 'from mpi4py import MPI\n'), ((23046, 23102), 'numpy.logical_and', 'np.logical_and', (['(self.assignments == rank)', '(self.done == 1)'], {}), '(self.assignments == rank, self.done == 1)\n', (23060, 23102), True, 'import numpy as np\n'), ((23810, 23832), 'numpy.all', 'np.all', (['(self.done == 1)'], {}), '(self.done == 1)\n', (23816, 23832), True, 'import numpy as np\n'), ((29112, 29162), 'numpy.array', 'np.array', (['[kwargs[key] for key in self.parameters]'], {}), '([kwargs[key] for key in self.parameters])\n', (29120, 29162), True, 'import numpy as np\n'), ((30378, 30390), 'gc.collect', 'gc.collect', ([], {}), '()\n', (30388, 30390), False, 'import gc\n'), ((31852, 31876), 'mpi4py.MPI.COMM_WORLD.Barrier', 'MPI.COMM_WORLD.Barrier', ([], {}), '()\n', (31874, 31876), False, 'from mpi4py import MPI\n'), ((33586, 33606), 'numpy.array', 'np.array', (['self._load'], {}), '(self._load)\n', (33594, 33606), True, 'import numpy as np\n'), ((34449, 34494), 'numpy.array', 'np.array', (['self._assignments[0:self.grid.size]'], {}), '(self._assignments[0:self.grid.size])\n', (34457, 34494), True, 'import numpy as np\n'), ((34780, 34818), 'numpy.empty', 'np.empty', (['self.grid.size'], {'dtype': 'np.int'}), '(self.grid.size, dtype=np.int)\n', (34788, 34818), True, 'import numpy as np\n'), ((34831, 34894), 'mpi4py.MPI.COMM_WORLD.Recv', 'MPI.COMM_WORLD.Recv', (['self._assignments'], {'source': '(0)', 'tag': '(10 * rank)'}), '(self._assignments, source=0, tag=10 * rank)\n', (34850, 34894), False, 'from mpi4py import MPI\n'), ((35709, 35745), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {'dtype': 'int'}), '(self.grid.shape, dtype=int)\n', (35717, 35745), True, 'import numpy as np\n'), ((36383, 36419), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {'dtype': 'int'}), '(self.grid.shape, dtype=int)\n', (36391, 36419), True, 'import numpy as np\n'), ((36450, 36481), 'numpy.ndenumerate', 'np.ndenumerate', (['tmp_assignments'], {}), '(tmp_assignments)\n', (36464, 36481), True, 'import numpy as np\n'), ((36713, 36749), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {'dtype': 'int'}), '(self.grid.shape, dtype=int)\n', (36721, 36749), True, 'import numpy as np\n'), ((36762, 36822), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['tmp_assignments', 'self._assignments'], {}), '(tmp_assignments, self._assignments)\n', (36786, 36822), False, 'from mpi4py import MPI\n'), ((4006, 4019), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (4014, 4019), True, 'import numpy as np\n'), ((15757, 15781), 'copy.deepcopy', 'copy.deepcopy', (['sim.blobs'], {}), '(sim.blobs)\n', (15770, 15781), False, 'import copy\n'), ((16025, 16055), 'copy.deepcopy', 'copy.deepcopy', (['self.blank_blob'], {}), '(self.blank_blob)\n', (16038, 16055), False, 'import copy\n'), ((16566, 16596), 'copy.deepcopy', 'copy.deepcopy', (['self.blank_blob'], {}), '(self.blank_blob)\n', (16579, 16596), False, 'import copy\n'), ((16733, 16824), 'numpy.interp', 'np.interp', (['sim.pops[2].halos.tab_z', 'sim.medium.field._zarr', 'sim.medium.field._Mmin_now'], {}), '(sim.pops[2].halos.tab_z, sim.medium.field._zarr, sim.medium.field\n ._Mmin_now)\n', (16742, 16824), True, 'import numpy as np\n'), ((23185, 23206), 'numpy.sum', 'np.sum', (['mine_and_done'], {}), '(mine_and_done)\n', (23191, 23206), True, 'import numpy as np\n'), ((23736, 23760), 'mpi4py.MPI.COMM_WORLD.Barrier', 'MPI.COMM_WORLD.Barrier', ([], {}), '()\n', (23758, 23760), False, 'from mpi4py import MPI\n'), ((28485, 28529), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'self._handler'], {}), '(signal.SIGALRM, self._handler)\n', (28498, 28529), False, 'import signal\n'), ((28546, 28572), 'signal.alarm', 'signal.alarm', (['self.timeout'], {}), '(self.timeout)\n', (28558, 28572), False, 'import signal\n'), ((28804, 28819), 'signal.alarm', 'signal.alarm', (['(0)'], {}), '(0)\n', (28816, 28819), False, 'import signal\n'), ((29499, 29511), 'gc.collect', 'gc.collect', ([], {}), '()\n', (29509, 29511), False, 'import gc\n'), ((31741, 31753), 'time.ctime', 'time.ctime', ([], {}), '()\n', (31751, 31753), False, 'import time\n'), ((32572, 32594), 're.search', 're.search', (['"""Tmin"""', 'par'], {}), "('Tmin', par)\n", (32581, 32594), False, 'import re\n'), ((34258, 34273), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (34267, 34273), True, 'import numpy as np\n'), ((34676, 34734), 'mpi4py.MPI.COMM_WORLD.Send', 'MPI.COMM_WORLD.Send', (['self._assignments'], {'dest': 'i', 'tag': '(10 * i)'}), '(self._assignments, dest=i, tag=10 * i)\n', (34695, 34734), False, 'from mpi4py import MPI\n'), ((36931, 36967), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {'dtype': 'int'}), '(self.grid.shape, dtype=int)\n', (36939, 36967), True, 'import numpy as np\n'), ((6120, 6144), 'numpy.unique', 'np.unique', (['kwargs[kwarg]'], {}), '(kwargs[kwarg])\n', (6129, 6144), True, 'import numpy as np\n'), ((14456, 14472), 'numpy.argmin', 'np.argmin', (['score'], {}), '(score)\n', (14465, 14472), True, 'import numpy as np\n'), ((20958, 20983), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {}), '(self.grid.shape)\n', (20966, 20983), True, 'import numpy as np\n'), ((21004, 21039), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['done', 'tmp'], {}), '(done, tmp)\n', (21028, 21039), False, 'from mpi4py import MPI\n'), ((21072, 21090), 'numpy.minimum', 'np.minimum', (['tmp', '(1)'], {}), '(tmp, 1)\n', (21082, 21090), True, 'import numpy as np\n'), ((21288, 21301), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (21296, 21301), True, 'import numpy as np\n'), ((21322, 21357), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['done', 'tmp'], {}), '(done, tmp)\n', (21346, 21357), False, 'from mpi4py import MPI\n'), ((21953, 21978), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {}), '(self.grid.shape)\n', (21961, 21978), True, 'import numpy as np\n'), ((22002, 22028), 'os.path.exists', 'os.path.exists', (['fn_size_p1'], {}), '(fn_size_p1)\n', (22016, 22028), False, 'import os\n'), ((22831, 22856), 'numpy.zeros', 'np.zeros', (['self.grid.shape'], {}), '(self.grid.shape)\n', (22839, 22856), True, 'import numpy as np\n'), ((22877, 22932), 'mpi4py.MPI.COMM_WORLD.Recv', 'MPI.COMM_WORLD.Recv', (['self.done'], {'source': '(0)', 'tag': '(10 * rank)'}), '(self.done, source=0, tag=10 * rank)\n', (22896, 22932), False, 'from mpi4py import MPI\n'), ((27091, 27121), 'copy.deepcopy', 'copy.deepcopy', (['pops[loc].fcoll'], {}), '(pops[loc].fcoll)\n', (27104, 27121), False, 'import copy\n'), ((27174, 27207), 'copy.deepcopy', 'copy.deepcopy', (['pops[loc].dfcolldz'], {}), '(pops[loc].dfcolldz)\n', (27187, 27207), False, 'import copy\n'), ((32023, 32035), 'time.ctime', 'time.ctime', ([], {}), '()\n', (32033, 32035), False, 'import time\n'), ((39274, 39309), 'numpy.zeros', 'np.zeros', (['self.grid.dims'], {'dtype': 'int'}), '(self.grid.dims, dtype=int)\n', (39282, 39309), True, 'import numpy as np\n'), ((39332, 39381), 'mpi4py.MPI.COMM_WORLD.Allreduce', 'MPI.COMM_WORLD.Allreduce', (['buff', 'self._assignments'], {}), '(buff, self._assignments)\n', (39356, 39381), False, 'from mpi4py import MPI\n'), ((14405, 14427), 'numpy.abs', 'np.abs', (['(vals - kw[par])'], {}), '(vals - kw[par])\n', (14411, 14427), True, 'import numpy as np\n'), ((14619, 14650), 'numpy.interp', 'np.interp', (['zz', 'zarr', 'Mmin[best]'], {}), '(zz, zarr, Mmin[best])\n', (14628, 14650), True, 'import numpy as np\n'), ((22727, 22777), 'mpi4py.MPI.COMM_WORLD.Send', 'MPI.COMM_WORLD.Send', (['_done_all'], {'dest': 'i', 'tag': '(10 * i)'}), '(_done_all, dest=i, tag=10 * i)\n', (22746, 22777), False, 'from mpi4py import MPI\n'), ((28365, 28377), 'time.ctime', 'time.ctime', ([], {}), '()\n', (28375, 28377), False, 'import time\n'), ((29068, 29080), 'time.ctime', 'time.ctime', ([], {}), '()\n', (29078, 29080), False, 'import time\n'), ((29921, 29933), 'time.ctime', 'time.ctime', ([], {}), '()\n', (29931, 29933), False, 'import time\n'), ((33482, 33513), 'numpy.array', 'np.array', (['(self.assignments == i)'], {}), '(self.assignments == i)\n', (33490, 33513), True, 'import numpy as np\n'), ((38858, 38893), 'numpy.zeros', 'np.zeros', (['self.grid.dims'], {'dtype': 'int'}), '(self.grid.dims, dtype=int)\n', (38866, 38893), True, 'import numpy as np\n'), ((39129, 39185), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': 'size', 'size': 'self.grid.size'}), '(low=0, high=size, size=self.grid.size)\n', (39146, 39185), True, 'import numpy as np\n'), ((39209, 39240), 'numpy.reshape', 'np.reshape', (['arr', 'self.grid.dims'], {}), '(arr, self.grid.dims)\n', (39219, 39240), True, 'import numpy as np\n'), ((37906, 37953), 'numpy.ones_like', 'np.ones_like', (['self._assignments[slc]'], {'dtype': 'int'}), '(self._assignments[slc], dtype=int)\n', (37918, 37953), True, 'import numpy as np\n'), ((38160, 38207), 'numpy.ones_like', 'np.ones_like', (['self._assignments[slc]'], {'dtype': 'int'}), '(self._assignments[slc], dtype=int)\n', (38172, 38207), True, 'import numpy as np\n'), ((38287, 38302), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (38296, 38302), True, 'import numpy as np\n'), ((38602, 38627), 'numpy.reshape', 'np.reshape', (['arr', 'tmp.size'], {}), '(arr, tmp.size)\n', (38612, 38627), True, 'import numpy as np\n'), ((10910, 10923), 'numpy.ones', 'np.ones', (['dims'], {}), '(dims)\n', (10917, 10923), True, 'import numpy as np\n'), ((38513, 38555), 'numpy.concatenate', 'np.concatenate', (['(arr, assign[0:leftovers])'], {}), '((arr, assign[0:leftovers]))\n', (38527, 38555), True, 'import numpy as np\n'), ((13989, 14028), 'numpy.abs', 'np.abs', (['(kw[par] - anl.unique_samples[k])'], {}), '(kw[par] - anl.unique_samples[k])\n', (13995, 14028), True, 'import numpy as np\n')] |
# Import modules
import numpy as np
import os
from sklearn.linear_model import ElasticNetCV
import pandas as pd
import time
from joblib import Parallel, delayed
import multiprocessing
from optparse import OptionParser
from local_functions_20200813 import make_weights, weight_data, select_frequent_dominate_genera, Elastic_net_fitting
# Define functions
def make_Smap_input(abund, target_otu, uncontinuous, uncontinous_loc):
print('Process data for otu No. %s' % str(target_otu + 1))
# Make input for the elastic_net
abund = np.matrix(abund)
block = np.append(abund[1:, target_otu], abund[0:-1, ], axis=1)
# Delete uncontinuous data
if uncontinuous == True:
block = np.delete(block, uncontinous_loc, axis=0)
# Scaling the input
## Each time series is normalized to have a mean of 0 and standard deviation of 1 before analysis with S-maps
block = (block - np.average(block, axis=0)) / np.std(block, axis=0)
return block
def predict_weight_possible_shift(abund, empirical_states, target_otu, target_abund, direction, theta,
weighted_posshifts, target_states, DD_analyzed_states):
print('Predict weighted possible shift at state No. %s' % str(target_abund + 1))
# Make input for the elastic_net using both time series and empirical data
## Predict the possible shift
### Select the wanted genera according to the time series data
wanted_empirical_state = pd.DataFrame(empirical_states, columns=abund.columns)
wanted_empirical_state.fillna(0, inplace=True)
### Combine the time series and empirical data except state at time t and t+1
if target_abund == abund.shape[0] - 1:
abund == abund
else:
abund.drop([target_abund+1])
wanted_abund = abund.append(wanted_empirical_state)
### Find possible shift
target_state = abund.iloc[target_abund, :]
if direction == 'increase':
possible_state = np.where(wanted_abund.iloc[:, target_otu] > target_state.iloc[target_otu])[0]
if direction == 'decrease':
possible_state = np.where(wanted_abund.iloc[:, target_otu] < target_state.iloc[target_otu])[0]
if direction == 'constant':
possible_state = np.where(wanted_abund.iloc[:, target_otu] == target_state.iloc[target_otu])[0]
possible_state = np.delete(possible_state, np.where(possible_state == target_abund))
if len(possible_state > 0):
possible_shifts = wanted_abund.iloc[possible_state, :]
### Calculate the weights
E_dist = np.array(np.sqrt(np.sum((possible_shifts - target_state) ** 2, axis=1)))
w = np.array(make_weights(E_dist, theta))
### Predict and collect weighted possible shift
weighted_posshift = np.dot(w, possible_shifts) / sum(w)
weighted_posshifts.append(weighted_posshift)
target_states.append(target_state)
DD_analyzed_states.append(target_abund)
else:
print('No possible shift in direction %s' % direction)
return weighted_posshifts, target_states, DD_analyzed_states
def main(interest_otu):
# Density dependent regularized S-map
## Make block data from the selected abundance data
print('Process data for otu No. %s' % str(interest_otu + 1))
for direction in ['increase', 'decrease']:
# Start making input
weighted_posshifts = []
target_states = []
DD_analyzed_states = []
for target_abund in range(abund.shape[0]):
weighted_posshifts, target_states, DD_analyzed_states = predict_weight_possible_shift(abund,
empirical_states,
interest_otu,
target_abund,
direction, theta,
weighted_posshifts,
target_states,
DD_analyzed_states)
weighted_posshifts = np.matrix(weighted_posshifts)
target_states = np.matrix(target_states)
for target_otu in range(weighted_posshifts.shape[1]):
block = np.append(weighted_posshifts[:, target_otu], target_states, axis=1)
##Output analyzed state numbers
print('/'.join([output_dir_DD, direction, '_'.join([str(interest_otu), str(target_otu), 'analyzed_states.csv'])]))
pd.DataFrame(data=DD_analyzed_states).to_csv(
'/'.join([output_dir_DD, direction, '_'.join([str(interest_otu), str(target_otu), 'analyzed_states.csv'])]),
encoding='utf-8')
## Scaling the input
## Each time series is normalized to have a mean of 0 and standard deviation of 1 before analysis with S-maps
block = (block - np.average(block, axis=0)) / np.std(block, axis=0)
## Use elastic_net to infer Jacobian matrices from the block
Elastic_net_fitting(block, target_otu, interest_otu, theta, train_len,
cv, iteration, l_grid, '/'.join([output_dir_DD, direction]))
if __name__ == '__main__':
# Imnput data and setting
parse = OptionParser()
parse.add_option('-I', '--input', dest='input', default='../inputs/month_sample.csv')
parse.add_option('-O', '--output', dest='output', default='../outputs')
(options, args) = parse.parse_args()
input = options.input
empirical_state_loc = '../input_2/level-5.csv'
dominate_threshold = 1 # More than threshold
zero_frequency_threshold = 20 # Less than threshold
# target_otu = 0
target_abund = 1
theta = 2
l_grid = 0.05
iteration = 100000
cv = 10
train_len = 3
t_range = 6
output_dir = '/'.join([options.output, 'S-map'])
output_dir_DD = '/'.join([options.output, 'DD_S-map'])
uncontinous = True
uncontinous_loc = [26,58,89,118,146,170]
# Work in parallel
num_cores = 40
# Make ouput direction
path_coefs = '/'.join([output_dir, 'coefs'])
if not os.path.exists(path_coefs):
os.makedirs('/'.join([output_dir, 'coefs']))
path_fitresult = '/'.join([output_dir, 'fit_result'])
if not os.path.exists(path_fitresult):
os.makedirs('/'.join([output_dir, 'fit_result']))
for direction in ['increase', 'decrease']:
## Make ouput direction
path_coefs = '/'.join([output_dir_DD, direction, 'coefs'])
if not os.path.exists(path_coefs):
os.makedirs('/'.join([output_dir_DD, direction, 'coefs']))
path_fitresult = '/'.join([output_dir_DD, direction, 'fit_result'])
if not os.path.exists(path_fitresult):
os.makedirs('/'.join([output_dir_DD, direction, 'fit_result']))
# Select frequent and dominate genera
abund = select_frequent_dominate_genera(input, dominate_threshold, zero_frequency_threshold, True)
print('Output analyzed OTUs')
abund.to_csv('/'.join([options.output,'abund.csv']))
# Select the wanted genera in empirical states
empirical_states = select_frequent_dominate_genera(empirical_state_loc, dominate_threshold,
zero_frequency_threshold, False)
# Infer Jacobian matrices for each OTU and state
Parallel(n_jobs=num_cores, backend='multiprocessing')(delayed(main)
(interest_otu) for interest_otu in range(abund.shape[1]))
| [
"pandas.DataFrame",
"numpy.matrix",
"numpy.average",
"numpy.sum",
"optparse.OptionParser",
"numpy.std",
"local_functions_20200813.make_weights",
"os.path.exists",
"numpy.append",
"numpy.where",
"joblib.Parallel",
"numpy.dot",
"joblib.delayed",
"numpy.delete",
"local_functions_20200813.se... | [((539, 555), 'numpy.matrix', 'np.matrix', (['abund'], {}), '(abund)\n', (548, 555), True, 'import numpy as np\n'), ((568, 622), 'numpy.append', 'np.append', (['abund[1:, target_otu]', 'abund[0:-1,]'], {'axis': '(1)'}), '(abund[1:, target_otu], abund[0:-1,], axis=1)\n', (577, 622), True, 'import numpy as np\n'), ((1459, 1512), 'pandas.DataFrame', 'pd.DataFrame', (['empirical_states'], {'columns': 'abund.columns'}), '(empirical_states, columns=abund.columns)\n', (1471, 1512), True, 'import pandas as pd\n'), ((5582, 5596), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (5594, 5596), False, 'from optparse import OptionParser\n'), ((7197, 7291), 'local_functions_20200813.select_frequent_dominate_genera', 'select_frequent_dominate_genera', (['input', 'dominate_threshold', 'zero_frequency_threshold', '(True)'], {}), '(input, dominate_threshold,\n zero_frequency_threshold, True)\n', (7228, 7291), False, 'from local_functions_20200813 import make_weights, weight_data, select_frequent_dominate_genera, Elastic_net_fitting\n'), ((7454, 7563), 'local_functions_20200813.select_frequent_dominate_genera', 'select_frequent_dominate_genera', (['empirical_state_loc', 'dominate_threshold', 'zero_frequency_threshold', '(False)'], {}), '(empirical_state_loc, dominate_threshold,\n zero_frequency_threshold, False)\n', (7485, 7563), False, 'from local_functions_20200813 import make_weights, weight_data, select_frequent_dominate_genera, Elastic_net_fitting\n'), ((700, 741), 'numpy.delete', 'np.delete', (['block', 'uncontinous_loc'], {'axis': '(0)'}), '(block, uncontinous_loc, axis=0)\n', (709, 741), True, 'import numpy as np\n'), ((930, 951), 'numpy.std', 'np.std', (['block'], {'axis': '(0)'}), '(block, axis=0)\n', (936, 951), True, 'import numpy as np\n'), ((4407, 4436), 'numpy.matrix', 'np.matrix', (['weighted_posshifts'], {}), '(weighted_posshifts)\n', (4416, 4436), True, 'import numpy as np\n'), ((4461, 4485), 'numpy.matrix', 'np.matrix', (['target_states'], {}), '(target_states)\n', (4470, 4485), True, 'import numpy as np\n'), ((6443, 6469), 'os.path.exists', 'os.path.exists', (['path_coefs'], {}), '(path_coefs)\n', (6457, 6469), False, 'import os\n'), ((6593, 6623), 'os.path.exists', 'os.path.exists', (['path_fitresult'], {}), '(path_fitresult)\n', (6607, 6623), False, 'import os\n'), ((7673, 7726), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'num_cores', 'backend': '"""multiprocessing"""'}), "(n_jobs=num_cores, backend='multiprocessing')\n", (7681, 7726), False, 'from joblib import Parallel, delayed\n'), ((901, 926), 'numpy.average', 'np.average', (['block'], {'axis': '(0)'}), '(block, axis=0)\n', (911, 926), True, 'import numpy as np\n'), ((1948, 2022), 'numpy.where', 'np.where', (['(wanted_abund.iloc[:, target_otu] > target_state.iloc[target_otu])'], {}), '(wanted_abund.iloc[:, target_otu] > target_state.iloc[target_otu])\n', (1956, 2022), True, 'import numpy as np\n'), ((2083, 2157), 'numpy.where', 'np.where', (['(wanted_abund.iloc[:, target_otu] < target_state.iloc[target_otu])'], {}), '(wanted_abund.iloc[:, target_otu] < target_state.iloc[target_otu])\n', (2091, 2157), True, 'import numpy as np\n'), ((2218, 2293), 'numpy.where', 'np.where', (['(wanted_abund.iloc[:, target_otu] == target_state.iloc[target_otu])'], {}), '(wanted_abund.iloc[:, target_otu] == target_state.iloc[target_otu])\n', (2226, 2293), True, 'import numpy as np\n'), ((2348, 2388), 'numpy.where', 'np.where', (['(possible_state == target_abund)'], {}), '(possible_state == target_abund)\n', (2356, 2388), True, 'import numpy as np\n'), ((2630, 2657), 'local_functions_20200813.make_weights', 'make_weights', (['E_dist', 'theta'], {}), '(E_dist, theta)\n', (2642, 2657), False, 'from local_functions_20200813 import make_weights, weight_data, select_frequent_dominate_genera, Elastic_net_fitting\n'), ((2743, 2769), 'numpy.dot', 'np.dot', (['w', 'possible_shifts'], {}), '(w, possible_shifts)\n', (2749, 2769), True, 'import numpy as np\n'), ((4568, 4635), 'numpy.append', 'np.append', (['weighted_posshifts[:, target_otu]', 'target_states'], {'axis': '(1)'}), '(weighted_posshifts[:, target_otu], target_states, axis=1)\n', (4577, 4635), True, 'import numpy as np\n'), ((6844, 6870), 'os.path.exists', 'os.path.exists', (['path_coefs'], {}), '(path_coefs)\n', (6858, 6870), False, 'import os\n'), ((7034, 7064), 'os.path.exists', 'os.path.exists', (['path_fitresult'], {}), '(path_fitresult)\n', (7048, 7064), False, 'import os\n'), ((2553, 2606), 'numpy.sum', 'np.sum', (['((possible_shifts - target_state) ** 2)'], {'axis': '(1)'}), '((possible_shifts - target_state) ** 2, axis=1)\n', (2559, 2606), True, 'import numpy as np\n'), ((5239, 5260), 'numpy.std', 'np.std', (['block'], {'axis': '(0)'}), '(block, axis=0)\n', (5245, 5260), True, 'import numpy as np\n'), ((7727, 7740), 'joblib.delayed', 'delayed', (['main'], {}), '(main)\n', (7734, 7740), False, 'from joblib import Parallel, delayed\n'), ((4820, 4857), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'DD_analyzed_states'}), '(data=DD_analyzed_states)\n', (4832, 4857), True, 'import pandas as pd\n'), ((5210, 5235), 'numpy.average', 'np.average', (['block'], {'axis': '(0)'}), '(block, axis=0)\n', (5220, 5235), True, 'import numpy as np\n')] |
import copy
import os.path
import output_utils
import sys
import torch
import numpy as np
import argparse
import time
import data_utils
import models
import model_utils
import config_utils
import embedding_loader
import sklearn.metrics
import pandas as pd # Try to avoid?
from collections import Counter, defaultdict
# torch.cuda.empty_cache()
def main():
args, settings = parse_args_and_settings()
logger = output_utils.Logger(args)
logger.shout('python main.py ' + ' '.join(sys.argv[1:]))
num_threads = 5
torch.set_num_threads(num_threads)
# Load entity map (needed for all phases; primarily for loading data):
entity_idx_to_name, entity_name_to_idx = data_utils.load_entity_map(settings.data.entity_map)
# Load Video Scene Embedding vector map / scene_embedding_map : (e.g. {"5000-7000-00005.npy":0,...}) / scene_embedding [[0.12,0.35,0.28...],...]
scene_embedding_map, scene_embedding = {}, []
if (settings.model.use_video):
scene_embedding_map, scene_embedding = data_utils.load_video_vec(settings.model.video_embedding_path)
settings.model.video_emb = np.array(scene_embedding)
settings.model.num_scene_vector = len(scene_embedding)
print ('Scene Embedding Loaded...')
if args.phase == 'train' or args.phase == 'deploy':
# Loading train data is needed for train, but also for deploy, namely if vocabulary doesn't exist yet:
train_data = None
if args.phase == 'train' or not os.path.exists(settings.data.vocabulary):
train_data = data_utils.load_data(settings.data.dataset, entity_name_to_idx, with_keys=True, logger=logger, use_video=settings.model.use_video)
# Load vocabulary (and extract from train_data if vocabulary doesn't exist yet)
vocabulary_idx_to_word, vocabulary_word_to_idx = data_utils.get_vocabulary(settings.data.vocabulary,
extract_from=train_data,
logger=logger)
# Avoid loading/generating google news embeddings in deploy phase:
if args.phase == 'deploy' and settings.model.token_emb == config_utils.data_paths["embeddings"]["google_news"]:
settings.model.token_emb = 300
# Appropriate embeddings will be loaded anyway from saved .pt model file.
# TODO: This won't generalize when using other embeddings.
# Load embeddings if needed:
if isinstance(settings.model.token_emb, str):
settings.model.token_emb = embedding_loader.load_word_embeddings(settings.model.token_emb,
settings.data.dataset, train_data, logger)
if isinstance(settings.model.speaker_emb, str):
settings.model.speaker_emb = embedding_loader.load_entity_embeddings(settings.model.speaker_emb,
settings.data.entity_map, logger)
# convenient to compute and store some dependent parameters:
settings.model.vocabulary_size = len(vocabulary_idx_to_word)
settings.model.num_entities = len(entity_idx_to_name)
if args.phase == 'train':
logger.save_config(settings.orig)
logger.say(output_utils.bcolors.BOLD + 'Training on ' + settings.data.dataset)
run_training(settings, train_data, vocabulary_idx_to_word, vocabulary_word_to_idx, logger, not args.no_cuda, scene_embedding_map,scene_emb_list=scene_embedding)
if args.phase == 'deploy':
logger.say(output_utils.bcolors.BOLD + 'Deploying ' + str(len(args.model)) + ' models (' + (
args.run_name if len(args.model) > 1 else args.model[0]) + ')...\n ...on ' + ('folds of ' if not args.no_cv else '') + args.deploy_data)
args.answer_file, with_keys = run_deploy(args.model, settings, args.deploy_data, vocabulary_idx_to_word, vocabulary_word_to_idx, entity_name_to_idx, args.answers_per_fold, args.no_cv, logger, not args.no_cuda, scene_embedding_map, scene_emb_list=scene_embedding)
# After deploying, evaluate (unless not desired or data does not contain reference keys):
if not args.no_eval:
if with_keys is True:
args.phase = 'evaluate'
else:
logger.shout('Warning: Model predictions will not be evaluated, since given data does not contain reference labels. ')
if args.phase == 'evaluate':
logger.say(output_utils.bcolors.BOLD + 'Evaluating ' + ('(not SemEval style) ' if args.no_semeval else '(SemEval style) ') + 'predictions of ' + args.answer_file)
run_evaluate(args.answer_file, args.deploy_data, entity_name_to_idx, entity_idx_to_name, args.no_semeval, logger)
def run_training(settings, data, vocabulary_idx_to_word, vocabulary_word_to_idx, logger, use_cuda, scene_embedding_key_to_id={}, scene_emb_list=[]):
reproduction_command = 'python main.py ' + '-c ' + os.path.join(logger.log_dir, logger.run_name + '.ini')
logger.shout(reproduction_command)
logger.log('# ' + reproduction_command)
logger.log('epoch\titeration\tfold\ttrain_loss\ttrain_acc\ttrain_macro_f1\ttrain_macro_f1_main\ttrain_total\tval_loss\tval_acc\tval_macro_f1\tval_macro_f1_main\tval_total\tmodel')
input_vecs, targets = data_utils.create_input_vectors(data, vocabulary_idx_to_word, vocabulary_word_to_idx, scene_embedding_key_to_id)
# Compute the class weights if necessary
if settings.training.class_weights:
class_weights = np.bincount(targets[targets != -1], minlength = settings.model.num_entities)
class_weights = 1.0 / (np.sqrt(class_weights) + 1e-6) # 1e-6 for numerical stability (though the inf values wouldn't be used anyway)
settings.training.class_weights = class_weights
else:
settings.training.class_weights = None
fold_indices = range(settings.data.folds)
if settings.data.folds > 1:
folds = data_utils.get_cv_folds(data, settings.data, logger)
else:
# No cross-validation:
train_sequence_bounds = data_utils.get_sequence_bounds(data, settings.data.level)
validation_sequence_bounds = []
for fold_idx in fold_indices:
# For bookkeeping (logging five folds in one file):
logger.fold_idx = fold_idx
# Select training and (if cross-validation) validation data:
if settings.data.folds > 1:
train_sequence_bounds = np.concatenate(tuple(folds[:fold_idx]+folds[fold_idx+1:]))
validation_sequence_bounds = folds[fold_idx]
# Initialise model
model = models.LSTM_basic(settings.model, padding_idx=data_utils.DUMMY_ENTITY_IDX)
if use_cuda:
model.cuda()
# Train the model
last_model, best_model = model_utils.train(model, input_vecs, targets,
train_sequence_bounds, validation_sequence_bounds, settings.training, settings.training.no_shuffle, logger, scene_emb_list=scene_emb_list)
# Save the best model through the logger
logger.save_model(best_model)
def run_deploy(model_path, settings, data_path, vocabulary_idx_to_word, vocabulary_word_to_idx, entity_name_to_idx, answers_per_fold, no_cv, logger, use_cuda, scene_embedding_key_to_id={}, scene_emb_list=[]):
data, keys_in_data = data_utils.load_data(data_path, entity_name_to_idx, logger=logger, use_video=settings.model.use_video)
input_vecs, targets = data_utils.create_input_vectors(data, vocabulary_idx_to_word,
vocabulary_word_to_idx, scene_embedding_key_to_id=scene_embedding_key_to_id)
# Set dropout probability to zero on deploy/test
settings.model.dropout_prob_video = 0.0
# Load all models from model_path:
model_list = []
for path in model_path:
print (path)
model_fold = models.LSTM_basic(settings.model, padding_idx=data_utils.DUMMY_ENTITY_IDX)
model_fold.load_state_dict(torch.load(path, map_location=lambda storage, loc: storage))
if use_cuda:
model_fold.cuda()
model_list.append(model_fold)
logger.whisper('Loaded model from ' + path)
if no_cv: # To deploy all models as ensemble to all the data
test_sequence_bounds = data_utils.get_sequence_bounds(data, settings.data.level)
collect_ensembles_preds = False # TODO @Future This may be useful at some point.
predictions_zipped, _ = model_utils.get_indexed_predictions_with_targets(
model_list, input_vecs, targets, test_sequence_bounds, use_cuda,
collect_ensembles_preds=collect_ensembles_preds, scene_emb_list=scene_emb_list)
# Write answers through logger
answers_path = logger.write_answers_csv(data_path, predictions_zipped, model_suffix="--ensemble", config=settings.orig)
# Optionally also per individual model (i.e., each model trained on one fold):
if answers_per_fold:
for i, model in enumerate(model_list):
predictions_zipped, _ = model_utils.get_indexed_predictions_with_targets(
model, input_vecs, targets, test_sequence_bounds, use_cuda, scene_emb_list=scene_emb_list)
logger.write_answers_csv(data_path, predictions_zipped, model_suffix='--fold'+str(i))
else: # To deploy per fold of the data
results = []
folds = data_utils.get_cv_folds(data, settings.data, logger)
for fold_idx in range(settings.data.folds):
# Obtain predictions for this fold:
predictions_zipped, _ = model_utils.get_indexed_predictions_with_targets(
model_list[fold_idx], input_vecs, targets, folds[fold_idx], use_cuda, scene_emb_list=scene_emb_list)
# Optionally write answers for this one fold
if answers_per_fold:
logger.write_answers_csv(settings.data.dataset + "--fold" + str(fold_idx), predictions_zipped,
model_suffix="--fold" + str(fold_idx), config=settings.orig)
# But also store them, to be merged and sorted later, for writing merged answers
results.extend(predictions_zipped)
# Write answers merged over all folds through logger
results.sort()
answers_path = logger.write_answers_csv(settings.data.dataset, results, model_suffix="--cv", config=settings.orig)
return answers_path, keys_in_data
def run_evaluate(answer_file, deploy_data, entity_name_to_idx, entity_idx_to_name, no_semeval, logger):
indices, predicted, targets = data_utils.read_answers_csv(answer_file, logger=logger)
evaluate_data = data_utils.load_data(deploy_data, entity_name_to_idx, with_keys=True, with_ling_info=True,
logger=logger)
# In SemEval, all entities that occurred fewer than 3 times were grouped together as 'other'.
# This can be turned off by command line argument --no_semeval .
target_freq = defaultdict(int)
if not no_semeval:
for entity_label in targets:
target_freq[entity_label] += 1
for i in range(len(targets)):
if target_freq[targets[i]] < 3:
targets[i] = data_utils.OTHER_ENTITY
if target_freq[predicted[i]] < 3:
predicted[i] = data_utils.OTHER_ENTITY
counts_entities, _ = data_utils.get_counts_entities(targets)
top_entities = [x[0] for x in counts_entities.most_common(200)]
confusion_mat = sklearn.metrics.confusion_matrix(targets, predicted, labels=top_entities)
top_entities_names = data_utils.transform_labels_into_names(top_entities, entity_idx_to_name)
confusion_mat = pd.DataFrame(confusion_mat, index=top_entities_names, columns=top_entities_names)
indices_by_type = data_utils.mask_ids_by_token_type(evaluate_data, indices=indices)
scores = {token_type: model_utils.get_scores(predicted, targets, restrict_indices=indices_by_type[token_type])
for token_type in indices_by_type.keys()}
# TODO @Future: Offload file naming, structure and writing etc. to logger.
output_file_scores = answer_file.strip('.csv') + '_scores.txt'
output_file_matrix = answer_file.strip('.csv') + '_matrix.csv'
with open(output_file_scores, 'w') as file:
for score_type in sorted(scores):
file.write(score_type.upper() + '\n')
for measure in sorted(scores[score_type]):
file.write(measure + ':\t' + str(scores[score_type][measure]) + '\n')
file.write('\n\n')
file.write(data_utils.data_summary(evaluate_data))
with open(output_file_matrix, 'w') as file:
confusion_mat.to_csv(file, sep='\t')
logger.whisper('Scores written to ' + output_file_scores)
logger.whisper('Confusion matrix written to ' + output_file_matrix)
def parse_args_and_settings():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--phase", default=None,
help="can be train, deploy (by default includes evaluate) or evaluate. Automatically inferred if not specified.")
# Only for training:
# TODO @Future Make parser give warnings when wrong combination of arguments is given (standard feature of argparse perhaps?)
parser.add_argument("-c", "--conf_file", default=None,
help="Path to config file including .ini; can be left None only in deploy/evaluation, in which case it is derived from model/answers path.",
metavar="FILE")
parser.add_argument("-r", "--random", action='store_true', # Note: also kinda used, but overwritten, during deploy/evaluate
help="To sample values randomly from intervals in config file.")
parser.add_argument("-d", "--subdir", default=None, # Note: also used, but overwritten, during deploy
help="(training phase) use /models/<subdir> for output; by default set to year_month.")
parser.add_argument("-n", "--run_name", default=None, # Note: also used, but overwritten, during deploy/evaluate
help="(training phase) by default set to time stamp; always automatically appended by randomly sampled params.")
# For deployment/evaluation:
parser.add_argument("-t", "--deploy_data", default=None,
help="Default is data on which the model was trained; can be 'train', 'test' or 'trial', abbreviations as defined in config_utils. During evaluation this can be omitted: it will be read from the predictions .csv file.")
parser.add_argument("-l", "--deploy_level", default=None,
help="Scene or episode; default is the level on which the model was trained. During evaluation this can be omitted: it will be read from the predictions .csv file.")
# Only for deployment
parser.add_argument("-m", "--model", default=None,
help="(deployment phase) path to model, with base name (though without .pt suffix); if fold number is included, only that fold is considered.")
parser.add_argument("--answers_per_fold", action='store_true',
help="To write an answers.txt file for each fold separately (in addition to their merger).")
parser.add_argument("--no_cv", action='store_true',
help="Option to prevent respecting cross-validation (which is done by default when deployed on training data).")
parser.add_argument("-s", "--no_eval", action='store_true',
help="If data includes keys, evaluation phase is run automatically after deployment; this option prevents that.")
# Only for evaluation
parser.add_argument("-a", "--answer_file", default=None,
help="Evaluates an answer file, outputting interesting statistics.")
parser.add_argument("--no_semeval", action='store_true',
help="To turn off the SemEval filter for evaluation (filter which groups infrequent (< 3) entities together as 'other').")
# Meta:
parser.add_argument("--no_cuda", action='store_true',
help="Forces not using cuda; otherwise cuda is used whenever available.")
parser.add_argument("-v", "--verbosity", type=int, default=3,
help="Sets verbosity regarding console output (default 3; lower to print less).")
parser.add_argument("-f", "--no_files", action='store_true',
help="Prevents generation of folders and files (log, model, answer).")
args = parser.parse_args()
# If phase is not specified, this can usually be inferred from other arguments:
if args.phase is None:
if args.model is not None:
args.phase = 'deploy'
elif args.answer_file is not None:
args.phase = 'evaluate'
else:
args.phase = 'train'
# Use CUDA only if available:
if not args.no_cuda and not torch.cuda.is_available:
print('WARNING: CUDA requested but unavailable; running on cpu instead.')
args.no_cuda = True
# Deploy either a single model or a set of models (of the same type).
# Also, from the model file arg.model also extract model_dir and run_name:
if args.phase == 'deploy':
if '.pt' in args.model:
# A single model file .pt was provided, so deploy only on that:
runs_path, args.run_name = os.path.split(args.model)
args.model_dir, args.subdir = os.path.split(runs_path)
args.run_name = args.run_name[:-3] # removes the .pt
if '--fold' in args.run_name:
args.run_name = args.run_name.split('--fold')[0]
args.model = [args.model]
else:
# model name doesn't contain .pt (i.e., either directory, or directory+run_name:
if os.path.isdir(args.model):
# model is a directory
runs_path = args.model
args.run_name = None # To be extracted below
else:
# model is not a directory, nor .pt; hence only run_name of model is given:
runs_path, args.run_name = os.path.split(args.model)
args.model_dir, args.subdir = os.path.split(runs_path)
# Get all model paths from directory (with run_name):
models = []
for file in os.listdir(runs_path):
if file.endswith(".pt"):
if args.run_name is None:
args.run_name = file[:-3] # removes the .pt
if '--fold' in args.run_name:
args.run_name = args.run_name.split('--fold')[0]
if file.startswith(args.run_name):
models.append(os.path.join(runs_path, file))
elif os.path.isdir(args.model):
print("ERROR: run_name could not be inferred; directory contains multiple runs.\n Rerun with more specific --model (i.e., including model file name, minus .pt and minus --fold#).")
quit()
args.model = sorted(models)
# When evaluating, obtain run name etcetera from the provided answers .csv file:
if args.phase == 'evaluate':
args.run_name = os.path.basename(args.answer_file)[:-4]
if args.run_name.endswith('--ensemble'):
args.run_name = args.run_name[:-10] # removes the --ensemble suffix
if '--fold' in args.run_name:
args.run_name = args.run_name.split('--fold')[0]
if '--cv' in args.run_name:
args.run_name = args.run_name.split('--cv')[0]
args.model_dir = None # This is kinda ugly.
# For train phase a config file is mandatory; otherwise it can be automatically obtained:
if args.conf_file is None:
if args.phase == 'train':
print('ERROR: training requires a config file (try including -c config.ini)')
quit()
elif args.phase == 'deploy':
args.conf_file = os.path.join(runs_path, args.run_name + '.ini')
elif args.phase == 'evaluate':
args.conf_file = os.path.join(os.path.dirname(args.answer_file), args.run_name + '.ini')
# Read the config file (either given as argument, or obtained from pre-trained model or its predictions file:
if args.phase == 'deploy' or args.phase == 'evaluate':
# Of course don't randomly sample when deploying or evaluating.
args.random = False
settings, fixed_params, sampled_params = config_utils.settings_from_config(args.conf_file, args.random)
# NOTE: Which params were fixed or sampled determines the subdir and run_name in case of training.
# If no level and data for deployment are given, these are taken from training data/level in config file
if args.phase == 'deploy':
args.deploy_level = args.deploy_level or settings.data.level
args.deploy_data = args.deploy_data or settings.data.dataset
if args.deploy_data in config_utils.data_paths:
args.deploy_data = config_utils.data_paths[args.deploy_data][args.deploy_level]
# For evaluate, if deploy_data is not provided, attempt to read it from the answer_file:
# (The alternative, of reading it from directory structure, seems too unsafe.)
if args.phase == 'evaluate' and args.deploy_data is None:
with open(args.answer_file) as file:
firstline = file.readline()
if firstline.startswith('#'):
args.deploy_data = firstline.strip('# \n')
# When deploying on a new dataset (not training data), cross-validation doesn't apply:
if args.deploy_data != settings.data.dataset:
args.no_cv = True
# When training, create runs dir, id and run name if none were given (mostly time stamps).
if args.phase == 'train':
args.model_dir = 'models' # Default for training output.
args.subdir = args.subdir or time.strftime("%Y_%m")
args.run_name = args.run_name or time.strftime("%Y_%m_%d_%H_%M_%S")
if not sampled_params:
args.run_name = 'fixed--' + args.run_name
else:
# TODO @Future: Automatic run naming can be considerably improved wrt. readability.
sampled_params_strings = sorted([k[0:3] + "--" + str(sampled_params[k])[0:5].replace(",", "-") for k in sampled_params])
args.run_name = '{0}--{1}'.format(args.run_name, "--".join(sampled_params_strings))
# Within the settings Namespace, which is subject to overwriting, make sure to include a backup,
# so that original settings can at any time be saved to a new config file.
settings.orig = copy.deepcopy(settings)
print ('--------------Setttings---------------------')
print ('[phase] ', args.phase)
print ('[deploy_data] ', args.deploy_data)
print ('[settings.data.datasets] ', settings.data.dataset)
print ('--------------------------------------------')
return args, settings
if __name__ == "__main__":
main()
| [
"argparse.ArgumentParser",
"data_utils.get_cv_folds",
"time.strftime",
"collections.defaultdict",
"torch.set_num_threads",
"data_utils.transform_labels_into_names",
"data_utils.get_counts_entities",
"numpy.sqrt",
"data_utils.load_video_vec",
"pandas.DataFrame",
"data_utils.get_vocabulary",
"em... | [((419, 444), 'output_utils.Logger', 'output_utils.Logger', (['args'], {}), '(args)\n', (438, 444), False, 'import output_utils\n'), ((531, 565), 'torch.set_num_threads', 'torch.set_num_threads', (['num_threads'], {}), '(num_threads)\n', (552, 565), False, 'import torch\n'), ((687, 739), 'data_utils.load_entity_map', 'data_utils.load_entity_map', (['settings.data.entity_map'], {}), '(settings.data.entity_map)\n', (713, 739), False, 'import data_utils\n'), ((5402, 5518), 'data_utils.create_input_vectors', 'data_utils.create_input_vectors', (['data', 'vocabulary_idx_to_word', 'vocabulary_word_to_idx', 'scene_embedding_key_to_id'], {}), '(data, vocabulary_idx_to_word,\n vocabulary_word_to_idx, scene_embedding_key_to_id)\n', (5433, 5518), False, 'import data_utils\n'), ((7451, 7557), 'data_utils.load_data', 'data_utils.load_data', (['data_path', 'entity_name_to_idx'], {'logger': 'logger', 'use_video': 'settings.model.use_video'}), '(data_path, entity_name_to_idx, logger=logger,\n use_video=settings.model.use_video)\n', (7471, 7557), False, 'import data_utils\n'), ((7580, 7727), 'data_utils.create_input_vectors', 'data_utils.create_input_vectors', (['data', 'vocabulary_idx_to_word', 'vocabulary_word_to_idx'], {'scene_embedding_key_to_id': 'scene_embedding_key_to_id'}), '(data, vocabulary_idx_to_word,\n vocabulary_word_to_idx, scene_embedding_key_to_id=scene_embedding_key_to_id\n )\n', (7611, 7727), False, 'import data_utils\n'), ((10754, 10809), 'data_utils.read_answers_csv', 'data_utils.read_answers_csv', (['answer_file'], {'logger': 'logger'}), '(answer_file, logger=logger)\n', (10781, 10809), False, 'import data_utils\n'), ((10830, 10939), 'data_utils.load_data', 'data_utils.load_data', (['deploy_data', 'entity_name_to_idx'], {'with_keys': '(True)', 'with_ling_info': '(True)', 'logger': 'logger'}), '(deploy_data, entity_name_to_idx, with_keys=True,\n with_ling_info=True, logger=logger)\n', (10850, 10939), False, 'import data_utils\n'), ((11163, 11179), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (11174, 11179), False, 'from collections import Counter, defaultdict\n'), ((11545, 11584), 'data_utils.get_counts_entities', 'data_utils.get_counts_entities', (['targets'], {}), '(targets)\n', (11575, 11584), False, 'import data_utils\n'), ((11772, 11844), 'data_utils.transform_labels_into_names', 'data_utils.transform_labels_into_names', (['top_entities', 'entity_idx_to_name'], {}), '(top_entities, entity_idx_to_name)\n', (11810, 11844), False, 'import data_utils\n'), ((11865, 11951), 'pandas.DataFrame', 'pd.DataFrame', (['confusion_mat'], {'index': 'top_entities_names', 'columns': 'top_entities_names'}), '(confusion_mat, index=top_entities_names, columns=\n top_entities_names)\n', (11877, 11951), True, 'import pandas as pd\n'), ((11970, 12035), 'data_utils.mask_ids_by_token_type', 'data_utils.mask_ids_by_token_type', (['evaluate_data'], {'indices': 'indices'}), '(evaluate_data, indices=indices)\n', (12003, 12035), False, 'import data_utils\n'), ((13070, 13095), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (13093, 13095), False, 'import argparse\n'), ((20706, 20768), 'config_utils.settings_from_config', 'config_utils.settings_from_config', (['args.conf_file', 'args.random'], {}), '(args.conf_file, args.random)\n', (20739, 20768), False, 'import config_utils\n'), ((22850, 22873), 'copy.deepcopy', 'copy.deepcopy', (['settings'], {}), '(settings)\n', (22863, 22873), False, 'import copy\n'), ((1022, 1084), 'data_utils.load_video_vec', 'data_utils.load_video_vec', (['settings.model.video_embedding_path'], {}), '(settings.model.video_embedding_path)\n', (1047, 1084), False, 'import data_utils\n'), ((1120, 1145), 'numpy.array', 'np.array', (['scene_embedding'], {}), '(scene_embedding)\n', (1128, 1145), True, 'import numpy as np\n'), ((1832, 1927), 'data_utils.get_vocabulary', 'data_utils.get_vocabulary', (['settings.data.vocabulary'], {'extract_from': 'train_data', 'logger': 'logger'}), '(settings.data.vocabulary, extract_from=train_data,\n logger=logger)\n', (1857, 1927), False, 'import data_utils\n'), ((5625, 5699), 'numpy.bincount', 'np.bincount', (['targets[targets != -1]'], {'minlength': 'settings.model.num_entities'}), '(targets[targets != -1], minlength=settings.model.num_entities)\n', (5636, 5699), True, 'import numpy as np\n'), ((6053, 6105), 'data_utils.get_cv_folds', 'data_utils.get_cv_folds', (['data', 'settings.data', 'logger'], {}), '(data, settings.data, logger)\n', (6076, 6105), False, 'import data_utils\n'), ((6179, 6236), 'data_utils.get_sequence_bounds', 'data_utils.get_sequence_bounds', (['data', 'settings.data.level'], {}), '(data, settings.data.level)\n', (6209, 6236), False, 'import data_utils\n'), ((6709, 6783), 'models.LSTM_basic', 'models.LSTM_basic', (['settings.model'], {'padding_idx': 'data_utils.DUMMY_ENTITY_IDX'}), '(settings.model, padding_idx=data_utils.DUMMY_ENTITY_IDX)\n', (6726, 6783), False, 'import models\n'), ((6890, 7083), 'model_utils.train', 'model_utils.train', (['model', 'input_vecs', 'targets', 'train_sequence_bounds', 'validation_sequence_bounds', 'settings.training', 'settings.training.no_shuffle', 'logger'], {'scene_emb_list': 'scene_emb_list'}), '(model, input_vecs, targets, train_sequence_bounds,\n validation_sequence_bounds, settings.training, settings.training.\n no_shuffle, logger, scene_emb_list=scene_emb_list)\n', (6907, 7083), False, 'import model_utils\n'), ((8027, 8101), 'models.LSTM_basic', 'models.LSTM_basic', (['settings.model'], {'padding_idx': 'data_utils.DUMMY_ENTITY_IDX'}), '(settings.model, padding_idx=data_utils.DUMMY_ENTITY_IDX)\n', (8044, 8101), False, 'import models\n'), ((8438, 8495), 'data_utils.get_sequence_bounds', 'data_utils.get_sequence_bounds', (['data', 'settings.data.level'], {}), '(data, settings.data.level)\n', (8468, 8495), False, 'import data_utils\n'), ((8623, 8825), 'model_utils.get_indexed_predictions_with_targets', 'model_utils.get_indexed_predictions_with_targets', (['model_list', 'input_vecs', 'targets', 'test_sequence_bounds', 'use_cuda'], {'collect_ensembles_preds': 'collect_ensembles_preds', 'scene_emb_list': 'scene_emb_list'}), '(model_list, input_vecs,\n targets, test_sequence_bounds, use_cuda, collect_ensembles_preds=\n collect_ensembles_preds, scene_emb_list=scene_emb_list)\n', (8671, 8825), False, 'import model_utils\n'), ((9564, 9616), 'data_utils.get_cv_folds', 'data_utils.get_cv_folds', (['data', 'settings.data', 'logger'], {}), '(data, settings.data, logger)\n', (9587, 9616), False, 'import data_utils\n'), ((12062, 12155), 'model_utils.get_scores', 'model_utils.get_scores', (['predicted', 'targets'], {'restrict_indices': 'indices_by_type[token_type]'}), '(predicted, targets, restrict_indices=indices_by_type\n [token_type])\n', (12084, 12155), False, 'import model_utils\n'), ((1555, 1690), 'data_utils.load_data', 'data_utils.load_data', (['settings.data.dataset', 'entity_name_to_idx'], {'with_keys': '(True)', 'logger': 'logger', 'use_video': 'settings.model.use_video'}), '(settings.data.dataset, entity_name_to_idx, with_keys=\n True, logger=logger, use_video=settings.model.use_video)\n', (1575, 1690), False, 'import data_utils\n'), ((2617, 2728), 'embedding_loader.load_word_embeddings', 'embedding_loader.load_word_embeddings', (['settings.model.token_emb', 'settings.data.dataset', 'train_data', 'logger'], {}), '(settings.model.token_emb, settings.\n data.dataset, train_data, logger)\n', (2654, 2728), False, 'import embedding_loader\n'), ((2898, 3003), 'embedding_loader.load_entity_embeddings', 'embedding_loader.load_entity_embeddings', (['settings.model.speaker_emb', 'settings.data.entity_map', 'logger'], {}), '(settings.model.speaker_emb,\n settings.data.entity_map, logger)\n', (2937, 3003), False, 'import embedding_loader\n'), ((8137, 8196), 'torch.load', 'torch.load', (['path'], {'map_location': '(lambda storage, loc: storage)'}), '(path, map_location=lambda storage, loc: storage)\n', (8147, 8196), False, 'import torch\n'), ((9754, 9912), 'model_utils.get_indexed_predictions_with_targets', 'model_utils.get_indexed_predictions_with_targets', (['model_list[fold_idx]', 'input_vecs', 'targets', 'folds[fold_idx]', 'use_cuda'], {'scene_emb_list': 'scene_emb_list'}), '(model_list[fold_idx],\n input_vecs, targets, folds[fold_idx], use_cuda, scene_emb_list=\n scene_emb_list)\n', (9802, 9912), False, 'import model_utils\n'), ((12755, 12793), 'data_utils.data_summary', 'data_utils.data_summary', (['evaluate_data'], {}), '(evaluate_data)\n', (12778, 12793), False, 'import data_utils\n'), ((22126, 22148), 'time.strftime', 'time.strftime', (['"""%Y_%m"""'], {}), "('%Y_%m')\n", (22139, 22148), False, 'import time\n'), ((22190, 22224), 'time.strftime', 'time.strftime', (['"""%Y_%m_%d_%H_%M_%S"""'], {}), "('%Y_%m_%d_%H_%M_%S')\n", (22203, 22224), False, 'import time\n'), ((5733, 5755), 'numpy.sqrt', 'np.sqrt', (['class_weights'], {}), '(class_weights)\n', (5740, 5755), True, 'import numpy as np\n'), ((9218, 9361), 'model_utils.get_indexed_predictions_with_targets', 'model_utils.get_indexed_predictions_with_targets', (['model', 'input_vecs', 'targets', 'test_sequence_bounds', 'use_cuda'], {'scene_emb_list': 'scene_emb_list'}), '(model, input_vecs, targets,\n test_sequence_bounds, use_cuda, scene_emb_list=scene_emb_list)\n', (9266, 9361), False, 'import model_utils\n')] |
import matplotlib.pyplot as plt
from scipy import signal
import numpy as np
# Number of neighbours 0 1 2 3 4 5 6 7 8
RULE_OF_SURVIVAL = np.array([0, 0, 1, 1, 0, 0, 0, 0, 0])
RULE_OF_CREATION = np.array([0, 0, 0, 1, 0, 0, 0, 0, 0])
# Map resolution
MAP_SIZE = 100
# Map creation
gof_map = np.random.choice([0, 1], size=(MAP_SIZE, MAP_SIZE))
# Initialize plotting
fig, ax = plt.subplots()
img = ax.imshow(gof_map)
plt.show(block=False)
# Helper function for map drawing
def draw_map(gof_map):
img.set_data(gof_map)
fig.canvas.draw()
fig.canvas.flush_events()
# This filter helps to count rank of life
gof_filter = np.array([
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
])
while True:
# Generate rank for each cell using image filtering
rank_map = signal.convolve2d(gof_map, gof_filter, boundary='wrap', mode='same')
# Find out which cells matches with the rules
gof_map = RULE_OF_CREATION[rank_map] | gof_map & RULE_OF_SURVIVAL[rank_map]
# Refresh the map
draw_map(gof_map)
| [
"matplotlib.pyplot.show",
"scipy.signal.convolve2d",
"numpy.array",
"numpy.random.choice",
"matplotlib.pyplot.subplots"
] | [((151, 188), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 0, 0, 0, 0, 0]'], {}), '([0, 0, 1, 1, 0, 0, 0, 0, 0])\n', (159, 188), True, 'import numpy as np\n'), ((208, 245), 'numpy.array', 'np.array', (['[0, 0, 0, 1, 0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 1, 0, 0, 0, 0, 0])\n', (216, 245), True, 'import numpy as np\n'), ((305, 356), 'numpy.random.choice', 'np.random.choice', (['[0, 1]'], {'size': '(MAP_SIZE, MAP_SIZE)'}), '([0, 1], size=(MAP_SIZE, MAP_SIZE))\n', (321, 356), True, 'import numpy as np\n'), ((390, 404), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (402, 404), True, 'import matplotlib.pyplot as plt\n'), ((430, 451), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (438, 451), True, 'import matplotlib.pyplot as plt\n'), ((644, 687), 'numpy.array', 'np.array', (['[[1, 1, 1], [1, 0, 1], [1, 1, 1]]'], {}), '([[1, 1, 1], [1, 0, 1], [1, 1, 1]])\n', (652, 687), True, 'import numpy as np\n'), ((786, 854), 'scipy.signal.convolve2d', 'signal.convolve2d', (['gof_map', 'gof_filter'], {'boundary': '"""wrap"""', 'mode': '"""same"""'}), "(gof_map, gof_filter, boundary='wrap', mode='same')\n", (803, 854), False, 'from scipy import signal\n')] |
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler
def get_next_batch(i_count):
while True:
if i_count >= max_batch - 1:
i_count = int(i_count % max_batch)
a_x = test_X[i_count * batch_size:(i_count + 1) * batch_size]
if a_x.shape[0] != 100:
i_count += 1
continue
a_y = np.zeros([batch_size, num_classes])
for index, j in enumerate(train_y[i_count * batch_size:(i_count + 1) * batch_size]):
if j == 0:
a_y[index, :] = [1, 0]
elif j == 1:
a_y[index, :] = [0, 1]
return a_x, a_y
def get_next_batch_test():
a_x = train_X
a_y = np.zeros([train_X.shape[0], num_classes])
for index, j in enumerate(test_y):
if j == 0:
a_y[index, :] = [1, 0]
else:
a_y[index, :] = [0, 1]
return a_x, a_y
def mmscaler(data):
# feature_range 映射到指定范围
maxmin = MinMaxScaler(feature_range=[0, 1])
data = maxmin.fit_transform(data)
return data
df = pd.read_csv("123456.csv")
# 分割数据
train, test = train_test_split(df, test_size=.3, random_state=12)
print(train.shape, test.shape)
train_X = train.drop('loan_status', axis=1)
train_X = mmscaler(train_X) # 归一化
train_y = train['loan_status'] # 归一化
test_X = test.drop('loan_status', axis=1)
test_X = mmscaler(test_X)
test_y = test['loan_status']
num_classes = 2 # 输出大小
input_size = 65 # 输入大小
hidden_units_size = 30 # 隐藏层节点数量
batch_size = 100
training_iterations = 3000 # 1000000
rows_number = train_X.shape[0]
max_batch = int(rows_number / batch_size) # 301
X = tf.placeholder(tf.float32, shape=[None, input_size])
Y = tf.placeholder(tf.float32, shape=[None, num_classes])
W1 = tf.Variable(tf.random_normal([input_size, hidden_units_size], stddev=0.1))
B1 = tf.Variable(tf.constant(0.1), [hidden_units_size])
hidden_opt_1 = tf.matmul(X, W1) + B1 # 输入层到隐藏层正向传播
W2 = tf.Variable(tf.random_normal([hidden_units_size, num_classes], stddev=0.1))
B2 = tf.Variable(tf.constant(0.1), [num_classes])
hidden_opt_2 = tf.nn.relu(hidden_opt_1) # 激活函数,用于计算节点输出值
final_opt = tf.matmul(hidden_opt_2, W2) + B2 # 隐藏层到输出层正向传播
# 对输出层计算交叉熵损失
loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=Y, logits=final_opt))
# 梯度下降算法,这里使用了反向传播算法用于修改权重,减小损失
opt = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)
# 计算准确率
origin_y = tf.argmax(Y, axis=1)
predict_y = tf.argmax(final_opt, axis=1)
correct_prediction = tf.equal(origin_y, predict_y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
batch_input_test, batch_labels_test = get_next_batch_test()
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(training_iterations):
# 初始化变量
batch_input, batch_labels = get_next_batch(i)
# 训练
_, cost_ = sess.run([opt, loss], feed_dict={X: batch_input, Y: batch_labels})
if i % 1000 == 0:
accuracy_test = sess.run(accuracy, feed_dict={X: batch_input_test, Y: batch_labels_test})
print("acc_test: {}".format(accuracy_test))
| [
"tensorflow.nn.relu",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"tensorflow.argmax",
"sklearn.preprocessing.MinMaxScaler",
"numpy.zeros",
"tensorflow.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.constant",
"tensorflow.Session",
"tensorflow.global_variables_initializer",
... | [((1171, 1196), 'pandas.read_csv', 'pd.read_csv', (['"""123456.csv"""'], {}), "('123456.csv')\n", (1182, 1196), True, 'import pandas as pd\n'), ((1218, 1270), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df'], {'test_size': '(0.3)', 'random_state': '(12)'}), '(df, test_size=0.3, random_state=12)\n', (1234, 1270), False, 'from sklearn.model_selection import train_test_split\n'), ((1741, 1793), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, input_size]'}), '(tf.float32, shape=[None, input_size])\n', (1755, 1793), True, 'import tensorflow as tf\n'), ((1798, 1851), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, num_classes]'}), '(tf.float32, shape=[None, num_classes])\n', (1812, 1851), True, 'import tensorflow as tf\n'), ((2188, 2212), 'tensorflow.nn.relu', 'tf.nn.relu', (['hidden_opt_1'], {}), '(hidden_opt_1)\n', (2198, 2212), True, 'import tensorflow as tf\n'), ((2516, 2536), 'tensorflow.argmax', 'tf.argmax', (['Y'], {'axis': '(1)'}), '(Y, axis=1)\n', (2525, 2536), True, 'import tensorflow as tf\n'), ((2549, 2577), 'tensorflow.argmax', 'tf.argmax', (['final_opt'], {'axis': '(1)'}), '(final_opt, axis=1)\n', (2558, 2577), True, 'import tensorflow as tf\n'), ((2600, 2629), 'tensorflow.equal', 'tf.equal', (['origin_y', 'predict_y'], {}), '(origin_y, predict_y)\n', (2608, 2629), True, 'import tensorflow as tf\n'), ((808, 849), 'numpy.zeros', 'np.zeros', (['[train_X.shape[0], num_classes]'], {}), '([train_X.shape[0], num_classes])\n', (816, 849), True, 'import numpy as np\n'), ((1075, 1109), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '[0, 1]'}), '(feature_range=[0, 1])\n', (1087, 1109), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), ((1870, 1931), 'tensorflow.random_normal', 'tf.random_normal', (['[input_size, hidden_units_size]'], {'stddev': '(0.1)'}), '([input_size, hidden_units_size], stddev=0.1)\n', (1886, 1931), True, 'import tensorflow as tf\n'), ((1950, 1966), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {}), '(0.1)\n', (1961, 1966), True, 'import tensorflow as tf\n'), ((2004, 2020), 'tensorflow.matmul', 'tf.matmul', (['X', 'W1'], {}), '(X, W1)\n', (2013, 2020), True, 'import tensorflow as tf\n'), ((2059, 2121), 'tensorflow.random_normal', 'tf.random_normal', (['[hidden_units_size, num_classes]'], {'stddev': '(0.1)'}), '([hidden_units_size, num_classes], stddev=0.1)\n', (2075, 2121), True, 'import tensorflow as tf\n'), ((2140, 2156), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {}), '(0.1)\n', (2151, 2156), True, 'import tensorflow as tf\n'), ((2244, 2271), 'tensorflow.matmul', 'tf.matmul', (['hidden_opt_2', 'W2'], {}), '(hidden_opt_2, W2)\n', (2253, 2271), True, 'import tensorflow as tf\n'), ((2329, 2396), 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', ([], {'labels': 'Y', 'logits': 'final_opt'}), '(labels=Y, logits=final_opt)\n', (2368, 2396), True, 'import tensorflow as tf\n'), ((2656, 2695), 'tensorflow.cast', 'tf.cast', (['correct_prediction', 'tf.float32'], {}), '(correct_prediction, tf.float32)\n', (2663, 2695), True, 'import tensorflow as tf\n'), ((2763, 2775), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2773, 2775), True, 'import tensorflow as tf\n'), ((2796, 2829), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2827, 2829), True, 'import tensorflow as tf\n'), ((472, 507), 'numpy.zeros', 'np.zeros', (['[batch_size, num_classes]'], {}), '([batch_size, num_classes])\n', (480, 507), True, 'import numpy as np\n'), ((2436, 2480), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': '(0.0001)'}), '(learning_rate=0.0001)\n', (2458, 2480), True, 'import tensorflow as tf\n')] |
#!/usr/bin/env python
"""
psource.py
Routines for dealing with point source files in ROMS
Author: <NAME> <<EMAIL>>
Copyright (c) 2019, <NAME>, all rights reserved.
Created: 10 January 2019
"""
import seapy.roms.ncgen
import numpy as np
import urllib.request as urllib
import json
import datetime
discharge_url = 'https://waterdata.usgs.gov/nwisweb/get_ratings?file_type=exsa&site_no='
river_url = 'https://waterservices.usgs.gov/nwis/iv/?format=json'
ft3m3 = 1 / (3.28**3)
def create(filename, river, s_rho=None, cdl=None):
"""
Construct a point source file with all of the point sources configured.
Input
-----
filename : string
Output filename
river : array,
array of dictionaries of rivers with the following information that
defines a point source:
The x and y values on the grid for where the point source is,
the direction of the point source (0 for xi or 1 for eta),
an identification number (any choice),
optional flag (1=temp, 2=salt, 3=temp+salt, 4=temp+salt+sed,
5=temp+salt+sed+bio),
and an array of values for the vertical shape (a value for each s-level)
that sum to 1.
{ "x":grid_x,
"y":grid_y,
"direction":0 or 1,
"id":value,
"flag":[1,2,3,4,or 5], [optional]
"vshape":[vals] } [optional]
s_rho : int, optional
Number of s-levels in the point source file (should match the grid).
If not specified, it will derive it from the vshape parameter
cdl : string, optional,
Name of CDL file to use
Output
------
nc : netCDF4 id
If successful, returns the netcdf id for writing
"""
river = np.asarray(river)
s_rho = len(river[0]['vshape']) if s_rho is None else s_rho
# Create an empty, new file
nc = seapy.roms.ncgen.create_psource(
filename, nriver=len(river), s_rho=s_rho, clobber=True, cdl=cdl)
# Go through each river and set up the basics
for i, r in enumerate(river):
nc.variables['river'][i] = int(r['id'])
nc.variables['river_Xposition'][i] = int(r['x'])
nc.variables['river_Eposition'][i] = int(r['y'])
nc.variables['river_direction'][i] = int(r['direction'])
try:
nc.variables['river_flag'][i] = int(r['flag'])
except:
nc.variables['river_flag'][i] = 0
try:
vshape = np.asarray(r['vshape'][:, np.newaxis])
nc.variables['river_Vshape'][:, i] = vshape
except Exception as err:
print("Using default shape")
vshape = np.ones((s_rho, 1)) / s_rho
nc.variables['river_Vshape'][:, i] = vshape
return nc
def stage2discharge(gage, usgs_id):
'''
Function to convert stage data to discharge using usgs reference table
Input
-------
gage : masked array,
array of stage data to be converted
usgs_id : int,
8 digit identifier for river on usgs
Output
---------
flux : masked array,
discharge data in cubic feet
'''
import urllib.request as urllib
# Load lookup table
url = discharge_url + usgs_id
stage = []
discharge = []
header = 0
for line in urllib.urlopen(url):
if not line.startswith(b'#'):
if header < 2:
header += 1
else:
a = line.split(b'\t')
stage.append(float(line.split(b'\t')[0]))
discharge.append(float(line.split(b'\t')[2]))
stage = np.asarray(stage).astype(float)
discharge = np.asarray(discharge).astype(float)
# Convert data
flux = np.ma.masked_array(np.zeros(len(gage)), mask=gage.mask)
for i, f in enumerate(gage):
if f:
flux[i] = discharge[(np.abs(stage - f)).argmin()]
return flux
def get_usgs_transport(usgs_id, times=1, source='discharge'):
'''
Function to get flux data from usgs and convert to cubic meters
Input
-------
usgs_id : int,
8 digit identifier for river on usgs
times : datetime array,
list of values to get usgs data for. Values from USGS
will be linearly interpolated onto these times.
source : string,
set to 'discharge' or 'stage' to access corresponding
parameter. Stage data is then converted to discharge
using stage2discharge function.
Output
---------
dates : list,
list of datetimes associated with the flux data
flux : array,
flux data in cubic meters per second
'''
# Build url
siteurl = '&sites=' + usgs_id
if source == 'discharge':
sourceurl = '¶meterCd=00060'
elif source == 'stage':
sourceurl = '¶meterCd=00065'
else:
print('Incorrect source type specified')
return None
timeurl = '&startDT=%s&endDT=%s' % (times[0].strftime(
'%Y-%m-%d'), times[-1].strftime('%Y-%m-%d'))
url = river_url + siteurl + sourceurl + timeurl
# Access url
print('Accessing ' + url)
x = json.loads(urllib.urlopen(url).read().decode('utf-8'))
dates = []
flux = []
if x['value']['timeSeries']:
for l in x['value']['timeSeries'][0]['values'][0]['value']:
dates.append(datetime.datetime.strptime(
l['dateTime'][:16], '%Y-%m-%dT%H:%M'))
flux.append(l['value'])
flux = np.ma.masked_values(
np.ma.masked_array(flux).astype(np.float), -999999)
try:
if source == 'stage':
flux = stage2discharge(flux, usgs_id)
# Interpolate the data for consistency
flux *= ft3m3
return np.interp(seapy.date2day(times),
seapy.date2day(np.array(dates)[
~np.ma.getmaskarray(flux)]),
flux.compressed(), left=flux.min(), right=flux.min())
except ValueError:
print('No valid data found')
return None
else:
print('Cannot process file from url')
return None
| [
"numpy.abs",
"numpy.asarray",
"numpy.ma.getmaskarray",
"urllib.request.urlopen",
"numpy.ones",
"datetime.datetime.strptime",
"numpy.array",
"numpy.ma.masked_array"
] | [((1856, 1873), 'numpy.asarray', 'np.asarray', (['river'], {}), '(river)\n', (1866, 1873), True, 'import numpy as np\n'), ((3412, 3431), 'urllib.request.urlopen', 'urllib.urlopen', (['url'], {}), '(url)\n', (3426, 3431), True, 'import urllib.request as urllib\n'), ((2566, 2604), 'numpy.asarray', 'np.asarray', (["r['vshape'][:, np.newaxis]"], {}), "(r['vshape'][:, np.newaxis])\n", (2576, 2604), True, 'import numpy as np\n'), ((3714, 3731), 'numpy.asarray', 'np.asarray', (['stage'], {}), '(stage)\n', (3724, 3731), True, 'import numpy as np\n'), ((3762, 3783), 'numpy.asarray', 'np.asarray', (['discharge'], {}), '(discharge)\n', (3772, 3783), True, 'import numpy as np\n'), ((5506, 5570), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (["l['dateTime'][:16]", '"""%Y-%m-%dT%H:%M"""'], {}), "(l['dateTime'][:16], '%Y-%m-%dT%H:%M')\n", (5532, 5570), False, 'import datetime\n'), ((2756, 2775), 'numpy.ones', 'np.ones', (['(s_rho, 1)'], {}), '((s_rho, 1))\n', (2763, 2775), True, 'import numpy as np\n'), ((5673, 5697), 'numpy.ma.masked_array', 'np.ma.masked_array', (['flux'], {}), '(flux)\n', (5691, 5697), True, 'import numpy as np\n'), ((3965, 3982), 'numpy.abs', 'np.abs', (['(stage - f)'], {}), '(stage - f)\n', (3971, 3982), True, 'import numpy as np\n'), ((5307, 5326), 'urllib.request.urlopen', 'urllib.urlopen', (['url'], {}), '(url)\n', (5321, 5326), True, 'import urllib.request as urllib\n'), ((5999, 6014), 'numpy.array', 'np.array', (['dates'], {}), '(dates)\n', (6007, 6014), True, 'import numpy as np\n'), ((6061, 6085), 'numpy.ma.getmaskarray', 'np.ma.getmaskarray', (['flux'], {}), '(flux)\n', (6079, 6085), True, 'import numpy as np\n')] |
#%%
# constants - enoshima (sample)
MESHES = ['523973', '523974']
GPKG = 'enoshima_shape.gpkg'
DEM = 'enoshima_dem.vrt'
# DEM = 'dem_10m.vrt'
TILES = [
(15, 29079, 12944), # 片瀬海岸
(15, 29080, 12944), # 龍口寺
(15, 29081, 12944), # 津西
(15, 29079, 12945), # 江の島参道
(15, 29080, 12945), # 湘南港
(15, 29081, 12945), # 鎌倉高校前
(15, 29079, 12946), # 江の島岩屋
(15, 29080, 12946), # 江の島灯台
]
DST_DIR = 'dst/gsi_enoshima_5m_unleveled'
#%%
# setup
import os
from glob import glob
os.remove(GPKG) if os.path.exists(GPKG) else None
for layer in ['RdCL', 'BldA']:
for mesh in MESHES:
for path in glob(f'../../data/gsi_nummap/{mesh}/*-*-*-{layer}-*-000?.shp'):
os.system(f"ogr2ogr -update -append -f GPKG -nln {layer} -oo ENCODING=CP932 {GPKG} {path}")
os.system(f'gdalbuildvrt {DEM} ../../data/dem05s/52397[34].tif')
# os.system(f'gdalbuildvrt ~dem_10m.vrt ../../data/dem10s/*.tif')
#%%
# build obj from gsi data
import os
from landtile import mesh as lmesh
from landtile import roads_weaver as rw
from landtile import buildings_extender as be
from landtile import dem_digger as dd
from landtile import terrain_creator as tc
from landtile import roads_builder as rb
from landtile import buildings_builder as bb
os.system(f'cp landtile/common.mtl .')
for tz, tx, ty in TILES:
tname = f'{tz}_{tx}_{ty}'
road_df = rw.weave(GPKG, tz, tx, ty)
bldg_df = be.extend(GPKG, tz, tx, ty)
# dem = dd.dig(DEM, tz, tx, ty, road_df, bldg_df)
dem = dd.undig(DEM, tz, tx, ty) # 整地しない場合
tc.create(dem, tz, tx, ty, f'{tname}_terrain')
tc.make_image('../../data/maptiles/', tz, tx, ty, 1).save(f'{tname}_terrain.png')
meshes, mats, props = rb.build(dem, road_df)
lmesh.write_obj(meshes, mats, f'{tname}_roads.obj')
meshes, mats, props = bb.build(dem, bldg_df)
lmesh.write_obj(meshes, mats, f'{tname}_bldgs.obj')
#%%
# convert obj to gltf
import os
from glob import glob
os.system(f'mkdir -p {DST_DIR}/gltfs')
for f in glob('*_*_*_*.obj'):
basename = os.path.splitext(os.path.basename(f))[0]
os.system(f'./node_modules/.bin/obj2gltf -i {f} -o {DST_DIR}/gltfs/{basename}.gltf')
#%%
# output tiles.json (for threejs viewer)
import json
from pyproj import Transformer
import numpy as np
from landtile.tile import num2lonlat
t = Transformer.from_crs('epsg:4612', 'epsg:2451', always_xy=True)
xys = np.array([t.transform(*num2lonlat(*tile)) for tile in TILES])
nxys = xys - np.mean(xys, axis=0)
locs = [[f'{z}_{x}_{y}', [xx, yy]]for (z, x, y), (xx, yy) in zip(TILES, nxys.tolist())]
json.dump(locs, open(f'{DST_DIR}/gltfs/tiles.json', 'w'), indent=2)
#%%
# build cesium 3dtiles
import json
import tileset_json_builder as tjb
for kind in ['terrain', 'roads', 'bldgs']:
os.system(f'mkdir -p {DST_DIR}/{kind}')
for tz, tx, ty in TILES:
tn = f'{tz}_{tx}_{ty}'
os.system(f'./node_modules/.bin/obj23dtiles -i {tn}_{kind}.obj -o {DST_DIR}/{kind}/{tn}.b3dm --b3dm')
os.system(f'for nm in {DST_DIR}/{kind}/*.b3dm; do mv $nm ${{nm%_{kind}.b3dm}}.b3dm; done')
json.dump(tjb.build(TILES), open(
f'{DST_DIR}/{kind}/_tileset.json', 'w'), indent=2)
#%%
# sweep obj & mtl files
os.system(f'mkdir -p {DST_DIR}/objs')
os.system(f'mv *_*_*_*.* {DST_DIR}/objs')
| [
"landtile.roads_builder.build",
"landtile.buildings_extender.extend",
"os.remove",
"landtile.terrain_creator.create",
"landtile.mesh.write_obj",
"os.path.basename",
"landtile.dem_digger.undig",
"landtile.tile.num2lonlat",
"os.path.exists",
"os.system",
"landtile.buildings_builder.build",
"nump... | [((792, 856), 'os.system', 'os.system', (['f"""gdalbuildvrt {DEM} ../../data/dem05s/52397[34].tif"""'], {}), "(f'gdalbuildvrt {DEM} ../../data/dem05s/52397[34].tif')\n", (801, 856), False, 'import os\n'), ((1253, 1291), 'os.system', 'os.system', (['f"""cp landtile/common.mtl ."""'], {}), "(f'cp landtile/common.mtl .')\n", (1262, 1291), False, 'import os\n'), ((1940, 1978), 'os.system', 'os.system', (['f"""mkdir -p {DST_DIR}/gltfs"""'], {}), "(f'mkdir -p {DST_DIR}/gltfs')\n", (1949, 1978), False, 'import os\n'), ((1988, 2007), 'glob.glob', 'glob', (['"""*_*_*_*.obj"""'], {}), "('*_*_*_*.obj')\n", (1992, 2007), False, 'from glob import glob\n'), ((2304, 2366), 'pyproj.Transformer.from_crs', 'Transformer.from_crs', (['"""epsg:4612"""', '"""epsg:2451"""'], {'always_xy': '(True)'}), "('epsg:4612', 'epsg:2451', always_xy=True)\n", (2324, 2366), False, 'from pyproj import Transformer\n'), ((3180, 3217), 'os.system', 'os.system', (['f"""mkdir -p {DST_DIR}/objs"""'], {}), "(f'mkdir -p {DST_DIR}/objs')\n", (3189, 3217), False, 'import os\n'), ((3218, 3259), 'os.system', 'os.system', (['f"""mv *_*_*_*.* {DST_DIR}/objs"""'], {}), "(f'mv *_*_*_*.* {DST_DIR}/objs')\n", (3227, 3259), False, 'import os\n'), ((517, 537), 'os.path.exists', 'os.path.exists', (['GPKG'], {}), '(GPKG)\n', (531, 537), False, 'import os\n'), ((498, 513), 'os.remove', 'os.remove', (['GPKG'], {}), '(GPKG)\n', (507, 513), False, 'import os\n'), ((1362, 1388), 'landtile.roads_weaver.weave', 'rw.weave', (['GPKG', 'tz', 'tx', 'ty'], {}), '(GPKG, tz, tx, ty)\n', (1370, 1388), True, 'from landtile import roads_weaver as rw\n'), ((1403, 1430), 'landtile.buildings_extender.extend', 'be.extend', (['GPKG', 'tz', 'tx', 'ty'], {}), '(GPKG, tz, tx, ty)\n', (1412, 1430), True, 'from landtile import buildings_extender as be\n'), ((1495, 1520), 'landtile.dem_digger.undig', 'dd.undig', (['DEM', 'tz', 'tx', 'ty'], {}), '(DEM, tz, tx, ty)\n', (1503, 1520), True, 'from landtile import dem_digger as dd\n'), ((1536, 1582), 'landtile.terrain_creator.create', 'tc.create', (['dem', 'tz', 'tx', 'ty', 'f"""{tname}_terrain"""'], {}), "(dem, tz, tx, ty, f'{tname}_terrain')\n", (1545, 1582), True, 'from landtile import terrain_creator as tc\n'), ((1696, 1718), 'landtile.roads_builder.build', 'rb.build', (['dem', 'road_df'], {}), '(dem, road_df)\n', (1704, 1718), True, 'from landtile import roads_builder as rb\n'), ((1723, 1774), 'landtile.mesh.write_obj', 'lmesh.write_obj', (['meshes', 'mats', 'f"""{tname}_roads.obj"""'], {}), "(meshes, mats, f'{tname}_roads.obj')\n", (1738, 1774), True, 'from landtile import mesh as lmesh\n'), ((1801, 1823), 'landtile.buildings_builder.build', 'bb.build', (['dem', 'bldg_df'], {}), '(dem, bldg_df)\n', (1809, 1823), True, 'from landtile import buildings_builder as bb\n'), ((1828, 1879), 'landtile.mesh.write_obj', 'lmesh.write_obj', (['meshes', 'mats', 'f"""{tname}_bldgs.obj"""'], {}), "(meshes, mats, f'{tname}_bldgs.obj')\n", (1843, 1879), True, 'from landtile import mesh as lmesh\n'), ((2069, 2158), 'os.system', 'os.system', (['f"""./node_modules/.bin/obj2gltf -i {f} -o {DST_DIR}/gltfs/{basename}.gltf"""'], {}), "(\n f'./node_modules/.bin/obj2gltf -i {f} -o {DST_DIR}/gltfs/{basename}.gltf')\n", (2078, 2158), False, 'import os\n'), ((2448, 2468), 'numpy.mean', 'np.mean', (['xys'], {'axis': '(0)'}), '(xys, axis=0)\n', (2455, 2468), True, 'import numpy as np\n'), ((2748, 2787), 'os.system', 'os.system', (['f"""mkdir -p {DST_DIR}/{kind}"""'], {}), "(f'mkdir -p {DST_DIR}/{kind}')\n", (2757, 2787), False, 'import os\n'), ((2962, 3062), 'os.system', 'os.system', (['f"""for nm in {DST_DIR}/{kind}/*.b3dm; do mv $nm ${{nm%_{kind}.b3dm}}.b3dm; done"""'], {}), "(\n f'for nm in {DST_DIR}/{kind}/*.b3dm; do mv $nm ${{nm%_{kind}.b3dm}}.b3dm; done'\n )\n", (2971, 3062), False, 'import os\n'), ((623, 685), 'glob.glob', 'glob', (['f"""../../data/gsi_nummap/{mesh}/*-*-*-{layer}-*-000?.shp"""'], {}), "(f'../../data/gsi_nummap/{mesh}/*-*-*-{layer}-*-000?.shp')\n", (627, 685), False, 'from glob import glob\n'), ((2856, 2967), 'os.system', 'os.system', (['f"""./node_modules/.bin/obj23dtiles -i {tn}_{kind}.obj -o {DST_DIR}/{kind}/{tn}.b3dm --b3dm"""'], {}), "(\n f'./node_modules/.bin/obj23dtiles -i {tn}_{kind}.obj -o {DST_DIR}/{kind}/{tn}.b3dm --b3dm'\n )\n", (2865, 2967), False, 'import os\n'), ((3068, 3084), 'tileset_json_builder.build', 'tjb.build', (['TILES'], {}), '(TILES)\n', (3077, 3084), True, 'import tileset_json_builder as tjb\n'), ((699, 800), 'os.system', 'os.system', (['f"""ogr2ogr -update -append -f GPKG -nln {layer} -oo ENCODING=CP932 {GPKG} {path}"""'], {}), "(\n f'ogr2ogr -update -append -f GPKG -nln {layer} -oo ENCODING=CP932 {GPKG} {path}'\n )\n", (708, 800), False, 'import os\n'), ((1587, 1639), 'landtile.terrain_creator.make_image', 'tc.make_image', (['"""../../data/maptiles/"""', 'tz', 'tx', 'ty', '(1)'], {}), "('../../data/maptiles/', tz, tx, ty, 1)\n", (1600, 1639), True, 'from landtile import terrain_creator as tc\n'), ((2041, 2060), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (2057, 2060), False, 'import os\n'), ((2396, 2413), 'landtile.tile.num2lonlat', 'num2lonlat', (['*tile'], {}), '(*tile)\n', (2406, 2413), False, 'from landtile.tile import num2lonlat\n')] |
"""Module that implement an iterator version of the sampler."""
from os.path import join
from random import shuffle
import numpy as np
import soundfile as sf
from audio_loader.samplers.decorator import SamplerBase
class WindowedSegmentSampler(SamplerBase):
"""Create samples with associated groundtruth.
No cache involved.
"""
def __init__(self, feature_processors, groundtruth, seg_size, overlap=0.5, supervised=True,
output_filepath=False, activity_detection=None):
"""Initialize the sampler.
Parameters
----------
feature_processors: list
List of feature processors.
groundtruth:
Contains methods allowing to get all sets + groundtruth.
seg_size: integer (greather than 0)
Size of segments in number of samples.
overlap: float between 0. and 1.
Overlap of the segments.
supervised: boolean
Return the groundthruth alongside with each sample.
activity_detection: audio_loader.actvity_detection
Activity detection used to separate the signals, if equals to None the whole file is selected.
"""
super().__init__(feature_processors, groundtruth,
supervised=supervised, output_filepath=output_filepath,
activity_detection=activity_detection)
if self.fe_win_size > seg_size:
raise Exception("seg_size should be larger or equel to feature extractors win_size")
self.n_frames_select = 1 + int((seg_size - self.fe_win_size) / self.fe_hop_size)
self.n_frames_hop = int(self.n_frames_select * (1 - overlap))
if self.n_frames_hop < 1:
raise Exception(
f"seg_size {seg_size} is too small for the chosen extractor(s)")
self.seg_size = self.fe_win_size + (self.n_frames_select-1) * self.fe_hop_size
self.hop_seg_size = self.fe_win_size + (self.n_frames_hop-1) * self.fe_hop_size
def get_samples_from(self, selected_set, randomize_files=False, file_list=None):
"""Iterator other the ground truth.
Parameters
----------
selected_set: str or list
possible keys are: 'train', 'validation', 'test'
if it is a list, the list represent filpaths
"""
if isinstance(selected_set, list):
file_list = selected_set
else:
file_list = self.get_file_list(selected_set)
if randomize_files:
file_list = file_list.copy() # the shuffle should not impact the initial list
shuffle(file_list)
for filepath in file_list:
if not isinstance(selected_set, list):
filepath = join(self.groundtruth.data_folderpath, filepath)
signal, sr = sf.read(filepath,
always_2d=True, dtype='float32')
x = None
for feature_processor in self.feature_processors:
if x is None:
x = feature_processor.process(signal, sr)
else:
x = np.concatenate((x, feature_processor.process(signal, sr)), axis=2)
if self.supervised:
y = self.groundtruth.get_gt_from_sample(filepath,
self.fe_win_size,
self.fe_hop_size,
padding=self.fe_padding)
if self.activity_detection is not None:
fe_filter = self.activity_detection.process(signal)
x = x[fe_filter]
if len(x.shape) != 3:
x = x.reshape(1, *x.shape)
# start FIXME y does not have a channel dimension
fe_filter = fe_filter.all(axis=0)
# end FIXME
if self.supervised:
y = y[fe_filter]
nb_win = x.shape[1]
n_frames = 1 + int((nb_win - self.n_frames_select) / self.n_frames_hop)
for i in range(0, n_frames):
i = i*self.n_frames_hop
x_selected = x[:, i:i+self.n_frames_select, :]
if self.supervised:
y_selected = y[i:i+self.n_frames_select, :]
sample = (x_selected, np.sum(y_selected, axis=0)/self.n_frames_select)
else:
sample = tuple(x_selected)
if self.output_filepath:
yield (sample, filepath)
else:
yield sample
| [
"random.shuffle",
"soundfile.read",
"os.path.join",
"numpy.sum"
] | [((2633, 2651), 'random.shuffle', 'shuffle', (['file_list'], {}), '(file_list)\n', (2640, 2651), False, 'from random import shuffle\n'), ((2841, 2891), 'soundfile.read', 'sf.read', (['filepath'], {'always_2d': '(True)', 'dtype': '"""float32"""'}), "(filepath, always_2d=True, dtype='float32')\n", (2848, 2891), True, 'import soundfile as sf\n'), ((2766, 2814), 'os.path.join', 'join', (['self.groundtruth.data_folderpath', 'filepath'], {}), '(self.groundtruth.data_folderpath, filepath)\n', (2770, 2814), False, 'from os.path import join\n'), ((4402, 4428), 'numpy.sum', 'np.sum', (['y_selected'], {'axis': '(0)'}), '(y_selected, axis=0)\n', (4408, 4428), True, 'import numpy as np\n')] |
from __future__ import absolute_import
import numpy as np
import scipy
import torch
from pysurvival.models import BaseModel
from pysurvival import utils, HAS_GPU
from pysurvival.utils import optimization as opt
from pysurvival.utils import neural_networks as nn
class BaseParametricModel(BaseModel):
""" Base class for all the Parametric estimators:
---------------------------------------------
Parametric models are special cases of the Cox proportional hazard
model where is is assumed that the baseline hazard has a specific
parametric form.
The BaseParametricModel object provides the necessary framework to use
the properties of parametric models. It should not be used on its own.
Parameters
----------
* bins: int (default=100)
Number of subdivisions of the time axis
* auto_scaler: boolean (default=True)
Determines whether a sklearn scaler should be automatically applied
"""
def __init__(self, bins=100, auto_scaler=True):
# Saving the attributes
self.loss_values = []
self.bins = bins
# Initializing the elements from BaseModel
super(BaseParametricModel, self).__init__(auto_scaler)
def get_hazard_survival(self, model, x, t):
raise NotImplementedError()
def get_times(self, T, is_min_time_zero=True, extra_pct_time=0.1):
""" Building the time axis (self.times) as well as the time intervals
( all the [ t(k-1), t(k) ) in the time axis.
"""
# Setting the min_time and max_time
max_time = max(T)
if is_min_time_zero:
min_time = 0.
else:
min_time = min(T)
# Setting optional extra percentage time
if 0. <= extra_pct_time <= 1.:
p = extra_pct_time
else:
raise Exception("extra_pct_time has to be between [0, 1].")
# Building time points and time buckets
self.times = np.linspace(min_time, max_time * (1. + p), self.bins)
self.get_time_buckets()
self.nb_times = len(self.time_buckets)
def loss_function(self, model, X, T, E, l2_reg):
""" Computes the loss function of any Parametric models.
All the operations have been vectorized to ensure optimal speed
"""
# Adapting the optimization for the use of GPU
# if HAS_GPU:
# X = X.cuda(async=True)
# T = T.cuda(async=True)
# E = E.cuda(async=True)
# model = model.cuda()
# Hazard & Survival calculations
hazard, Survival = self.get_hazard_survival(model, X, T)
# Loss function calculations
hazard = torch.max(hazard, torch.FloatTensor([1e-6]))
Survival = torch.max(Survival, torch.FloatTensor([1e-6]))
loss = - torch.sum(E * torch.log(hazard) + torch.log(Survival))
# Adding the regularized loss
for w in model.parameters():
loss += l2_reg * torch.sum(w * w) / 2.
return loss
def fit(self, X, T, E, init_method='glorot_uniform', optimizer='adam',
lr=1e-4, num_epochs=1000, l2_reg=1e-2, verbose=True,
is_min_time_zero=True, extra_pct_time=0.1):
"""
Fit the estimator based on the given parameters.
Parameters:
-----------
* `X` : **array-like**, *shape=(n_samples, n_features)* --
The input samples.
* `T` : **array-like** --
The target values describing when the event of interest or censoring
occurred.
* `E` : **array-like** --
The values that indicate if the event of interest occurred i.e.:
E[i]=1 corresponds to an event, and E[i] = 0 means censoring,
for all i.
* `init_method` : **str** *(default = 'glorot_uniform')* --
Initialization method to use. Here are the possible options:
* `glorot_uniform`: Glorot/Xavier uniform initializer
* `he_uniform`: He uniform variance scaling initializer
* `uniform`: Initializing tensors with uniform (-1, 1) distribution
* `glorot_normal`: Glorot normal initializer,
* `he_normal`: He normal initializer.
* `normal`: Initializing tensors with standard normal distribution
* `ones`: Initializing tensors to 1
* `zeros`: Initializing tensors to 0
* `orthogonal`: Initializing tensors with a orthogonal matrix,
* `optimizer`: **str** *(default = 'adam')* --
iterative method for optimizing a differentiable objective function.
Here are the possible options:
- `adadelta`
- `adagrad`
- `adam`
- `adamax`
- `rmsprop`
- `sparseadam`
- `sgd`
* `lr`: **float** *(default=1e-4)* --
learning rate used in the optimization
* `num_epochs`: **int** *(default=1000)* --
The number of iterations in the optimization
* `l2_reg`: **float** *(default=1e-4)* --
L2 regularization parameter for the model coefficients
* `verbose`: **bool** *(default=True)* --
Whether or not producing detailed logging about the modeling
* `extra_pct_time`: **float** *(default=0.1)* --
Providing an extra fraction of time in the time axis
* `is_min_time_zero`: **bool** *(default=True)* --
Whether the the time axis starts at 0
Returns:
--------
* self : object
Example:
--------
#### 1 - Importing packages
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from pysurvival.models.simulations import SimulationModel
from pysurvival.models.parametric import GompertzModel
from pysurvival.utils.metrics import concordance_index
from pysurvival.utils.display import integrated_brier_score
#%matplotlib inline # To use with Jupyter notebooks
#### 2 - Generating the dataset from a Gompertz parametric model
# Initializing the simulation model
sim = SimulationModel( survival_distribution = 'Gompertz',
risk_type = 'linear',
censored_parameter = 10.0,
alpha = .01, beta = 3.0 )
# Generating N random samples
N = 1000
dataset = sim.generate_data(num_samples = N, num_features = 3)
# Showing a few data-points
time_column = 'time'
event_column = 'event'
dataset.head(2)
#### 3 - Creating the modeling dataset
# Defining the features
features = sim.features
# Building training and testing sets #
index_train, index_test = train_test_split( range(N), test_size = 0.2)
data_train = dataset.loc[index_train].reset_index( drop = True )
data_test = dataset.loc[index_test].reset_index( drop = True )
# Creating the X, T and E input
X_train, X_test = data_train[features], data_test[features]
T_train, T_test = data_train['time'].values, data_test['time'].values
E_train, E_test = data_train['event'].values, data_test['event'].values
#### 4 - Creating an instance of the Gompertz model and fitting the data
# Building the model
gomp_model = GompertzModel()
gomp_model.fit(X_train, T_train, E_train, lr=1e-2, init_method='zeros',
optimizer ='adam', l2_reg = 1e-3, num_epochs=2000)
#### 5 - Cross Validation / Model Performances
c_index = concordance_index(gomp_model, X_test, T_test, E_test) #0.8
print('C-index: {:.2f}'.format(c_index))
ibs = integrated_brier_score(gomp_model, X_test, T_test, E_test,
t_max=30, figure_size=(20, 6.5) )
"""
# Checking data format (i.e.: transforming into numpy array)
X, T, E = utils.check_data(X, T, E)
T = np.maximum(T, 1e-6)
self.get_times(T, is_min_time_zero, extra_pct_time)
# Extracting data parameters
nb_units, self.num_vars = X.shape
input_shape = self.num_vars
# Scaling data
if self.auto_scaler:
X = self.scaler.fit_transform(X)
# Does the model need a parameter called Beta
is_beta_used = True
init_alpha = 1.
if self.name == 'ExponentialModel':
is_beta_used = False
if self.name == 'GompertzModel':
init_alpha = 1000.
# Initializing the model
model = nn.ParametricNet(input_shape, init_method, init_alpha,
is_beta_used)
# Trasnforming the inputs into tensors
X = torch.FloatTensor(X)
T = torch.FloatTensor(T.reshape(-1, 1))
E = torch.FloatTensor(E.reshape(-1, 1))
# Performing order 1 optimization
model, loss_values = opt.optimize(self.loss_function, model, optimizer,
lr, num_epochs, verbose, X=X, T=T, E=E, l2_reg=l2_reg)
# Saving attributes
self.model = model.eval()
self.loss_values = loss_values
# Calculating the AIC
self.aic = 2 * self.loss_values[-1]
self.aic -= 2 * (self.num_vars + 1 + is_beta_used * 1. - 1)
return self
def _predict(self, x, t=None, **kwargs):
"""
Predicting the hazard, density and survival functions
Arguments:
----------
* x: pd.Dataframe or np.ndarray or list
x is the testing dataset containing the features
x should not be standardized before, the model
will take care of it
* t: float (default=None)
Time at which hazard, density and survival functions
should be calculated. If None, the method returns
the functions for all times t.
"""
# Scaling the data
if self.auto_scaler:
if x.ndim == 1:
x = self.scaler.transform(x.reshape(1, -1))
elif x.ndim == 2:
x = self.scaler.transform(x)
else:
# Ensuring x has 2 dimensions
if x.ndim == 1:
x = np.reshape(x, (1, -1))
# Transforming into pytorch objects
x = torch.FloatTensor(x)
times = torch.FloatTensor(self.times.flatten())
# Calculating hazard, density, Survival
hazard, Survival = self.get_hazard_survival(self.model, x, times)
density = hazard * Survival
# Transforming into numpy objects
hazard = hazard.data.numpy()
density = density.data.numpy()
Survival = Survival.data.numpy()
# Returning the full functions of just one time point
if t is None:
return hazard, density, Survival
else:
min_abs_value = [abs(a_j_1 - t) for (a_j_1, a_j) in self.time_buckets]
index = np.argmin(min_abs_value)
return hazard[:, index], density[:, index], Survival[:, index]
class ExponentialModel(BaseParametricModel):
"""
ExponentialModel:
-----------------
The exponential distribution is the simplest and most
important distribution in survival studies. Being independent
of prior information, it is known as a "lack of
memory" distribution requiring that the present age of the
living organism does not influence its future survival.
(Application of Parametric Models to a Survival Analysis of
Hemodialysis Patients)
"""
def get_hazard_survival(self, model, x, t):
""" Computing the hazard and Survival functions. """
# Computing the score
score = model(x).reshape(-1, 1)
# Computing hazard and Survival
hazard = score
Survival = torch.exp(-hazard * t)
return hazard, Survival
class WeibullModel(BaseParametricModel):
"""
WeibullModel:
-------------
The Weibull distribution is a generalized form of the exponential
distribution and is de facto more flexible than the exponential model.
It is a two-parameter model (alpha and beta):
* alpha is the location parameter
* beta is the shape parameter
"""
def get_hazard_survival(self, model, x, t):
""" Computing the hazard and Survival functions. """
# Computing the score
score = model(x).reshape(-1, 1)
# Extracting beta
beta = list(model.parameters())[-1]
# Computing hazard and Survival
hazard = beta * score * torch.pow(t, beta - 1)
Survival = torch.exp(- score * torch.pow(t, beta))
return hazard, Survival
class GompertzModel(BaseParametricModel):
"""
GompertzModel:
--------------
The Gompertz distribution is a continuous probability distribution,
that has an exponentially increasing failure rate, and is often
applied to analyze survival data.
"""
def get_hazard_survival(self, model, x, t):
""" Computing the hazard and Survival functions. """
# Computing the score
score = model(x).reshape(-1, 1)
# Extracting beta
beta = list(model.parameters())[-1]
# Computing hazard and Survival
hazard = score * torch.exp(beta * t)
Survival = torch.exp(-score / beta * (torch.exp(beta * t) - 1))
return hazard, Survival
class LogLogisticModel(BaseParametricModel):
"""
LogLogisticModel:
----------------
As the name suggests, the log-logistic distribution is the distribution
of a variable whose logarithm has the logistic distribution.
The log-logistic distribution is often used to model random lifetimes.
(http://www.randomservices.org/random/special/LogLogistic.html)
"""
def get_hazard_survival(self, model, x, t):
""" Computing the hazard and Survival functions. """
# Computing the score
score = model(x).reshape(-1, 1)
# Extracting beta
beta = list(model.parameters())[-1]
# Computing hazard and Survival
hazard = score * beta * torch.pow(t, beta - 1)
hazard = hazard / (1 + score * torch.pow(t, beta))
Survival = 1. / (1. + torch.pow(score * t, beta))
return hazard, Survival
class LogNormalModel(BaseParametricModel):
"""
LogNormalModel:
---------------
The lognormal distribution is used to model continuous random quantities
when the distribution is believed to be skewed, such as lifetime variables
(http://www.randomservices.org/random/special/LogNormal.html)
"""
def get_hazard_survival(self, model, x, t):
""" Computing the hazard and Survival functions. """
# Computing the score
score = model(x).reshape(-1, 1)
# Extracting beta
beta = list(model.parameters())[-1]
# Initializing the Normal distribution
from torch.distributions.normal import Normal
m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
# Computing hazard and Survival
hazard = (torch.log(t) - torch.log(score)) / (np.sqrt(2) * beta)
Survival = 1. - m.cdf((torch.log(t) - torch.log(score)) / (np.sqrt(2) * beta))
hazard = hazard * (torch.log(t) - torch.log(score)) / (np.sqrt(2) * beta)
hazard = torch.exp(-hazard / 2.)
hazard = hazard / (np.sqrt(2 * np.pi) * Survival * (t * beta))
hazard = torch.max(hazard, torch.FloatTensor([1e-6]))
Survival = torch.max(Survival, torch.FloatTensor([1e-6]))
return hazard, Survival
| [
"pysurvival.utils.check_data",
"numpy.maximum",
"torch.FloatTensor",
"numpy.argmin",
"pysurvival.utils.neural_networks.ParametricNet",
"torch.exp",
"torch.pow",
"numpy.reshape",
"numpy.linspace",
"pysurvival.utils.optimization.optimize",
"torch.sum",
"torch.log",
"torch.tensor",
"numpy.sqr... | [((2026, 2080), 'numpy.linspace', 'np.linspace', (['min_time', '(max_time * (1.0 + p))', 'self.bins'], {}), '(min_time, max_time * (1.0 + p), self.bins)\n', (2037, 2080), True, 'import numpy as np\n'), ((8167, 8192), 'pysurvival.utils.check_data', 'utils.check_data', (['X', 'T', 'E'], {}), '(X, T, E)\n', (8183, 8192), False, 'from pysurvival import utils, HAS_GPU\n'), ((8205, 8225), 'numpy.maximum', 'np.maximum', (['T', '(1e-06)'], {}), '(T, 1e-06)\n', (8215, 8225), True, 'import numpy as np\n'), ((8810, 8878), 'pysurvival.utils.neural_networks.ParametricNet', 'nn.ParametricNet', (['input_shape', 'init_method', 'init_alpha', 'is_beta_used'], {}), '(input_shape, init_method, init_alpha, is_beta_used)\n', (8826, 8878), True, 'from pysurvival.utils import neural_networks as nn\n'), ((8972, 8992), 'torch.FloatTensor', 'torch.FloatTensor', (['X'], {}), '(X)\n', (8989, 8992), False, 'import torch\n'), ((9161, 9270), 'pysurvival.utils.optimization.optimize', 'opt.optimize', (['self.loss_function', 'model', 'optimizer', 'lr', 'num_epochs', 'verbose'], {'X': 'X', 'T': 'T', 'E': 'E', 'l2_reg': 'l2_reg'}), '(self.loss_function, model, optimizer, lr, num_epochs, verbose,\n X=X, T=T, E=E, l2_reg=l2_reg)\n', (9173, 9270), True, 'from pysurvival.utils import optimization as opt\n'), ((10598, 10618), 'torch.FloatTensor', 'torch.FloatTensor', (['x'], {}), '(x)\n', (10615, 10618), False, 'import torch\n'), ((12112, 12134), 'torch.exp', 'torch.exp', (['(-hazard * t)'], {}), '(-hazard * t)\n', (12121, 12134), False, 'import torch\n'), ((15662, 15686), 'torch.exp', 'torch.exp', (['(-hazard / 2.0)'], {}), '(-hazard / 2.0)\n', (15671, 15686), False, 'import torch\n'), ((2774, 2800), 'torch.FloatTensor', 'torch.FloatTensor', (['[1e-06]'], {}), '([1e-06])\n', (2791, 2800), False, 'import torch\n'), ((2840, 2866), 'torch.FloatTensor', 'torch.FloatTensor', (['[1e-06]'], {}), '([1e-06])\n', (2857, 2866), False, 'import torch\n'), ((11241, 11265), 'numpy.argmin', 'np.argmin', (['min_abs_value'], {}), '(min_abs_value)\n', (11250, 11265), True, 'import numpy as np\n'), ((12870, 12892), 'torch.pow', 'torch.pow', (['t', '(beta - 1)'], {}), '(t, beta - 1)\n', (12879, 12892), False, 'import torch\n'), ((13588, 13607), 'torch.exp', 'torch.exp', (['(beta * t)'], {}), '(beta * t)\n', (13597, 13607), False, 'import torch\n'), ((14440, 14462), 'torch.pow', 'torch.pow', (['t', '(beta - 1)'], {}), '(t, beta - 1)\n', (14449, 14462), False, 'import torch\n'), ((15320, 15339), 'torch.tensor', 'torch.tensor', (['[0.0]'], {}), '([0.0])\n', (15332, 15339), False, 'import torch\n'), ((15341, 15360), 'torch.tensor', 'torch.tensor', (['[1.0]'], {}), '([1.0])\n', (15353, 15360), False, 'import torch\n'), ((15793, 15819), 'torch.FloatTensor', 'torch.FloatTensor', (['[1e-06]'], {}), '([1e-06])\n', (15810, 15819), False, 'import torch\n'), ((15859, 15885), 'torch.FloatTensor', 'torch.FloatTensor', (['[1e-06]'], {}), '([1e-06])\n', (15876, 15885), False, 'import torch\n'), ((10518, 10540), 'numpy.reshape', 'np.reshape', (['x', '(1, -1)'], {}), '(x, (1, -1))\n', (10528, 10540), True, 'import numpy as np\n'), ((12932, 12950), 'torch.pow', 'torch.pow', (['t', 'beta'], {}), '(t, beta)\n', (12941, 12950), False, 'import torch\n'), ((14552, 14578), 'torch.pow', 'torch.pow', (['(score * t)', 'beta'], {}), '(score * t, beta)\n', (14561, 14578), False, 'import torch\n'), ((15421, 15433), 'torch.log', 'torch.log', (['t'], {}), '(t)\n', (15430, 15433), False, 'import torch\n'), ((15436, 15452), 'torch.log', 'torch.log', (['score'], {}), '(score)\n', (15445, 15452), False, 'import torch\n'), ((15457, 15467), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15464, 15467), True, 'import numpy as np\n'), ((15626, 15636), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15633, 15636), True, 'import numpy as np\n'), ((2918, 2937), 'torch.log', 'torch.log', (['Survival'], {}), '(Survival)\n', (2927, 2937), False, 'import torch\n'), ((3044, 3060), 'torch.sum', 'torch.sum', (['(w * w)'], {}), '(w * w)\n', (3053, 3060), False, 'import torch\n'), ((13654, 13673), 'torch.exp', 'torch.exp', (['(beta * t)'], {}), '(beta * t)\n', (13663, 13673), False, 'import torch\n'), ((14502, 14520), 'torch.pow', 'torch.pow', (['t', 'beta'], {}), '(t, beta)\n', (14511, 14520), False, 'import torch\n'), ((15590, 15602), 'torch.log', 'torch.log', (['t'], {}), '(t)\n', (15599, 15602), False, 'import torch\n'), ((15605, 15621), 'torch.log', 'torch.log', (['score'], {}), '(score)\n', (15614, 15621), False, 'import torch\n'), ((15713, 15731), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (15720, 15731), True, 'import numpy as np\n'), ((2898, 2915), 'torch.log', 'torch.log', (['hazard'], {}), '(hazard)\n', (2907, 2915), False, 'import torch\n'), ((15507, 15519), 'torch.log', 'torch.log', (['t'], {}), '(t)\n', (15516, 15519), False, 'import torch\n'), ((15522, 15538), 'torch.log', 'torch.log', (['score'], {}), '(score)\n', (15531, 15538), False, 'import torch\n'), ((15543, 15553), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (15550, 15553), True, 'import numpy as np\n')] |
import math
import sys, os
#import .base
from .base.pygamewrapper import PyGameWrapper
import pygame
from pygame.constants import K_w, K_s
from .utils.vec2d import vec2d
class Block(pygame.sprite.Sprite):
def __init__(self, pos_init, speed, SCREEN_WIDTH, SCREEN_HEIGHT):
pygame.sprite.Sprite.__init__(self)
self.pos = vec2d(pos_init)
self.width = int(SCREEN_WIDTH * 0.07)
self.height = int(SCREEN_HEIGHT * 0.1)
self.speed = speed
self.SCREEN_WIDTH = SCREEN_WIDTH
self.SCREEN_HEIGHT = SCREEN_HEIGHT
image = pygame.Surface((self.width, self.height))
image.fill((0, 0, 0, 0))
image.set_colorkey((0, 0, 0))
pygame.draw.rect(
image,
(120, 240, 80),
(0, 0, self.width, self.height),
0
)
self.image = image
self.rect = self.image.get_rect()
self.rect.center = pos_init
def update(self, dt):
self.pos.x -= self.speed * dt
self.rect.center = (self.pos.x, self.pos.y)
class HelicopterPlayer(pygame.sprite.Sprite):
def __init__(self, speed, SCREEN_WIDTH, SCREEN_HEIGHT, _asset_dir):
pygame.sprite.Sprite.__init__(self)
pos_init = (int(SCREEN_WIDTH * 0.35), SCREEN_HEIGHT / 2)
self.pos = vec2d(pos_init)
self.speed = speed
self.climb_speed = speed * -0.875 # -0.0175
self.fall_speed = speed * 0.09 # 0.0019
self.momentum = 0
self.width = SCREEN_WIDTH * 0.1
self.height = SCREEN_HEIGHT * 0.05
heli_sprite_path = os.path.join(_asset_dir, "heli.png")
self.image = pygame.image.load(heli_sprite_path).convert_alpha()
self.image = pygame.transform.scale(self.image, (int(self.width), int(self.height)))
#image = pygame.Surface((self.width, self.height))
#image.fill((0, 0, 0, 0))
#image.set_colorkey((0, 0, 0))
#pygame.draw.rect(
# image,
# (255, 255, 255),
# (0, 0, self.width, self.height),
# 0
#)
#self.image = image
self.rect = self.image.get_rect()
self.rect.center = pos_init
def update(self, is_climbing, dt):
self.momentum += (self.climb_speed if is_climbing else self.fall_speed) * dt
self.momentum *= 0.99
self.pos.y += self.momentum
self.rect.center = (self.pos.x, self.pos.y)
class Terrain(pygame.sprite.Sprite):
def __init__(self, pos_init, speed, SCREEN_WIDTH, SCREEN_HEIGHT):
pygame.sprite.Sprite.__init__(self)
self.pos = vec2d(pos_init)
self.speed = speed
self.width = int(SCREEN_WIDTH * 0.1)
image = pygame.Surface((self.width, SCREEN_HEIGHT * 1.5))
image.fill((0, 0, 0, 0))
image.set_colorkey((0, 0, 0))
color = (120, 240, 80)
# top rect
pygame.draw.rect(
image,
color,
(0, 0, self.width, SCREEN_HEIGHT * 0.5),
0
)
# bot rect
pygame.draw.rect(
image,
color,
(0, SCREEN_HEIGHT * 1.05, self.width, SCREEN_HEIGHT * 0.5),
0
)
self.image = image
self.rect = self.image.get_rect()
self.rect.center = pos_init
def update(self, dt):
self.pos.x -= self.speed * dt
self.rect.center = (self.pos.x, self.pos.y)
class Pixelcopter(PyGameWrapper):
"""
Parameters
----------
width : int
Screen width.
height : int
Screen height, recommended to be same dimension as width.
"""
def __init__(self, width=48, height=48):
actions = {
"up": K_w
}
PyGameWrapper.__init__(self, width, height, actions=actions)
self.is_climbing = False
self.speed = 0.0004 * width
self._dir_ = os.path.dirname(os.path.abspath(__file__))
self._asset_dir = os.path.join(self._dir_, "assets/")
def _handle_player_events(self):
self.is_climbing = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
key = event.key
if key == self.actions['up']:
self.is_climbing = True
def getGameState(self):
"""
Gets a non-visual state representation of the game.
Returns
-------
dict
* player y position.
* player velocity.
* player distance to floor.
* player distance to ceiling.
* next block x distance to player.
* next blocks top y location,
* next blocks bottom y location.
See code for structure.
"""
min_dist = 999
min_block = None
for b in self.block_group: # Groups do not return in order
dist_to = b.pos.x - self.player.pos.x
if dist_to > 0 and dist_to < min_dist:
min_block = b
min_dist = dist_to
current_terrain = pygame.sprite.spritecollide(
self.player, self.terrain_group, False)[0]
state = {
"player_y": self.player.pos.y,
"player_vel": self.player.momentum,
"player_dist_to_ceil": self.player.pos.y - (current_terrain.pos.y - self.height * 0.25),
"player_dist_to_floor": (current_terrain.pos.y + self.height * 0.25) - self.player.pos.y,
"next_gate_dist_to_player": min_dist,
"next_gate_block_top": min_block.pos.y,
"next_gate_block_bottom": min_block.pos.y + min_block.height
}
return state
def getScreenDims(self):
return self.screen_dim
def getActions(self):
return self.actions.values()
def getScore(self):
return self.score
def game_over(self):
return self.lives <= 0.0
def init(self):
self.score = 0.0
self.lives = 1.0
self.player = HelicopterPlayer(
self.speed,
self.width,
self.height,
self._asset_dir
)
self.player_group = pygame.sprite.Group()
self.player_group.add(self.player)
self.block_group = pygame.sprite.Group()
self._add_blocks()
self.terrain_group = pygame.sprite.Group()
self._add_terrain(0, self.width * 4)
def _add_terrain(self, start, end):
w = int(self.width * 0.1)
# each block takes up 10 units.
steps = range(start + int(w / 2), end + int(w / 2), w)
y_jitter = []
freq = 4.5 / self.width + self.rng.uniform(-0.01, 0.01)
for step in steps:
jitter = (self.height * 0.125) * \
math.sin(freq * step + self.rng.uniform(0.0, 0.5))
y_jitter.append(jitter)
y_pos = [int((self.height / 2.0) + y_jit) for y_jit in y_jitter]
for i in range(0, len(steps)):
self.terrain_group.add(Terrain(
(steps[i], y_pos[i]),
self.speed,
self.width,
self.height
)
)
def _add_blocks(self):
x_pos = self.rng.randint(self.width, int(self.width * 1.5))
y_pos = self.rng.randint(
int(self.height * 0.25),
int(self.height * 0.75)
)
self.block_group.add(
Block(
(x_pos, y_pos),
self.speed,
self.width,
self.height
)
)
def reset(self):
self.init()
def step(self, dt):
self.screen.fill((0, 0, 0))
self._handle_player_events()
self.score += self.rewards["tick"]
self.player.update(self.is_climbing, dt)
self.block_group.update(dt)
self.terrain_group.update(dt)
hits = pygame.sprite.spritecollide(
self.player, self.block_group, False)
for creep in hits:
self.lives -= 1
hits = pygame.sprite.spritecollide(
self.player, self.terrain_group, False)
for t in hits:
if self.player.pos.y - self.player.height <= t.pos.y - self.height * 0.25:
self.lives -= 1
if self.player.pos.y >= t.pos.y + self.height * 0.25:
self.lives -= 1
for b in self.block_group:
if b.pos.x <= self.player.pos.x and len(self.block_group) == 1:
self.score += self.rewards["positive"]
self._add_blocks()
if b.pos.x <= -b.width:
b.kill()
for t in self.terrain_group:
if t.pos.x <= -t.width:
self.score += self.rewards["positive"]
t.kill()
if self.player.pos.y < self.height * 0.125: # its above
self.lives -= 1
if self.player.pos.y > self.height * 0.875: # its below the lowest possible block
self.lives -= 1
if len(self.terrain_group) <= (
10 + 3): # 10% per terrain, offset of ~2 with 1 extra
self._add_terrain(self.width, self.width * 5)
if self.lives <= 0.0:
self.score += self.rewards["loss"]
self.player_group.draw(self.screen)
self.block_group.draw(self.screen)
self.terrain_group.draw(self.screen)
if __name__ == "__main__":
import numpy as np
pygame.init()
game = Pixelcopter(width=256, height=256)
game.screen = pygame.display.set_mode(game.getScreenDims(), 0, 32)
game.clock = pygame.time.Clock()
game.rng = np.random.RandomState(24)
game.init()
while True:
if game.game_over():
game.reset()
dt = game.clock.tick_busy_loop(30)
game.step(dt)
pygame.display.update()
| [
"pygame.quit",
"os.path.abspath",
"pygame.Surface",
"pygame.draw.rect",
"pygame.event.get",
"numpy.random.RandomState",
"pygame.init",
"pygame.sprite.Group",
"pygame.display.update",
"pygame.sprite.Sprite.__init__",
"pygame.sprite.spritecollide",
"pygame.image.load",
"pygame.time.Clock",
"... | [((9529, 9542), 'pygame.init', 'pygame.init', ([], {}), '()\n', (9540, 9542), False, 'import pygame\n'), ((9677, 9696), 'pygame.time.Clock', 'pygame.time.Clock', ([], {}), '()\n', (9694, 9696), False, 'import pygame\n'), ((9712, 9737), 'numpy.random.RandomState', 'np.random.RandomState', (['(24)'], {}), '(24)\n', (9733, 9737), True, 'import numpy as np\n'), ((288, 323), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (317, 323), False, 'import pygame\n'), ((583, 624), 'pygame.Surface', 'pygame.Surface', (['(self.width, self.height)'], {}), '((self.width, self.height))\n', (597, 624), False, 'import pygame\n'), ((705, 780), 'pygame.draw.rect', 'pygame.draw.rect', (['image', '(120, 240, 80)', '(0, 0, self.width, self.height)', '(0)'], {}), '(image, (120, 240, 80), (0, 0, self.width, self.height), 0)\n', (721, 780), False, 'import pygame\n'), ((1192, 1227), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (1221, 1227), False, 'import pygame\n'), ((1604, 1640), 'os.path.join', 'os.path.join', (['_asset_dir', '"""heli.png"""'], {}), "(_asset_dir, 'heli.png')\n", (1616, 1640), False, 'import sys, os\n'), ((2558, 2593), 'pygame.sprite.Sprite.__init__', 'pygame.sprite.Sprite.__init__', (['self'], {}), '(self)\n', (2587, 2593), False, 'import pygame\n'), ((2719, 2768), 'pygame.Surface', 'pygame.Surface', (['(self.width, SCREEN_HEIGHT * 1.5)'], {}), '((self.width, SCREEN_HEIGHT * 1.5))\n', (2733, 2768), False, 'import pygame\n'), ((2900, 2974), 'pygame.draw.rect', 'pygame.draw.rect', (['image', 'color', '(0, 0, self.width, SCREEN_HEIGHT * 0.5)', '(0)'], {}), '(image, color, (0, 0, self.width, SCREEN_HEIGHT * 0.5), 0)\n', (2916, 2974), False, 'import pygame\n'), ((3061, 3159), 'pygame.draw.rect', 'pygame.draw.rect', (['image', 'color', '(0, SCREEN_HEIGHT * 1.05, self.width, SCREEN_HEIGHT * 0.5)', '(0)'], {}), '(image, color, (0, SCREEN_HEIGHT * 1.05, self.width, \n SCREEN_HEIGHT * 0.5), 0)\n', (3077, 3159), False, 'import pygame\n'), ((3978, 4013), 'os.path.join', 'os.path.join', (['self._dir_', '"""assets/"""'], {}), "(self._dir_, 'assets/')\n", (3990, 4013), False, 'import sys, os\n'), ((4107, 4125), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (4123, 4125), False, 'import pygame\n'), ((6272, 6293), 'pygame.sprite.Group', 'pygame.sprite.Group', ([], {}), '()\n', (6291, 6293), False, 'import pygame\n'), ((6365, 6386), 'pygame.sprite.Group', 'pygame.sprite.Group', ([], {}), '()\n', (6384, 6386), False, 'import pygame\n'), ((6444, 6465), 'pygame.sprite.Group', 'pygame.sprite.Group', ([], {}), '()\n', (6463, 6465), False, 'import pygame\n'), ((7988, 8053), 'pygame.sprite.spritecollide', 'pygame.sprite.spritecollide', (['self.player', 'self.block_group', '(False)'], {}), '(self.player, self.block_group, False)\n', (8015, 8053), False, 'import pygame\n'), ((8138, 8205), 'pygame.sprite.spritecollide', 'pygame.sprite.spritecollide', (['self.player', 'self.terrain_group', '(False)'], {}), '(self.player, self.terrain_group, False)\n', (8165, 8205), False, 'import pygame\n'), ((9898, 9921), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (9919, 9921), False, 'import pygame\n'), ((3925, 3950), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (3940, 3950), False, 'import sys, os\n'), ((5182, 5249), 'pygame.sprite.spritecollide', 'pygame.sprite.spritecollide', (['self.player', 'self.terrain_group', '(False)'], {}), '(self.player, self.terrain_group, False)\n', (5209, 5249), False, 'import pygame\n'), ((1662, 1697), 'pygame.image.load', 'pygame.image.load', (['heli_sprite_path'], {}), '(heli_sprite_path)\n', (1679, 1697), False, 'import pygame\n'), ((4185, 4198), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (4196, 4198), False, 'import pygame\n'), ((4215, 4225), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4223, 4225), False, 'import sys, os\n')] |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import patches
import matplotlib.patches as mpatches
import scipy.io as sio
# plotting configuration
ratio = 1.5
figure_len, figure_width = 15*ratio, 12*ratio
font_size_1, font_size_2 = 36*ratio, 36*ratio
legend_size = 18*ratio
line_width, tick_len = 3*ratio, 10*ratio
marker_size = 15*ratio
plot_line_width = 5*ratio
hfont = {'fontname': 'Arial'}
# simulation setup
dt = 0.0001
T = int(9/dt)
# neuronal parameters
tau_e, tau_i = 0.020, 0.010
alpha_e, alpha_i = 1, 1
# short-term depression
x, u_d = 1, 1
tau_x = 0.20
# network connectivity
Jee = 1.8
Jie = 1.0
Jei = 1.0
Jii = 0.6
r_e, r_i = 0, 0
z_e, z_i = 0, 0
l_r_e, l_r_i, l_x = [], [], []
for i in range(T):
if 50000 <= i < 70000:
g_e, g_i = 2.0, 2
else:
g_e, g_i = 1.55, 2
g_e = g_e * (g_e > 0)
g_i = g_i * (g_i > 0)
# SSN part
z_e = Jee * x * r_e - Jei * r_i + g_e
z_i = Jie * r_e - Jii * r_i + g_i
z_e = z_e * (z_e > 0)
z_i = z_i * (z_i > 0)
r_e = r_e + (-r_e + np.power(z_e, alpha_e)) / tau_e * dt
r_i = r_i + (-r_i + np.power(z_i, alpha_i)) / tau_i * dt
r_e = r_e * (r_e > 0)
r_i = r_i * (r_i > 0)
x = x + ((1 - x) / tau_x - u_d * x * r_e) * dt
x = np.clip(x, 0, 1)
l_r_e.append(r_e)
l_r_i.append(r_i)
l_x.append(x)
l_r_e = np.asarray(l_r_e)
l_r_i = np.asarray(l_r_i)
l_x = np.asarray(l_x)
# plotting
plt.figure(figsize=(figure_len, figure_width))
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_linewidth(line_width)
plt.tick_params(width=line_width, length=tick_len)
plt.yscale('symlog', linthreshy=0.1)
plt.plot(l_r_e, color='blue', linewidth=plot_line_width)
plt.plot(l_r_i, color='red', linewidth=plot_line_width)
plt.xticks(np.arange(30000, 90000 + 5000, 20000), np.arange(0, 6 + 0.5, 2), fontsize=font_size_1, **hfont)
plt.yticks([0, 1, 100, 10000], fontsize=font_size_1, **hfont)
plt.xlabel('Time (s)', fontsize=font_size_1, **hfont)
plt.ylabel('Firing rate (Hz)', fontsize=font_size_1, **hfont)
plt.xlim([30000, 90000])
plt.ylim([0, 10000])
plt.legend(['Exc', 'Inh'], prop={"family": "Arial", 'size': font_size_1}, loc='upper right')
plt.savefig('paper_figures/png/Revision_Fig_Point_Linear_network.png')
plt.savefig('paper_figures/pdf/Revision_Fig_Point_Linear_network.pdf')
# simulation setup
dt = 0.0001
T = int(9/dt)
# neuronal parameters
tau_e, tau_i = 0.020, 0.010
alpha_e, alpha_i = 2, 2
# network connectivity
Jee = 1.8
Jie = 2.0
Jei = 1.0
Jii = 1.0
r_e, r_i = 0, 0
z_e, z_i = 0, 0
l_r_e, l_r_i = [], []
for i in range(T):
if 50000 <= i < 70000:
g_e, g_i = 2.0, 2
else:
g_e, g_i = 1.55, 2
g_e = g_e * (g_e > 0)
g_i = g_i * (g_i > 0)
# SSN part
z_e = Jee * r_e - Jei * r_i + g_e
z_i = Jie * r_e - Jii * r_i + g_i
z_e = z_e * (z_e > 0)
z_i = z_i * (z_i > 0)
r_e = r_e + (-r_e + np.power(z_e, alpha_e)) / tau_e * dt
r_i = r_i + (-r_i + np.power(z_i, alpha_i)) / tau_i * dt
r_e = r_e * (r_e > 0)
r_i = r_i * (r_i > 0)
l_r_e.append(r_e)
l_r_i.append(r_i)
l_r_e = np.asarray(l_r_e)
l_r_i = np.asarray(l_r_i)
# plotting
plt.figure(figsize=(figure_len, figure_width))
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_linewidth(line_width)
plt.tick_params(width=line_width, length=tick_len)
plt.yscale('symlog', linthreshy=0.1)
plt.plot(l_r_e, color='blue', linewidth=plot_line_width)
plt.plot(l_r_i, color='red', linewidth=plot_line_width)
plt.xticks(np.arange(30000, 90000 + 5000, 20000), np.arange(0, 6 + 0.5, 2), fontsize=font_size_1, **hfont)
plt.yticks([0, 1, 100, 10000], fontsize=font_size_1, **hfont)
plt.xlabel('Time (s)', fontsize=font_size_1, **hfont)
plt.ylabel('Firing rate (Hz)', fontsize=font_size_1, **hfont)
plt.xlim([30000, 90000])
plt.ylim([0, 10000])
plt.legend(['Exc', 'Inh'], prop={"family": "Arial", 'size': font_size_1}, loc='upper right')
plt.savefig('paper_figures/png/Revision_Fig_Point_SSN.png')
plt.savefig('paper_figures/pdf/Revision_Fig_Point_SSN.pdf')
# simulation setup
dt = 0.0001
T = int(9/dt)
# neuronal parameters
tau_e, tau_i = 0.020, 0.010
alpha_e, alpha_i = 2, 2
# short-term depression
x, u_d = 1, 1
tau_x = 0.20
# network connectivity
Jee = 1.8
Jie = 1.0
Jei = 1.0
Jii = 0.6
r_e, r_i = 0, 0
z_e, z_i = 0, 0
l_r_e, l_r_i, l_x = [], [], []
for i in range(T):
if 50000 <= i < 70000:
g_e, g_i = 2.0, 2
else:
g_e, g_i = 1.55, 2
g_e = g_e * (g_e > 0)
g_i = g_i * (g_i > 0)
# SSN part
z_e = Jee * x * r_e - Jei * r_i + g_e
z_i = Jie * r_e - Jii * r_i + g_i
z_e = z_e * (z_e > 0)
z_i = z_i * (z_i > 0)
r_e = r_e + (-r_e + np.power(z_e, alpha_e)) / tau_e * dt
r_i = r_i + (-r_i + np.power(z_i, alpha_i)) / tau_i * dt
r_e = r_e * (r_e > 0)
r_i = r_i * (r_i > 0)
x = x + ((1 - x) / tau_x - u_d * x * r_e) * dt
x = np.clip(x, 0, 1)
l_r_e.append(r_e)
l_r_i.append(r_i)
l_x.append(x)
l_r_e = np.asarray(l_r_e)
l_r_i = np.asarray(l_r_i)
l_x = np.asarray(l_x)
# plotting
plt.figure(figsize=(figure_len, figure_width))
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(True)
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_linewidth(line_width)
plt.tick_params(width=line_width, length=tick_len)
plt.yscale('symlog', linthreshy=0.1)
plt.plot(l_r_e, color='blue', linewidth=plot_line_width)
plt.plot(l_r_i, color='red', linewidth=plot_line_width)
plt.xticks(np.arange(30000, 90000 + 5000, 20000), np.arange(0, 6 + 0.5, 2), fontsize=font_size_1, **hfont)
plt.yticks([0, 1, 100, 10000], fontsize=font_size_1, **hfont)
plt.xlabel('Time (s)', fontsize=font_size_1, **hfont)
plt.ylabel('Firing rate (Hz)', fontsize=font_size_1, **hfont)
plt.xlim([30000, 90000])
plt.ylim([0, 10000])
plt.legend(['Exc', 'Inh'], prop={"family": "Arial", 'size': font_size_1}, loc='upper right')
plt.savefig('paper_figures/png/Revision_Fig_Point_NTA.png')
plt.savefig('paper_figures/pdf/Revision_Fig_Point_NTA.pdf') | [
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.power",
"numpy.asarray",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.legend",
"numpy.clip",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.gca",
"matplotlib.pyp... | [((1377, 1394), 'numpy.asarray', 'np.asarray', (['l_r_e'], {}), '(l_r_e)\n', (1387, 1394), True, 'import numpy as np\n'), ((1403, 1420), 'numpy.asarray', 'np.asarray', (['l_r_i'], {}), '(l_r_i)\n', (1413, 1420), True, 'import numpy as np\n'), ((1427, 1442), 'numpy.asarray', 'np.asarray', (['l_x'], {}), '(l_x)\n', (1437, 1442), True, 'import numpy as np\n'), ((1455, 1501), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figure_len, figure_width)'}), '(figsize=(figure_len, figure_width))\n', (1465, 1501), True, 'import matplotlib.pyplot as plt\n'), ((1507, 1516), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1514, 1516), True, 'import matplotlib.pyplot as plt\n'), ((1759, 1809), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'width': 'line_width', 'length': 'tick_len'}), '(width=line_width, length=tick_len)\n', (1774, 1809), True, 'import matplotlib.pyplot as plt\n'), ((1810, 1846), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""symlog"""'], {'linthreshy': '(0.1)'}), "('symlog', linthreshy=0.1)\n", (1820, 1846), True, 'import matplotlib.pyplot as plt\n'), ((1848, 1904), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_e'], {'color': '"""blue"""', 'linewidth': 'plot_line_width'}), "(l_r_e, color='blue', linewidth=plot_line_width)\n", (1856, 1904), True, 'import matplotlib.pyplot as plt\n'), ((1905, 1960), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_i'], {'color': '"""red"""', 'linewidth': 'plot_line_width'}), "(l_r_i, color='red', linewidth=plot_line_width)\n", (1913, 1960), True, 'import matplotlib.pyplot as plt\n'), ((2069, 2130), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 1, 100, 10000]'], {'fontsize': 'font_size_1'}), '([0, 1, 100, 10000], fontsize=font_size_1, **hfont)\n', (2079, 2130), True, 'import matplotlib.pyplot as plt\n'), ((2131, 2184), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {'fontsize': 'font_size_1'}), "('Time (s)', fontsize=font_size_1, **hfont)\n", (2141, 2184), True, 'import matplotlib.pyplot as plt\n'), ((2185, 2246), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Firing rate (Hz)"""'], {'fontsize': 'font_size_1'}), "('Firing rate (Hz)', fontsize=font_size_1, **hfont)\n", (2195, 2246), True, 'import matplotlib.pyplot as plt\n'), ((2247, 2271), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[30000, 90000]'], {}), '([30000, 90000])\n', (2255, 2271), True, 'import matplotlib.pyplot as plt\n'), ((2272, 2292), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 10000]'], {}), '([0, 10000])\n', (2280, 2292), True, 'import matplotlib.pyplot as plt\n'), ((2293, 2389), 'matplotlib.pyplot.legend', 'plt.legend', (["['Exc', 'Inh']"], {'prop': "{'family': 'Arial', 'size': font_size_1}", 'loc': '"""upper right"""'}), "(['Exc', 'Inh'], prop={'family': 'Arial', 'size': font_size_1},\n loc='upper right')\n", (2303, 2389), True, 'import matplotlib.pyplot as plt\n'), ((2386, 2456), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/png/Revision_Fig_Point_Linear_network.png"""'], {}), "('paper_figures/png/Revision_Fig_Point_Linear_network.png')\n", (2397, 2456), True, 'import matplotlib.pyplot as plt\n'), ((2457, 2527), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/pdf/Revision_Fig_Point_Linear_network.pdf"""'], {}), "('paper_figures/pdf/Revision_Fig_Point_Linear_network.pdf')\n", (2468, 2527), True, 'import matplotlib.pyplot as plt\n'), ((3308, 3325), 'numpy.asarray', 'np.asarray', (['l_r_e'], {}), '(l_r_e)\n', (3318, 3325), True, 'import numpy as np\n'), ((3334, 3351), 'numpy.asarray', 'np.asarray', (['l_r_i'], {}), '(l_r_i)\n', (3344, 3351), True, 'import numpy as np\n'), ((3364, 3410), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figure_len, figure_width)'}), '(figsize=(figure_len, figure_width))\n', (3374, 3410), True, 'import matplotlib.pyplot as plt\n'), ((3416, 3425), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3423, 3425), True, 'import matplotlib.pyplot as plt\n'), ((3668, 3718), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'width': 'line_width', 'length': 'tick_len'}), '(width=line_width, length=tick_len)\n', (3683, 3718), True, 'import matplotlib.pyplot as plt\n'), ((3719, 3755), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""symlog"""'], {'linthreshy': '(0.1)'}), "('symlog', linthreshy=0.1)\n", (3729, 3755), True, 'import matplotlib.pyplot as plt\n'), ((3757, 3813), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_e'], {'color': '"""blue"""', 'linewidth': 'plot_line_width'}), "(l_r_e, color='blue', linewidth=plot_line_width)\n", (3765, 3813), True, 'import matplotlib.pyplot as plt\n'), ((3814, 3869), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_i'], {'color': '"""red"""', 'linewidth': 'plot_line_width'}), "(l_r_i, color='red', linewidth=plot_line_width)\n", (3822, 3869), True, 'import matplotlib.pyplot as plt\n'), ((3978, 4039), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 1, 100, 10000]'], {'fontsize': 'font_size_1'}), '([0, 1, 100, 10000], fontsize=font_size_1, **hfont)\n', (3988, 4039), True, 'import matplotlib.pyplot as plt\n'), ((4040, 4093), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {'fontsize': 'font_size_1'}), "('Time (s)', fontsize=font_size_1, **hfont)\n", (4050, 4093), True, 'import matplotlib.pyplot as plt\n'), ((4094, 4155), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Firing rate (Hz)"""'], {'fontsize': 'font_size_1'}), "('Firing rate (Hz)', fontsize=font_size_1, **hfont)\n", (4104, 4155), True, 'import matplotlib.pyplot as plt\n'), ((4156, 4180), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[30000, 90000]'], {}), '([30000, 90000])\n', (4164, 4180), True, 'import matplotlib.pyplot as plt\n'), ((4181, 4201), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 10000]'], {}), '([0, 10000])\n', (4189, 4201), True, 'import matplotlib.pyplot as plt\n'), ((4202, 4298), 'matplotlib.pyplot.legend', 'plt.legend', (["['Exc', 'Inh']"], {'prop': "{'family': 'Arial', 'size': font_size_1}", 'loc': '"""upper right"""'}), "(['Exc', 'Inh'], prop={'family': 'Arial', 'size': font_size_1},\n loc='upper right')\n", (4212, 4298), True, 'import matplotlib.pyplot as plt\n'), ((4295, 4354), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/png/Revision_Fig_Point_SSN.png"""'], {}), "('paper_figures/png/Revision_Fig_Point_SSN.png')\n", (4306, 4354), True, 'import matplotlib.pyplot as plt\n'), ((4355, 4414), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/pdf/Revision_Fig_Point_SSN.pdf"""'], {}), "('paper_figures/pdf/Revision_Fig_Point_SSN.pdf')\n", (4366, 4414), True, 'import matplotlib.pyplot as plt\n'), ((5355, 5372), 'numpy.asarray', 'np.asarray', (['l_r_e'], {}), '(l_r_e)\n', (5365, 5372), True, 'import numpy as np\n'), ((5381, 5398), 'numpy.asarray', 'np.asarray', (['l_r_i'], {}), '(l_r_i)\n', (5391, 5398), True, 'import numpy as np\n'), ((5405, 5420), 'numpy.asarray', 'np.asarray', (['l_x'], {}), '(l_x)\n', (5415, 5420), True, 'import numpy as np\n'), ((5433, 5479), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(figure_len, figure_width)'}), '(figsize=(figure_len, figure_width))\n', (5443, 5479), True, 'import matplotlib.pyplot as plt\n'), ((5485, 5494), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5492, 5494), True, 'import matplotlib.pyplot as plt\n'), ((5737, 5787), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'width': 'line_width', 'length': 'tick_len'}), '(width=line_width, length=tick_len)\n', (5752, 5787), True, 'import matplotlib.pyplot as plt\n'), ((5788, 5824), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""symlog"""'], {'linthreshy': '(0.1)'}), "('symlog', linthreshy=0.1)\n", (5798, 5824), True, 'import matplotlib.pyplot as plt\n'), ((5826, 5882), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_e'], {'color': '"""blue"""', 'linewidth': 'plot_line_width'}), "(l_r_e, color='blue', linewidth=plot_line_width)\n", (5834, 5882), True, 'import matplotlib.pyplot as plt\n'), ((5883, 5938), 'matplotlib.pyplot.plot', 'plt.plot', (['l_r_i'], {'color': '"""red"""', 'linewidth': 'plot_line_width'}), "(l_r_i, color='red', linewidth=plot_line_width)\n", (5891, 5938), True, 'import matplotlib.pyplot as plt\n'), ((6047, 6108), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 1, 100, 10000]'], {'fontsize': 'font_size_1'}), '([0, 1, 100, 10000], fontsize=font_size_1, **hfont)\n', (6057, 6108), True, 'import matplotlib.pyplot as plt\n'), ((6109, 6162), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {'fontsize': 'font_size_1'}), "('Time (s)', fontsize=font_size_1, **hfont)\n", (6119, 6162), True, 'import matplotlib.pyplot as plt\n'), ((6163, 6224), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Firing rate (Hz)"""'], {'fontsize': 'font_size_1'}), "('Firing rate (Hz)', fontsize=font_size_1, **hfont)\n", (6173, 6224), True, 'import matplotlib.pyplot as plt\n'), ((6225, 6249), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[30000, 90000]'], {}), '([30000, 90000])\n', (6233, 6249), True, 'import matplotlib.pyplot as plt\n'), ((6250, 6270), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 10000]'], {}), '([0, 10000])\n', (6258, 6270), True, 'import matplotlib.pyplot as plt\n'), ((6271, 6367), 'matplotlib.pyplot.legend', 'plt.legend', (["['Exc', 'Inh']"], {'prop': "{'family': 'Arial', 'size': font_size_1}", 'loc': '"""upper right"""'}), "(['Exc', 'Inh'], prop={'family': 'Arial', 'size': font_size_1},\n loc='upper right')\n", (6281, 6367), True, 'import matplotlib.pyplot as plt\n'), ((6364, 6423), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/png/Revision_Fig_Point_NTA.png"""'], {}), "('paper_figures/png/Revision_Fig_Point_NTA.png')\n", (6375, 6423), True, 'import matplotlib.pyplot as plt\n'), ((6424, 6483), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""paper_figures/pdf/Revision_Fig_Point_NTA.pdf"""'], {}), "('paper_figures/pdf/Revision_Fig_Point_NTA.pdf')\n", (6435, 6483), True, 'import matplotlib.pyplot as plt\n'), ((1288, 1304), 'numpy.clip', 'np.clip', (['x', '(0)', '(1)'], {}), '(x, 0, 1)\n', (1295, 1304), True, 'import numpy as np\n'), ((1973, 2010), 'numpy.arange', 'np.arange', (['(30000)', '(90000 + 5000)', '(20000)'], {}), '(30000, 90000 + 5000, 20000)\n', (1982, 2010), True, 'import numpy as np\n'), ((2012, 2036), 'numpy.arange', 'np.arange', (['(0)', '(6 + 0.5)', '(2)'], {}), '(0, 6 + 0.5, 2)\n', (2021, 2036), True, 'import numpy as np\n'), ((3882, 3919), 'numpy.arange', 'np.arange', (['(30000)', '(90000 + 5000)', '(20000)'], {}), '(30000, 90000 + 5000, 20000)\n', (3891, 3919), True, 'import numpy as np\n'), ((3921, 3945), 'numpy.arange', 'np.arange', (['(0)', '(6 + 0.5)', '(2)'], {}), '(0, 6 + 0.5, 2)\n', (3930, 3945), True, 'import numpy as np\n'), ((5266, 5282), 'numpy.clip', 'np.clip', (['x', '(0)', '(1)'], {}), '(x, 0, 1)\n', (5273, 5282), True, 'import numpy as np\n'), ((5951, 5988), 'numpy.arange', 'np.arange', (['(30000)', '(90000 + 5000)', '(20000)'], {}), '(30000, 90000 + 5000, 20000)\n', (5960, 5988), True, 'import numpy as np\n'), ((5990, 6014), 'numpy.arange', 'np.arange', (['(0)', '(6 + 0.5)', '(2)'], {}), '(0, 6 + 0.5, 2)\n', (5999, 6014), True, 'import numpy as np\n'), ((1077, 1099), 'numpy.power', 'np.power', (['z_e', 'alpha_e'], {}), '(z_e, alpha_e)\n', (1085, 1099), True, 'import numpy as np\n'), ((1138, 1160), 'numpy.power', 'np.power', (['z_i', 'alpha_i'], {}), '(z_i, alpha_i)\n', (1146, 1160), True, 'import numpy as np\n'), ((3103, 3125), 'numpy.power', 'np.power', (['z_e', 'alpha_e'], {}), '(z_e, alpha_e)\n', (3111, 3125), True, 'import numpy as np\n'), ((3164, 3186), 'numpy.power', 'np.power', (['z_i', 'alpha_i'], {}), '(z_i, alpha_i)\n', (3172, 3186), True, 'import numpy as np\n'), ((5055, 5077), 'numpy.power', 'np.power', (['z_e', 'alpha_e'], {}), '(z_e, alpha_e)\n', (5063, 5077), True, 'import numpy as np\n'), ((5116, 5138), 'numpy.power', 'np.power', (['z_i', 'alpha_i'], {}), '(z_i, alpha_i)\n', (5124, 5138), True, 'import numpy as np\n')] |
"""Data utils functions for pre-processing and data loading."""
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
import torch
from sc_utility import *
def load_data(args, datapath):
if args.task == 'nc':
data = load_data_nc(args.dataset)
else:
data = load_data_lp(args.dataset, args.use_feats, datapath)
adj = data['adj_train']
if args.task == 'lp':
adj_train, train_edges, train_edges_false, val_edges, val_edges_false, test_edges, test_edges_false = mask_edges(
adj, args.val_prop, args.test_prop, args.split_seed
)
data['adj_train'] = adj_train
data['train_edges'], data['train_edges_false'] = train_edges, train_edges_false
data['val_edges'], data['val_edges_false'] = val_edges, val_edges_false
data['test_edges'], data['test_edges_false'] = test_edges, test_edges_false
data['adj_train_norm'], data['features'] = process(
data['adj_train'], data['features'], args.normalize_adj, args.normalize_feats
)
if args.dataset == 'airport':
data['features'] = augment(data['adj_train'], data['features'])
return data
# ############### FEATURES PROCESSING ####################################
def process(adj, features, normalize_adj, normalize_feats):
if sp.isspmatrix(features):
features = np.array(features.todense())
if normalize_feats:
features = normalize(features)
features = torch.Tensor(features)
if normalize_adj:
adj = normalize(adj + sp.eye(adj.shape[0]))
adj = sparse_mx_to_torch_sparse_tensor(adj)
return adj, features
def normalize(mx):
"""Row-normalize sparse matrix."""
rowsum = np.array(mx.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
mx = r_mat_inv.dot(mx)
return mx
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo()
indices = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64)
)
values = torch.Tensor(sparse_mx.data)
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape)
def augment(adj, features, normalize_feats=True):
deg = np.squeeze(np.sum(adj, axis=0).astype(int))
deg[deg > 5] = 5
deg_onehot = torch.tensor(np.eye(6)[deg], dtype=torch.float).squeeze()
const_f = torch.ones(features.size(0), 1)
features = torch.cat((features, deg_onehot, const_f), dim=1)
return features
# ############### DATA SPLITS #####################################################
def mask_edges(adj, val_prop, test_prop, seed):
np.random.seed(seed) # get tp edges
x, y = sp.triu(adj).nonzero()
pos_edges = np.array(list(zip(x, y)))
np.random.shuffle(pos_edges)
# get tn edges
x, y = sp.triu(sp.csr_matrix(1. - adj.toarray())).nonzero()
neg_edges = np.array(list(zip(x, y)))
np.random.shuffle(neg_edges)
m_pos = len(pos_edges)
n_val = int(m_pos * val_prop)
n_test = int(m_pos * test_prop)
val_edges, test_edges, train_edges = pos_edges[:n_val], pos_edges[n_val:n_test + n_val], pos_edges[n_test + n_val:]
val_edges_false, test_edges_false = neg_edges[:n_val], neg_edges[n_val:n_test + n_val]
train_edges_false = np.concatenate([neg_edges, val_edges, test_edges], axis=0)
adj_train = sp.csr_matrix((np.ones(train_edges.shape[0]), (train_edges[:, 0], train_edges[:, 1])), shape=adj.shape)
adj_train = adj_train + adj_train.T
return adj_train, torch.LongTensor(train_edges), torch.LongTensor(train_edges_false), torch.LongTensor(val_edges), \
torch.LongTensor(val_edges_false), torch.LongTensor(test_edges), torch.LongTensor(
test_edges_false)
def split_data(labels, val_prop, test_prop, seed):
np.random.seed(seed)
nb_nodes = labels.shape[0]
all_idx = np.arange(nb_nodes)
pos_idx = labels.nonzero()[0]
neg_idx = (1. - labels).nonzero()[0]
np.random.shuffle(pos_idx)
np.random.shuffle(neg_idx)
pos_idx = pos_idx.tolist()
neg_idx = neg_idx.tolist()
nb_pos_neg = min(len(pos_idx), len(neg_idx))
nb_val = round(val_prop * nb_pos_neg)
nb_test = round(test_prop * nb_pos_neg)
idx_val_pos, idx_test_pos, idx_train_pos = pos_idx[:nb_val], pos_idx[nb_val:nb_val + nb_test], pos_idx[
nb_val + nb_test:]
idx_val_neg, idx_test_neg, idx_train_neg = neg_idx[:nb_val], neg_idx[nb_val:nb_val + nb_test], neg_idx[
nb_val + nb_test:]
return idx_val_pos + idx_val_neg, idx_test_pos + idx_test_neg, idx_train_pos + idx_train_neg
def bin_feat(feat, bins):
digitized = np.digitize(feat, bins)
return digitized - digitized.min()
# ############### LINK PREDICTION DATA LOADERS ####################################
def load_data_lp(dataset, use_feats, data_path):
if dataset in ['cora', 'pubmed']:
adj, features = load_citation_data(dataset, use_feats, data_path)[:2]
elif dataset == 'disease_lp':
adj, features = load_synthetic_data(dataset, use_feats, data_path)[:2]
elif dataset == 'airport':
adj, features = load_data_airport(dataset, data_path, return_label=False)
else:
raise FileNotFoundError('Dataset {} is not supported.'.format(dataset))
data = {'adj_train': adj, 'features': features}
return data
# ############### NODE CLASSIFICATION DATA LOADERS ####################################
def load_data_nc(dataset):
adj, features, labels, idx_train, idx_val, idx_test, idx_pred = load_customize_data(dataset)
labels = torch.LongTensor(labels)
data = {'adj_train': adj, 'features': features, 'labels': labels, 'idx_train': idx_train, 'idx_val': idx_val, 'idx_test': idx_test, 'idx_pred': idx_pred}
return data
# ############### DATASETS ####################################
def load_citation_data(dataset_str, use_feats, data_path, split_seed=None):
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = []
for i in range(len(names)):
with open(os.path.join(data_path, "ind.{}.{}".format(dataset_str, names[i])), 'rb') as f:
if sys.version_info > (3, 0):
objects.append(pkl.load(f, encoding='latin1'))
else:
objects.append(pkl.load(f))
x, y, tx, ty, allx, ally, graph = tuple(objects)
test_idx_reorder = parse_index_file(os.path.join(data_path, "ind.{}.test.index".format(dataset_str)))
test_idx_range = np.sort(test_idx_reorder)
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
labels = np.vstack((ally, ty))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
labels = np.argmax(labels, 1)
idx_test = test_idx_range.tolist()
idx_train = list(range(len(y)))
idx_val = range(len(y), len(y) + 500)
adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
if not use_feats:
features = sp.eye(adj.shape[0])
return adj, features, labels, idx_train, idx_val, idx_test
def parse_index_file(filename):
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
def load_synthetic_data(dataset_str, use_feats, data_path):
object_to_idx = {}
idx_counter = 0
edges = []
with open(os.path.join(data_path, "{}.edges.csv".format(dataset_str)), 'r') as f:
all_edges = f.readlines()
for line in all_edges:
n1, n2 = line.rstrip().split(',')
if n1 in object_to_idx:
i = object_to_idx[n1]
else:
i = idx_counter
object_to_idx[n1] = i
idx_counter += 1
if n2 in object_to_idx:
j = object_to_idx[n2]
else:
j = idx_counter
object_to_idx[n2] = j
idx_counter += 1
edges.append((i, j))
adj = np.zeros((len(object_to_idx), len(object_to_idx)))
for i, j in edges:
adj[i, j] = 1. # comment this line for directed adjacency matrix
adj[j, i] = 1.
if use_feats:
features = sp.load_npz(os.path.join(data_path, "{}.feats.npz".format(dataset_str)))
else:
features = sp.eye(adj.shape[0])
labels = np.load(os.path.join(data_path, "{}.labels.npy".format(dataset_str)))
return sp.csr_matrix(adj), features, labels
def load_data_airport(dataset_str, data_path, return_label=False):
graph = pkl.load(open(os.path.join(data_path, dataset_str + '.p'), 'rb'))
adj = nx.adjacency_matrix(graph)
features = np.array([graph.node[u]['feat'] for u in graph.nodes()])
if return_label:
label_idx = 4
labels = features[:, label_idx]
features = features[:, :label_idx]
labels = bin_feat(labels, bins=[7.0/7, 8.0/7, 9.0/7])
return sp.csr_matrix(adj), features, labels
else:
return sp.csr_matrix(adj), features
| [
"numpy.random.seed",
"numpy.sum",
"numpy.argmax",
"torch.cat",
"numpy.ones",
"pickle.load",
"numpy.arange",
"scipy.sparse.isspmatrix",
"os.path.join",
"scipy.sparse.eye",
"networkx.adjacency_matrix",
"numpy.power",
"scipy.sparse.triu",
"torch.Tensor",
"numpy.random.shuffle",
"scipy.spa... | [((1389, 1412), 'scipy.sparse.isspmatrix', 'sp.isspmatrix', (['features'], {}), '(features)\n', (1402, 1412), True, 'import scipy.sparse as sp\n'), ((1540, 1562), 'torch.Tensor', 'torch.Tensor', (['features'], {}), '(features)\n', (1552, 1562), False, 'import torch\n'), ((1894, 1909), 'scipy.sparse.diags', 'sp.diags', (['r_inv'], {}), '(r_inv)\n', (1902, 1909), True, 'import scipy.sparse as sp\n'), ((2224, 2252), 'torch.Tensor', 'torch.Tensor', (['sparse_mx.data'], {}), '(sparse_mx.data)\n', (2236, 2252), False, 'import torch\n'), ((2265, 2292), 'torch.Size', 'torch.Size', (['sparse_mx.shape'], {}), '(sparse_mx.shape)\n', (2275, 2292), False, 'import torch\n'), ((2304, 2352), 'torch.sparse.FloatTensor', 'torch.sparse.FloatTensor', (['indices', 'values', 'shape'], {}), '(indices, values, shape)\n', (2328, 2352), False, 'import torch\n'), ((2616, 2665), 'torch.cat', 'torch.cat', (['(features, deg_onehot, const_f)'], {'dim': '(1)'}), '((features, deg_onehot, const_f), dim=1)\n', (2625, 2665), False, 'import torch\n'), ((2826, 2846), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2840, 2846), True, 'import numpy as np\n'), ((2943, 2971), 'numpy.random.shuffle', 'np.random.shuffle', (['pos_edges'], {}), '(pos_edges)\n', (2960, 2971), True, 'import numpy as np\n'), ((3101, 3129), 'numpy.random.shuffle', 'np.random.shuffle', (['neg_edges'], {}), '(neg_edges)\n', (3118, 3129), True, 'import numpy as np\n'), ((3463, 3521), 'numpy.concatenate', 'np.concatenate', (['[neg_edges, val_edges, test_edges]'], {'axis': '(0)'}), '([neg_edges, val_edges, test_edges], axis=0)\n', (3477, 3521), True, 'import numpy as np\n'), ((3986, 4006), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (4000, 4006), True, 'import numpy as np\n'), ((4052, 4071), 'numpy.arange', 'np.arange', (['nb_nodes'], {}), '(nb_nodes)\n', (4061, 4071), True, 'import numpy as np\n'), ((4151, 4177), 'numpy.random.shuffle', 'np.random.shuffle', (['pos_idx'], {}), '(pos_idx)\n', (4168, 4177), True, 'import numpy as np\n'), ((4182, 4208), 'numpy.random.shuffle', 'np.random.shuffle', (['neg_idx'], {}), '(neg_idx)\n', (4199, 4208), True, 'import numpy as np\n'), ((4999, 5022), 'numpy.digitize', 'np.digitize', (['feat', 'bins'], {}), '(feat, bins)\n', (5010, 5022), True, 'import numpy as np\n'), ((5928, 5952), 'torch.LongTensor', 'torch.LongTensor', (['labels'], {}), '(labels)\n', (5944, 5952), False, 'import torch\n'), ((6825, 6850), 'numpy.sort', 'np.sort', (['test_idx_reorder'], {}), '(test_idx_reorder)\n', (6832, 6850), True, 'import numpy as np\n'), ((6973, 6994), 'numpy.vstack', 'np.vstack', (['(ally, ty)'], {}), '((ally, ty))\n', (6982, 6994), True, 'import numpy as np\n'), ((7068, 7088), 'numpy.argmax', 'np.argmax', (['labels', '(1)'], {}), '(labels, 1)\n', (7077, 7088), True, 'import numpy as np\n'), ((8839, 8865), 'networkx.adjacency_matrix', 'nx.adjacency_matrix', (['graph'], {}), '(graph)\n', (8858, 8865), True, 'import networkx as nx\n'), ((1856, 1871), 'numpy.isinf', 'np.isinf', (['r_inv'], {}), '(r_inv)\n', (1864, 1871), True, 'import numpy as np\n'), ((3704, 3733), 'torch.LongTensor', 'torch.LongTensor', (['train_edges'], {}), '(train_edges)\n', (3720, 3733), False, 'import torch\n'), ((3735, 3770), 'torch.LongTensor', 'torch.LongTensor', (['train_edges_false'], {}), '(train_edges_false)\n', (3751, 3770), False, 'import torch\n'), ((3772, 3799), 'torch.LongTensor', 'torch.LongTensor', (['val_edges'], {}), '(val_edges)\n', (3788, 3799), False, 'import torch\n'), ((3814, 3847), 'torch.LongTensor', 'torch.LongTensor', (['val_edges_false'], {}), '(val_edges_false)\n', (3830, 3847), False, 'import torch\n'), ((3849, 3877), 'torch.LongTensor', 'torch.LongTensor', (['test_edges'], {}), '(test_edges)\n', (3865, 3877), False, 'import torch\n'), ((3879, 3913), 'torch.LongTensor', 'torch.LongTensor', (['test_edges_false'], {}), '(test_edges_false)\n', (3895, 3913), False, 'import torch\n'), ((7236, 7264), 'networkx.from_dict_of_lists', 'nx.from_dict_of_lists', (['graph'], {}), '(graph)\n', (7257, 7264), True, 'import networkx as nx\n'), ((7307, 7327), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (7313, 7327), True, 'import scipy.sparse as sp\n'), ((8530, 8550), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (8536, 8550), True, 'import scipy.sparse as sp\n'), ((8645, 8663), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['adj'], {}), '(adj)\n', (8658, 8663), True, 'import scipy.sparse as sp\n'), ((1815, 1835), 'numpy.power', 'np.power', (['rowsum', '(-1)'], {}), '(rowsum, -1)\n', (1823, 1835), True, 'import numpy as np\n'), ((2874, 2886), 'scipy.sparse.triu', 'sp.triu', (['adj'], {}), '(adj)\n', (2881, 2886), True, 'import scipy.sparse as sp\n'), ((3553, 3582), 'numpy.ones', 'np.ones', (['train_edges.shape[0]'], {}), '(train_edges.shape[0])\n', (3560, 3582), True, 'import numpy as np\n'), ((6866, 6887), 'scipy.sparse.vstack', 'sp.vstack', (['(allx, tx)'], {}), '((allx, tx))\n', (6875, 6887), True, 'import scipy.sparse as sp\n'), ((8777, 8820), 'os.path.join', 'os.path.join', (['data_path', "(dataset_str + '.p')"], {}), "(data_path, dataset_str + '.p')\n", (8789, 8820), False, 'import os\n'), ((9141, 9159), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['adj'], {}), '(adj)\n', (9154, 9159), True, 'import scipy.sparse as sp\n'), ((9203, 9221), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['adj'], {}), '(adj)\n', (9216, 9221), True, 'import scipy.sparse as sp\n'), ((1615, 1635), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (1621, 1635), True, 'import scipy.sparse as sp\n'), ((2146, 2187), 'numpy.vstack', 'np.vstack', (['(sparse_mx.row, sparse_mx.col)'], {}), '((sparse_mx.row, sparse_mx.col))\n', (2155, 2187), True, 'import numpy as np\n'), ((2426, 2445), 'numpy.sum', 'np.sum', (['adj'], {'axis': '(0)'}), '(adj, axis=0)\n', (2432, 2445), True, 'import numpy as np\n'), ((2510, 2519), 'numpy.eye', 'np.eye', (['(6)'], {}), '(6)\n', (2516, 2519), True, 'import numpy as np\n'), ((6551, 6581), 'pickle.load', 'pkl.load', (['f'], {'encoding': '"""latin1"""'}), "(f, encoding='latin1')\n", (6559, 6581), True, 'import pickle as pkl\n'), ((6632, 6643), 'pickle.load', 'pkl.load', (['f'], {}), '(f)\n', (6640, 6643), True, 'import pickle as pkl\n')] |
import unittest
import pointcloud.utils.misc as misc
from shapely.geometry import Polygon
import numpy as np
workspace = 'test_data/'
points = np.array([[1, 1, 1],
[1, 2, 1],
[3, 1, 1],
[4, 5, 1],
[3, 6, 10],
[2, 5, 10],
[4, 6, 10],
[3, 5, 10]])
class MiscTests(unittest.TestCase):
def test_get_names_and_polygons(self):
workspace = './test_data'
out = misc.get_names_and_polygons_in_workspace(workspace, settings=None, polygon_from_filename_settings=None,
file_format='las', file_format_settings=None)
print(out)
def test_calculate_tile_size_from_target_number_of_points(self):
grid = misc.calculate_tile_size_from_target_number_of_points(1000, 10, tile_type='grid')
circle = misc.calculate_tile_size_from_target_number_of_points(1000, 10, tile_type='circle')
self.assertEqual(10, grid)
self.assertEqual(6, circle)
def test_calculate_polygon_from_filename(self):
polygon = misc.calculate_polygon_from_filename('test_data/test_tile_27620_158050', 10, 3, 4)
polygon_a = Polygon([(27620, 158050), (27630, 158050), (27630, 158060), (27620, 158060), (27620, 158050)])
self.assertEqual(polygon_a, polygon)
def test_get_names_and_polygons_in_workspace(self):
names_polygons = misc.get_names_and_polygons_in_workspace(workspace, settings={'step': 25, 'x_pos': 3, 'y_pos': 4})
data1 = names_polygons[0]
self.assertEqual('test_tile_27620_158060', data1['name'])
self.assertIsInstance(data1['polygon'], Polygon)
data1 = names_polygons[1]
self.assertEqual('test_tile_27620_158050', data1['name'])
self.assertIsInstance(data1['polygon'], Polygon)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"shapely.geometry.Polygon",
"pointcloud.utils.misc.calculate_tile_size_from_target_number_of_points",
"pointcloud.utils.misc.get_names_and_polygons_in_workspace",
"pointcloud.utils.misc.calculate_polygon_from_filename",
"numpy.array"
] | [((145, 252), 'numpy.array', 'np.array', (['[[1, 1, 1], [1, 2, 1], [3, 1, 1], [4, 5, 1], [3, 6, 10], [2, 5, 10], [4, 6,\n 10], [3, 5, 10]]'], {}), '([[1, 1, 1], [1, 2, 1], [3, 1, 1], [4, 5, 1], [3, 6, 10], [2, 5, 10\n ], [4, 6, 10], [3, 5, 10]])\n', (153, 252), True, 'import numpy as np\n'), ((1904, 1919), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1917, 1919), False, 'import unittest\n'), ((511, 668), 'pointcloud.utils.misc.get_names_and_polygons_in_workspace', 'misc.get_names_and_polygons_in_workspace', (['workspace'], {'settings': 'None', 'polygon_from_filename_settings': 'None', 'file_format': '"""las"""', 'file_format_settings': 'None'}), "(workspace, settings=None,\n polygon_from_filename_settings=None, file_format='las',\n file_format_settings=None)\n", (551, 668), True, 'import pointcloud.utils.misc as misc\n'), ((805, 891), 'pointcloud.utils.misc.calculate_tile_size_from_target_number_of_points', 'misc.calculate_tile_size_from_target_number_of_points', (['(1000)', '(10)'], {'tile_type': '"""grid"""'}), "(1000, 10, tile_type=\n 'grid')\n", (858, 891), True, 'import pointcloud.utils.misc as misc\n'), ((904, 992), 'pointcloud.utils.misc.calculate_tile_size_from_target_number_of_points', 'misc.calculate_tile_size_from_target_number_of_points', (['(1000)', '(10)'], {'tile_type': '"""circle"""'}), "(1000, 10, tile_type=\n 'circle')\n", (957, 992), True, 'import pointcloud.utils.misc as misc\n'), ((1131, 1217), 'pointcloud.utils.misc.calculate_polygon_from_filename', 'misc.calculate_polygon_from_filename', (['"""test_data/test_tile_27620_158050"""', '(10)', '(3)', '(4)'], {}), "('test_data/test_tile_27620_158050', 10,\n 3, 4)\n", (1167, 1217), True, 'import pointcloud.utils.misc as misc\n'), ((1234, 1332), 'shapely.geometry.Polygon', 'Polygon', (['[(27620, 158050), (27630, 158050), (27630, 158060), (27620, 158060), (27620,\n 158050)]'], {}), '([(27620, 158050), (27630, 158050), (27630, 158060), (27620, 158060),\n (27620, 158050)])\n', (1241, 1332), False, 'from shapely.geometry import Polygon\n'), ((1457, 1559), 'pointcloud.utils.misc.get_names_and_polygons_in_workspace', 'misc.get_names_and_polygons_in_workspace', (['workspace'], {'settings': "{'step': 25, 'x_pos': 3, 'y_pos': 4}"}), "(workspace, settings={'step': 25,\n 'x_pos': 3, 'y_pos': 4})\n", (1497, 1559), True, 'import pointcloud.utils.misc as misc\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from utilities.helpers import load_model_from_dict
class Model(nn.Module):
"""
Defines an aligner network.
This is the main class of the architecture code.
`height` is the number of levels of the network
`feature_maps` is the number of feature maps per encoding layer
"""
def __init__(self, *args, **kwargs):
super().__init__()
self.encode = UNet()
self.forward = self.encode.forward
def __getitem__(self, index):
return self.submodule(index)
def __len__(self):
return self.height
def load(self, path):
"""
Loads saved weights into the model
"""
with path.open('rb') as f:
weights = torch.load(f)
load_model_from_dict(self.encode, weights)
return self
def save(self, path):
"""
Saves the model weights to a file
"""
with path.open('wb') as f:
torch.save(self.encode.state_dict(), f)
@property
def height(self):
return 1
def submodule(self, index):
"""
Returns a submodule as indexed by `index`.
Submodules with lower indecies are intended to be trained earlier,
so this also decides the training order.
`index` must be an int, a slice, or None.
If `index` is a slice, the submodule contains the relevant levels.
If `index` is None or greater than the height, the submodule
returned contains the whole model.
"""
return self
def train_level(self, *args, **kwargs):
return self
def init_level(self, *args, **kwargs):
return self
# helper operations
def conv3x3(in_channels, out_channels):
return nn.Conv2d(in_channels, out_channels,
kernel_size=3, stride=1, padding=1, bias=True)
def maxpool2x2():
return nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
class UpConv2x2(nn.Module):
def __init__(self, channels):
super(UpConv2x2, self).__init__()
self.conv = nn.Conv2d(channels, channels // 2,
kernel_size=2, stride=1, padding=0, bias=True)
def forward(self, x):
x = F.interpolate(x, scale_factor=2, mode='nearest')
x = F.pad(x, (0,1,0,1))
x = self.conv(x)
return x
def concat(xh, xv):
return torch.cat([xh, xv], dim=1)
# unet blocks
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
"""
Args:
in_channels: number of channels in input (1st) feature map
out_channels: number of channels in output feature maps
"""
super(ConvBlock, self).__init__()
self.conv1 = conv3x3(in_channels, out_channels)
self.conv2 = conv3x3(out_channels, out_channels)
self.conv3 = conv3x3(out_channels, out_channels)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
return x
class DownConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
"""
Args:
in_channels: number of channels in input (1st) feature map
out_channels: number of channels in output feature maps
"""
super(DownConvBlock, self).__init__()
self.maxpool = maxpool2x2()
self.conv1 = conv3x3(in_channels, out_channels)
self.conv2 = conv3x3(out_channels, out_channels)
self.conv3 = conv3x3(out_channels, out_channels)
def forward(self, x):
x = self.maxpool(x)
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
return x
class UpConvBlock(nn.Module):
def __init__(self, in_channels, out_channels):
"""
Args:
in_channels: number of channels in input (1st) feature map
out_channels: number of channels in output feature maps
"""
super(UpConvBlock, self).__init__()
self.upconv = UpConv2x2(in_channels)
self.conv1 = conv3x3(in_channels, out_channels)
self.conv2 = conv3x3(out_channels, out_channels)
self.conv3 = conv3x3(out_channels, out_channels)
def forward(self, xh, xv):
"""
Args:
xh: torch Variable, activations from same resolution feature maps (gray arrow in diagram)
xv: torch Variable, activations from lower resolution feature maps (green arrow in diagram)
"""
xv = self.upconv(xv)
x = concat(xh, xv)
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.relu(self.conv3(x))
return x
class UNet(nn.Module):
def __init__(self):
super(UNet, self).__init__()
fs = [16,32,64,128,256]
self.conv_in = ConvBlock(1, fs[0])
self.dconv1 = DownConvBlock(fs[0], fs[1])
self.dconv2 = DownConvBlock(fs[1], fs[2])
self.dconv3 = DownConvBlock(fs[2], fs[3])
self.dconv4 = DownConvBlock(fs[3], fs[4])
self.uconv1 = UpConvBlock(fs[4], fs[3])
self.uconv2 = UpConvBlock(fs[3], fs[2])
self.uconv3 = UpConvBlock(fs[2], fs[1])
self.uconv4 = UpConvBlock(fs[1], fs[0])
self.conv_out = conv3x3(fs[0], 2)
self._initialize_weights()
def forward(self, x):
x1 = self.conv_in(x)
x2 = self.dconv1(x1)
x3 = self.dconv2(x2)
x4 = self.dconv3(x3)
x5 = self.dconv4(x4)
x6 = self.uconv1(x4, x5)
x7 = self.uconv2(x3, x6)
x8 = self.uconv3(x2, x7)
x9 = self.uconv4(x1, x8)
x10 = self.conv_out(x9)
return x10
def _initialize_weights(self):
conv_modules = [m for m in self.modules() if isinstance(m, nn.Conv2d)]
for m in conv_modules:
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, np.sqrt(2. / n))
| [
"torch.load",
"torch.nn.Conv2d",
"utilities.helpers.load_model_from_dict",
"torch.cat",
"torch.nn.MaxPool2d",
"torch.nn.functional.interpolate",
"numpy.sqrt",
"torch.nn.functional.pad"
] | [((1812, 1899), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)', 'bias': '(True)'}), '(in_channels, out_channels, kernel_size=3, stride=1, padding=1,\n bias=True)\n', (1821, 1899), True, 'import torch.nn as nn\n'), ((1948, 1996), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'padding': '(0)'}), '(kernel_size=2, stride=2, padding=0)\n', (1960, 1996), True, 'import torch.nn as nn\n'), ((2412, 2438), 'torch.cat', 'torch.cat', (['[xh, xv]'], {'dim': '(1)'}), '([xh, xv], dim=1)\n', (2421, 2438), False, 'import torch\n'), ((822, 864), 'utilities.helpers.load_model_from_dict', 'load_model_from_dict', (['self.encode', 'weights'], {}), '(self.encode, weights)\n', (842, 864), False, 'from utilities.helpers import load_model_from_dict\n'), ((2123, 2209), 'torch.nn.Conv2d', 'nn.Conv2d', (['channels', '(channels // 2)'], {'kernel_size': '(2)', 'stride': '(1)', 'padding': '(0)', 'bias': '(True)'}), '(channels, channels // 2, kernel_size=2, stride=1, padding=0, bias\n =True)\n', (2132, 2209), True, 'import torch.nn as nn\n'), ((2256, 2304), 'torch.nn.functional.interpolate', 'F.interpolate', (['x'], {'scale_factor': '(2)', 'mode': '"""nearest"""'}), "(x, scale_factor=2, mode='nearest')\n", (2269, 2304), True, 'import torch.nn.functional as F\n'), ((2317, 2339), 'torch.nn.functional.pad', 'F.pad', (['x', '(0, 1, 0, 1)'], {}), '(x, (0, 1, 0, 1))\n', (2322, 2339), True, 'import torch.nn.functional as F\n'), ((800, 813), 'torch.load', 'torch.load', (['f'], {}), '(f)\n', (810, 813), False, 'import torch\n'), ((5966, 5982), 'numpy.sqrt', 'np.sqrt', (['(2.0 / n)'], {}), '(2.0 / n)\n', (5973, 5982), True, 'import numpy as np\n')] |
from PIL import Image
import numpy as np
import os
import re
import cv2
import shutil
import random
def get_all_images_in_folder(train_folder,test_folder):
images = []
dataCounter = 1
random.seed(1)
#Train - Tumour
for directory in sorted(os.listdir(train_folder)):
print (directory)
if "TCGA" in directory:
for filename in sorted(os.listdir(os.path.join(train_folder,directory))):
if not("mask" in filename):
imgInput = cv2.imread(os.path.join(train_folder,directory,filename))
imgMask = cv2.imread(os.path.join(train_folder,directory,filename[:-4]+"_mask.tif"))
if imgInput is not None and imgMask is not None:
imgInput = cv2.resize(imgInput, (64, 64), interpolation = cv2.INTER_AREA)
suffixInput = "input"
imgMask = cv2.resize(imgMask, (64, 64), interpolation = cv2.INTER_AREA)
ret,imgMask = cv2.threshold(imgMask,70,1,cv2.THRESH_BINARY)
suffixMask = "label"
print(imgInput.shape, filename, imgInput.max())
print(imgMask.shape, filename+"_mask", imgMask.max())
nonZeroCount = np.count_nonzero(imgMask)/np.size(imgMask)
if (nonZeroCount < 0.03): #removing images that dont have tumour
continue
imgMask = imgMask[:, :, 0]
images.append([str(dataCounter) + "_" + suffixInput,imgInput,str(dataCounter) + "_" + suffixMask,imgMask])
dataCounter += 1
totalImages = len(images)
print (totalImages)
random.shuffle(images)
for i in range(0,int(0.7 * totalImages)):
np.save("../dataset/Train/" + images[i][0], images[i][1])
np.save("../dataset/Train/" + images[i][2], images[i][3])
for i in range(int(0.7 * totalImages),int(0.85 * totalImages)):
np.save("../dataset/Valid/" + images[i][0], images[i][1])
np.save("../dataset/Valid/" + images[i][2], images[i][3])
images = []
dataCounter = 1
#Test - Chest XRAY
for directory in sorted(os.listdir(test_folder)):
print (directory)
if "images" in directory:
for filename in sorted(os.listdir(os.path.join(test_folder,directory))):
if not("mask" in filename):
imgInput = cv2.imread(os.path.join(test_folder,directory,filename))
imgMask = cv2.imread(os.path.join(test_folder,"masks",filename[:-4]+"_mask.png"))
if imgInput is not None and imgMask is not None:
imgInput = cv2.resize(imgInput, (64, 64), interpolation = cv2.INTER_AREA)
suffixInput = "input"
imgMask = cv2.resize(imgMask, (64, 64), interpolation = cv2.INTER_AREA)
ret,imgMask = cv2.threshold(imgMask,70,1,cv2.THRESH_BINARY)
suffixMask = "label"
print(imgInput.shape, filename, imgInput.max())
print(imgMask.shape, filename+"_mask", imgMask.max())
nonZeroCount = np.count_nonzero(imgMask)/np.size(imgMask)
if (nonZeroCount < 0.03): #removing images that dont have lung
continue
imgMask = imgMask[:, :, 0]
images.append([str(dataCounter) + "_" + suffixInput,imgInput,str(dataCounter) + "_" + suffixMask,imgMask])
dataCounter += 1
totalImages = len(images)
print (totalImages)
random.shuffle(images)
for i in range(int(0.85 * totalImages),int(totalImages)):
np.save("../dataset/Test/" + images[i][0], images[i][1])
np.save("../dataset/Test/" + images[i][2], images[i][3])
for root, dirs, files in os.walk('../dataset/Train/'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk('../dataset/Test/'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk('../dataset/Valid/'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk('../network'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
get_all_images_in_folder("/home.ORIG/npochhi/kaggle_3m/","/home.ORIG/npochhi/Lung Segmentation/")
'''
Replace the path in the above method call with path to Lgg_Mri_Segmentation/kaggle_3m/ folder, Lung_Segmentation/ folder
''' | [
"numpy.size",
"numpy.save",
"numpy.count_nonzero",
"random.shuffle",
"cv2.threshold",
"os.walk",
"random.seed",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((3970, 3998), 'os.walk', 'os.walk', (['"""../dataset/Train/"""'], {}), "('../dataset/Train/')\n", (3977, 3998), False, 'import os\n'), ((4150, 4177), 'os.walk', 'os.walk', (['"""../dataset/Test/"""'], {}), "('../dataset/Test/')\n", (4157, 4177), False, 'import os\n'), ((4329, 4357), 'os.walk', 'os.walk', (['"""../dataset/Valid/"""'], {}), "('../dataset/Valid/')\n", (4336, 4357), False, 'import os\n'), ((4509, 4530), 'os.walk', 'os.walk', (['"""../network"""'], {}), "('../network')\n", (4516, 4530), False, 'import os\n'), ((197, 211), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (208, 211), False, 'import random\n'), ((1753, 1775), 'random.shuffle', 'random.shuffle', (['images'], {}), '(images)\n', (1767, 1775), False, 'import random\n'), ((3729, 3751), 'random.shuffle', 'random.shuffle', (['images'], {}), '(images)\n', (3743, 3751), False, 'import random\n'), ((265, 289), 'os.listdir', 'os.listdir', (['train_folder'], {}), '(train_folder)\n', (275, 289), False, 'import os\n'), ((1830, 1887), 'numpy.save', 'np.save', (["('../dataset/Train/' + images[i][0])", 'images[i][1]'], {}), "('../dataset/Train/' + images[i][0], images[i][1])\n", (1837, 1887), True, 'import numpy as np\n'), ((1896, 1953), 'numpy.save', 'np.save', (["('../dataset/Train/' + images[i][2])", 'images[i][3]'], {}), "('../dataset/Train/' + images[i][2], images[i][3])\n", (1903, 1953), True, 'import numpy as np\n'), ((2030, 2087), 'numpy.save', 'np.save', (["('../dataset/Valid/' + images[i][0])", 'images[i][1]'], {}), "('../dataset/Valid/' + images[i][0], images[i][1])\n", (2037, 2087), True, 'import numpy as np\n'), ((2096, 2153), 'numpy.save', 'np.save', (["('../dataset/Valid/' + images[i][2])", 'images[i][3]'], {}), "('../dataset/Valid/' + images[i][2], images[i][3])\n", (2103, 2153), True, 'import numpy as np\n'), ((2247, 2270), 'os.listdir', 'os.listdir', (['test_folder'], {}), '(test_folder)\n', (2257, 2270), False, 'import os\n'), ((3822, 3878), 'numpy.save', 'np.save', (["('../dataset/Test/' + images[i][0])", 'images[i][1]'], {}), "('../dataset/Test/' + images[i][0], images[i][1])\n", (3829, 3878), True, 'import numpy as np\n'), ((3887, 3943), 'numpy.save', 'np.save', (["('../dataset/Test/' + images[i][2])", 'images[i][3]'], {}), "('../dataset/Test/' + images[i][2], images[i][3])\n", (3894, 3943), True, 'import numpy as np\n'), ((4038, 4059), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (4050, 4059), False, 'import os\n'), ((4102, 4123), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (4114, 4123), False, 'import os\n'), ((4217, 4238), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (4229, 4238), False, 'import os\n'), ((4281, 4302), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (4293, 4302), False, 'import os\n'), ((4397, 4418), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (4409, 4418), False, 'import os\n'), ((4461, 4482), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (4473, 4482), False, 'import os\n'), ((4570, 4591), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (4582, 4591), False, 'import os\n'), ((4634, 4655), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (4646, 4655), False, 'import os\n'), ((396, 433), 'os.path.join', 'os.path.join', (['train_folder', 'directory'], {}), '(train_folder, directory)\n', (408, 433), False, 'import os\n'), ((2379, 2415), 'os.path.join', 'os.path.join', (['test_folder', 'directory'], {}), '(test_folder, directory)\n', (2391, 2415), False, 'import os\n'), ((522, 569), 'os.path.join', 'os.path.join', (['train_folder', 'directory', 'filename'], {}), '(train_folder, directory, filename)\n', (534, 569), False, 'import os\n'), ((610, 676), 'os.path.join', 'os.path.join', (['train_folder', 'directory', "(filename[:-4] + '_mask.tif')"], {}), "(train_folder, directory, filename[:-4] + '_mask.tif')\n", (622, 676), False, 'import os\n'), ((778, 838), 'cv2.resize', 'cv2.resize', (['imgInput', '(64, 64)'], {'interpolation': 'cv2.INTER_AREA'}), '(imgInput, (64, 64), interpolation=cv2.INTER_AREA)\n', (788, 838), False, 'import cv2\n'), ((921, 980), 'cv2.resize', 'cv2.resize', (['imgMask', '(64, 64)'], {'interpolation': 'cv2.INTER_AREA'}), '(imgMask, (64, 64), interpolation=cv2.INTER_AREA)\n', (931, 980), False, 'import cv2\n'), ((1021, 1069), 'cv2.threshold', 'cv2.threshold', (['imgMask', '(70)', '(1)', 'cv2.THRESH_BINARY'], {}), '(imgMask, 70, 1, cv2.THRESH_BINARY)\n', (1034, 1069), False, 'import cv2\n'), ((2504, 2550), 'os.path.join', 'os.path.join', (['test_folder', 'directory', 'filename'], {}), '(test_folder, directory, filename)\n', (2516, 2550), False, 'import os\n'), ((2591, 2654), 'os.path.join', 'os.path.join', (['test_folder', '"""masks"""', "(filename[:-4] + '_mask.png')"], {}), "(test_folder, 'masks', filename[:-4] + '_mask.png')\n", (2603, 2654), False, 'import os\n'), ((2756, 2816), 'cv2.resize', 'cv2.resize', (['imgInput', '(64, 64)'], {'interpolation': 'cv2.INTER_AREA'}), '(imgInput, (64, 64), interpolation=cv2.INTER_AREA)\n', (2766, 2816), False, 'import cv2\n'), ((2899, 2958), 'cv2.resize', 'cv2.resize', (['imgMask', '(64, 64)'], {'interpolation': 'cv2.INTER_AREA'}), '(imgMask, (64, 64), interpolation=cv2.INTER_AREA)\n', (2909, 2958), False, 'import cv2\n'), ((2999, 3047), 'cv2.threshold', 'cv2.threshold', (['imgMask', '(70)', '(1)', 'cv2.THRESH_BINARY'], {}), '(imgMask, 70, 1, cv2.THRESH_BINARY)\n', (3012, 3047), False, 'import cv2\n'), ((1301, 1326), 'numpy.count_nonzero', 'np.count_nonzero', (['imgMask'], {}), '(imgMask)\n', (1317, 1326), True, 'import numpy as np\n'), ((1327, 1343), 'numpy.size', 'np.size', (['imgMask'], {}), '(imgMask)\n', (1334, 1343), True, 'import numpy as np\n'), ((3279, 3304), 'numpy.count_nonzero', 'np.count_nonzero', (['imgMask'], {}), '(imgMask)\n', (3295, 3304), True, 'import numpy as np\n'), ((3305, 3321), 'numpy.size', 'np.size', (['imgMask'], {}), '(imgMask)\n', (3312, 3321), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# Copyright (C) 2018 <NAME>
import numpy as np
import crispy as cy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from natsort import natsorted
from scipy.stats import pearsonr
from analysis.DataImporter import DataImporter
def estimate_copynumber_bias(beds):
# - Aggregate by segments
agg_fun = dict(
fold_change=np.mean, gp_mean=np.mean, corrected=np.mean, ceres=np.mean,
copy_number=np.mean, chr_copy=np.mean, ploidy=np.mean, ratio=np.mean, len=np.mean
)
beds_seg = {s: beds[s].groupby(['chr', 'start', 'end']).agg(agg_fun) for s in beds}
# - Aggregate by genes
agg_fun = dict(
fold_change=np.mean, gp_mean=np.mean, corrected=np.mean, copy_number=np.mean, ratio=np.mean, ceres=np.mean
)
beds_gene = {s: beds[s].groupby(['gene']).agg(agg_fun) for s in beds}
# - Copy-number bias
aucs_df = []
for y_label, y_var in [('ceres', 'ceres'), ('original', 'fold_change'), ('corrected', 'corrected')]:
for x_var, x_thres in [('copy_number', 10), ('ratio', 4)]:
for groupby, df in [('segment', beds_seg), ('gene', beds_gene)]:
cn_aucs_df = pd.concat([
cy.QCplot.recall_curve_discretise(
df[s][y_var], df[s][x_var], x_thres
).assign(sample=s) for s in df
])
ax = cy.QCplot.bias_boxplot(cn_aucs_df, x=x_var, notch=False, add_n=True, n_text_y=.05)
ax.set_ylim(0, 1)
ax.axhline(.5, lw=.3, c=cy.QCplot.PAL_DBGD[0], ls=':', zorder=0)
x_label = x_var.replace('_', ' ').capitalize()
plt.xlabel(f'{x_label}')
plt.ylabel(f'AURC (per {groupby})')
plt.title('Copy-number effect on CRISPR-Cas9')
plt.gcf().set_size_inches(3, 3)
plt.savefig(f'reports/gdsc/bias_copynumber_{groupby}_{y_label}_{x_label}.png', bbox_inches='tight', dpi=600)
plt.close('all')
# Export
cn_aucs_df = pd.melt(cn_aucs_df, id_vars=['sample', x_var], value_vars=['auc'])
cn_aucs_df = cn_aucs_df \
.assign(fold_change=y_label) \
.assign(feature=x_var) \
.assign(groupby=groupby) \
.drop(['variable'], axis=1) \
.rename(columns={x_var: 'feature_value', 'value': 'auc'})
aucs_df.append(cn_aucs_df)
aucs_df = pd.concat(aucs_df)
return aucs_df
def copynumber_bias_comparison(cn_bias):
plot_df = cn_bias.query("groupby == 'gene'").query("feature == 'ratio'")
#
order = natsorted(set(plot_df['feature_value']))
pal = pd.Series(cy.QCplot.get_palette_continuous(len(order)), index=order)
#
aucs_mean = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=np.median
).loc[order]
aucs_mean = aucs_mean.assign(copy_number=aucs_mean.index)
aucs_perc_down = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=lambda v: np.percentile(v, 25)
).loc[order]
aucs_perc_down = aucs_perc_down.assign(copy_number=aucs_perc_down.index)
aucs_perc_up = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=lambda v: np.percentile(v, 75)
).loc[order]
aucs_perc_up = aucs_perc_up.assign(copy_number=aucs_perc_up.index)
#
for i in reversed(order):
x, y = aucs_mean.loc[i, 'original'], aucs_mean.loc[i, 'corrected']
y_err_min, y_err_max = aucs_perc_down.loc[i, 'corrected'], aucs_perc_up.loc[i, 'corrected']
yerr = np.array([y - y_err_min, y_err_max - y]).reshape(2, -1)
x_err_min, x_err_max = aucs_perc_down.loc[i, 'original'], aucs_perc_up.loc[i, 'original']
xerr = np.array([x - x_err_min, x_err_max - x]).reshape(2, -1)
plt.errorbar(x, y, yerr=yerr, xerr=xerr, c=pal[i], label=i, fmt='o', lw=.3)
plt.xlim((None, 1))
plt.ylim((None, 1))
(x0, x1), (y0, y1) = plt.xlim(), plt.ylim()
lims = [max(x0, y0), min(x1, y1)]
plt.plot(lims, lims, lw=.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])
plt.axhline(0.5, ls=':', lw=.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)
plt.axvline(0.5, ls=':', lw=.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)
plt.legend(title='Copy-number ratio', loc=2, frameon=False, prop={'size': 6})\
.get_title().set_fontsize('6')
plt.xlabel('Original fold-changes\ncopy-number AURC')
plt.ylabel('Crispy corrected fold-changes\ncopy-number AURC')
plt.title('Copy-number enrichment\ncorrection')
def essential_aurc(beds_gene):
essential = cy.Utils.get_essential_genes(return_series=False)
ess_aurcs = pd.DataFrame({
s: {f: cy.QCplot.recall_curve(beds_gene[s][f], essential)[2] for f in list(beds_gene[s])} for s in beds_gene
}).T
return ess_aurcs
def essential_recall_comparison(ess_aurcs):
plt.scatter(ess_aurcs['ceres'], ess_aurcs['corrected'], color=cy.QCplot.PAL_DBGD[0], alpha=.7, lw=.1, edgecolors='white')
(x0, x1), (y0, y1) = plt.xlim(), plt.ylim()
lims = [max(x0, y0), min(x1, y1)]
plt.plot(lims, lims, lw=.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])
plt.xlabel('CERES\nessential genes AURC')
plt.ylabel('Crispy\nessential genes AURC')
plt.title('Essential genes recall')
def essential_replicates(ess_aurcs, rep_corr):
plot_df = pd.concat([
ess_aurcs.eval('ceres - corrected').rename('ceres'),
rep_corr.groupby('name_1')['corr'].mean()
], axis=1, sort=False).dropna()
scatter_kws = dict(edgecolor='w', lw=.3, s=10, alpha=.6)
line_kws = dict(lw=1., color=cy.QCplot.PAL_DBGD[1], alpha=1.)
joint_kws = dict(lowess=False, scatter_kws=scatter_kws, line_kws=line_kws)
marginal_kws = dict(kde=False, hist_kws={'linewidth': 0})
annot_kws = dict(stat='R')
g = sns.jointplot(
'ceres', 'corr', data=plot_df, kind='reg', space=0, color=cy.QCplot.PAL_DBGD[0],
marginal_kws=marginal_kws, annot_kws=annot_kws, joint_kws=joint_kws
)
g.annotate(pearsonr, template='R={val:.2g}, p={p:.1e}', frameon=False)
g.set_axis_labels('CERES\nessential genes recall gain', 'Replicates correlation\n(mean Pearson)')
def similarity_original(beds_gene, xlim=None, ylim=None):
plot_df = pd.DataFrame({s: beds_gene[s].corr().iloc[0, :] for s in beds_gene}).drop(['fold_change']).T
plt.scatter(plot_df['ceres'], plot_df['corrected'], c=cy.QCplot.PAL_DBGD[0], alpha=.7, lw=.1, edgecolors='white')
if xlim is not None:
plt.xlim(xlim)
if ylim is not None:
plt.ylim(ylim)
(x0, x1), (y0, y1) = plt.xlim(), plt.ylim()
lims = [max(x0, y0), min(x1, y1)]
plt.plot(lims, lims, lw=.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])
plt.xlabel('CERES scores\ncorrelation with original')
plt.ylabel('Crispy scores\ncorrelation with original')
plt.title('Similarity with original fold-changes')
def aupr_comparison(aucs):
plot_df = aucs.query("groupby == 'gene'").query("feature == 'ratio'")
#
order = natsorted(set(plot_df['feature_value']))
pal = pd.Series(cy.QCplot.get_palette_continuous(len(order)), index=order)
#
aucs_mean = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=np.median
).loc[order]
aucs_mean = aucs_mean.assign(copy_number=aucs_mean.index)
aucs_perc_down = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=lambda v: np.percentile(v, 25)
).loc[order]
aucs_perc_down = aucs_perc_down.assign(copy_number=aucs_perc_down.index)
aucs_perc_up = pd.pivot_table(
plot_df, index='feature_value', columns='fold_change', values='auc', aggfunc=lambda v: np.percentile(v, 75)
).loc[order]
aucs_perc_up = aucs_perc_up.assign(copy_number=aucs_perc_up.index)
#
for i in reversed(order):
x, y = aucs_mean.loc[i, 'ceres'], aucs_mean.loc[i, 'corrected']
y_err_min, y_err_max = aucs_perc_down.loc[i, 'corrected'], aucs_perc_up.loc[i, 'corrected']
yerr = np.array([y - y_err_min, y_err_max - y]).reshape(2, -1)
x_err_min, x_err_max = aucs_perc_down.loc[i, 'ceres'], aucs_perc_up.loc[i, 'ceres']
xerr = np.array([x - x_err_min, x_err_max - x]).reshape(2, -1)
plt.errorbar(x, y, yerr=yerr, xerr=xerr, c=pal[i], label=i, fmt='o', lw=.3)
plt.xlim((None, .8))
plt.ylim((None, .8))
(x0, x1), (y0, y1) = plt.xlim(), plt.ylim()
lims = [max(x0, y0), min(x1, y1)]
plt.plot(lims, lims, lw=.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])
plt.axhline(0.5, ls=':', lw=.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)
plt.axvline(0.5, ls=':', lw=.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)
plt.legend(title='Copy-number ratio', loc=2, frameon=False, prop={'size': 6})\
.get_title().set_fontsize('6')
plt.xlabel('CERES\ncopy-number AURC')
plt.ylabel('Crispy\ncopy-number AURC')
plt.title('Copy-number enrichment')
if __name__ == '__main__':
# - Import data
data = DataImporter()
beds = data.get_crispy_beds()
# - Add CERES gene scores to bed
ceres = data.get_ceres_scores()
beds = {s: beds[s].assign(ceres=ceres.loc[beds[s]['gene'], s].values) for s in beds}
# - Replicates correlation
replicates_corr = pd.read_csv('data/analysis/replicates_correlation_sgrna_fc.csv').query('replicate == 1')
# - Bias
aucs_df = estimate_copynumber_bias(beds)
aucs_df.to_csv('data/analysis/copynumber_bias_aurc.csv', index=False)
qc_aucs = pd.read_csv('data/analysis/gene_ess_ness_aucs.csv')
# - Aggregate by genes
agg_fun = dict(fold_change=np.mean, corrected=np.mean, ceres=np.mean)
beds_gene = {s: beds[s].groupby(['gene']).agg(agg_fun) for s in beds}
# - Essential AURCs
ess_aurcs = essential_aurc(beds_gene)
# - Plotting
# Essential genes recall capacity comparison
essential_recall_comparison(ess_aurcs)
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_ceres_essentiality.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Essential genes recall gain comparison with replicates correlation
essential_replicates(ess_aurcs, replicates_corr)
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_ceres_replicates.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Similarity of corrected fold-changes compared to original fold-changes
similarity_original(beds_gene, xlim=(0.85, 1.02), ylim=(0.85, 1.02))
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_ceres_similarity.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Comparison of correction AURCs
aupr_comparison(aucs_df)
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_ceres_aucs.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Gene copy-number ratio bias boxplots CERES
plot_df = aucs_df.query("groupby == 'gene'").query("feature == 'ratio'").query("fold_change == 'ceres'")
ax = cy.QCplot.bias_boxplot(plot_df, x='feature_value', y='auc', notch=True, add_n=True, n_text_y=.05)
ax.set_ylim(0, 1)
ax.axhline(.5, lw=.3, c=cy.QCplot.PAL_DBGD[0], ls=':', zorder=0)
plt.xlabel('Copy-number ratio')
plt.ylabel(f'AURC (per cell line)')
plt.title('Copy-number effect on CRISPR-Cas9\nCERES corrected')
plt.gcf().set_size_inches(2, 3)
plt.savefig(f'reports/analysis/comparison_aucs_ceres_boxplots.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Gene copy-number ratio bias boxplots Crispy
plot_df = aucs_df.query("groupby == 'gene'").query("feature == 'ratio'").query("fold_change == 'corrected'")
ax = cy.QCplot.bias_boxplot(plot_df, x='feature_value', y='auc', notch=True, add_n=True, n_text_y=.05)
ax.set_ylim(0, 1)
ax.axhline(.5, lw=.3, c=cy.QCplot.PAL_DBGD[0], ls=':', zorder=0)
plt.xlabel('Copy-number ratio')
plt.ylabel(f'AURC (per cell line)')
plt.title('Copy-number effect on CRISPR-Cas9\nCrispy corrected')
plt.gcf().set_size_inches(2, 3)
plt.savefig(f'reports/analysis/comparison_crispy_boxplots.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Essential AURCs comparison
plot_df = qc_aucs.query("geneset == 'essential'")
plot_df = pd.pivot_table(plot_df, index='sample', columns='type', values='aurc')
plt.scatter(plot_df['original'], plot_df['corrected'], c=cy.QCplot.PAL_DBGD[0], alpha=.7, lw=.1, edgecolors='white')
(x0, x1), (y0, y1) = plt.xlim(), plt.ylim()
lims = [max(x0, y0), min(x1, y1)]
plt.plot(lims, lims, lw=.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])
plt.xlabel('Original fold-changes')
plt.ylabel('Crispy corrected fold-changes')
plt.title('AURCs of essential genes')
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_essential_aucs.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
# Copy-number bias comparison
copynumber_bias_comparison(aucs_df)
plt.gcf().set_size_inches(2, 2)
plt.savefig(f'reports/analysis/comparison_copynumber_bias.pdf', bbox_inches='tight', transparent=True)
plt.close('all')
#
plot_df = pd.pivot_table(
aucs_df.query("feature == 'ratio'"),
index=['sample', 'feature_value'], columns=['fold_change'], values='auc'
)
plot_df = plot_df.eval('original - corrected').rename('diff').sort_values().to_frame().reset_index()
plot_df['cancer_type'] = data.samplesheet.loc[plot_df['sample'], 'Cancer Type'].values
#
samples_replicates = pd.read_csv(f'data/analysis/replicates_correlation_gene_fc.csv').query('replicate == 1')
supmaterial = pd.concat([
data.samplesheet[['COSMIC ID', 'Tissue', 'Cancer Type', 'TCGA', 'CCLE ID']],
pd.Series({c: beds[c]['ploidy'].mean().round(5) for c in data.samples}).rename('ploidy'),
samples_replicates.groupby('name_1')['corr'].mean().rename('replicate_corr')
], axis=1, sort=False).sort_values('Tissue')
| [
"matplotlib.pyplot.title",
"pandas.pivot_table",
"pandas.read_csv",
"crispy.QCplot.bias_boxplot",
"crispy.QCplot.recall_curve",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.close",
"crispy.QCplot.recall_curve_discretise",
"pandas.concat",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.axhli... | [((2537, 2555), 'pandas.concat', 'pd.concat', (['aucs_df'], {}), '(aucs_df)\n', (2546, 2555), True, 'import pandas as pd\n'), ((4079, 4098), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(None, 1)'], {}), '((None, 1))\n', (4087, 4098), True, 'import matplotlib.pyplot as plt\n'), ((4103, 4122), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(None, 1)'], {}), '((None, 1))\n', (4111, 4122), True, 'import matplotlib.pyplot as plt\n'), ((4214, 4289), 'matplotlib.pyplot.plot', 'plt.plot', (['lims', 'lims'], {'lw': '(0.5)', 'zorder': '(0)', 'ls': '""":"""', 'color': 'cy.QCplot.PAL_DBGD[2]'}), "(lims, lims, lw=0.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])\n", (4222, 4289), True, 'import matplotlib.pyplot as plt\n'), ((4294, 4365), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(0.5)'], {'ls': '""":"""', 'lw': '(0.5)', 'color': 'cy.QCplot.PAL_DBGD[2]', 'zorder': '(0)'}), "(0.5, ls=':', lw=0.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)\n", (4305, 4365), True, 'import matplotlib.pyplot as plt\n'), ((4369, 4440), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(0.5)'], {'ls': '""":"""', 'lw': '(0.5)', 'color': 'cy.QCplot.PAL_DBGD[2]', 'zorder': '(0)'}), "(0.5, ls=':', lw=0.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)\n", (4380, 4440), True, 'import matplotlib.pyplot as plt\n'), ((4568, 4624), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Original fold-changes\ncopy-number AURC"""'], {}), '("""Original fold-changes\ncopy-number AURC""")\n', (4578, 4624), True, 'import matplotlib.pyplot as plt\n'), ((4626, 4690), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Crispy corrected fold-changes\ncopy-number AURC"""'], {}), '("""Crispy corrected fold-changes\ncopy-number AURC""")\n', (4636, 4690), True, 'import matplotlib.pyplot as plt\n'), ((4692, 4742), 'matplotlib.pyplot.title', 'plt.title', (['"""Copy-number enrichment\ncorrection"""'], {}), '("""Copy-number enrichment\ncorrection""")\n', (4701, 4742), True, 'import matplotlib.pyplot as plt\n'), ((4789, 4838), 'crispy.Utils.get_essential_genes', 'cy.Utils.get_essential_genes', ([], {'return_series': '(False)'}), '(return_series=False)\n', (4817, 4838), True, 'import crispy as cy\n'), ((5069, 5197), 'matplotlib.pyplot.scatter', 'plt.scatter', (["ess_aurcs['ceres']", "ess_aurcs['corrected']"], {'color': 'cy.QCplot.PAL_DBGD[0]', 'alpha': '(0.7)', 'lw': '(0.1)', 'edgecolors': '"""white"""'}), "(ess_aurcs['ceres'], ess_aurcs['corrected'], color=cy.QCplot.\n PAL_DBGD[0], alpha=0.7, lw=0.1, edgecolors='white')\n", (5080, 5197), True, 'import matplotlib.pyplot as plt\n'), ((5282, 5357), 'matplotlib.pyplot.plot', 'plt.plot', (['lims', 'lims'], {'lw': '(0.5)', 'zorder': '(0)', 'ls': '""":"""', 'color': 'cy.QCplot.PAL_DBGD[2]'}), "(lims, lims, lw=0.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])\n", (5290, 5357), True, 'import matplotlib.pyplot as plt\n'), ((5362, 5406), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""CERES\nessential genes AURC"""'], {}), '("""CERES\nessential genes AURC""")\n', (5372, 5406), True, 'import matplotlib.pyplot as plt\n'), ((5408, 5453), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Crispy\nessential genes AURC"""'], {}), '("""Crispy\nessential genes AURC""")\n', (5418, 5453), True, 'import matplotlib.pyplot as plt\n'), ((5455, 5490), 'matplotlib.pyplot.title', 'plt.title', (['"""Essential genes recall"""'], {}), "('Essential genes recall')\n", (5464, 5490), True, 'import matplotlib.pyplot as plt\n'), ((6022, 6194), 'seaborn.jointplot', 'sns.jointplot', (['"""ceres"""', '"""corr"""'], {'data': 'plot_df', 'kind': '"""reg"""', 'space': '(0)', 'color': 'cy.QCplot.PAL_DBGD[0]', 'marginal_kws': 'marginal_kws', 'annot_kws': 'annot_kws', 'joint_kws': 'joint_kws'}), "('ceres', 'corr', data=plot_df, kind='reg', space=0, color=cy.\n QCplot.PAL_DBGD[0], marginal_kws=marginal_kws, annot_kws=annot_kws,\n joint_kws=joint_kws)\n", (6035, 6194), True, 'import seaborn as sns\n'), ((6559, 6678), 'matplotlib.pyplot.scatter', 'plt.scatter', (["plot_df['ceres']", "plot_df['corrected']"], {'c': 'cy.QCplot.PAL_DBGD[0]', 'alpha': '(0.7)', 'lw': '(0.1)', 'edgecolors': '"""white"""'}), "(plot_df['ceres'], plot_df['corrected'], c=cy.QCplot.PAL_DBGD[0],\n alpha=0.7, lw=0.1, edgecolors='white')\n", (6570, 6678), True, 'import matplotlib.pyplot as plt\n'), ((6862, 6937), 'matplotlib.pyplot.plot', 'plt.plot', (['lims', 'lims'], {'lw': '(0.5)', 'zorder': '(0)', 'ls': '""":"""', 'color': 'cy.QCplot.PAL_DBGD[2]'}), "(lims, lims, lw=0.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])\n", (6870, 6937), True, 'import matplotlib.pyplot as plt\n'), ((6942, 6998), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""CERES scores\ncorrelation with original"""'], {}), '("""CERES scores\ncorrelation with original""")\n', (6952, 6998), True, 'import matplotlib.pyplot as plt\n'), ((7000, 7057), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Crispy scores\ncorrelation with original"""'], {}), '("""Crispy scores\ncorrelation with original""")\n', (7010, 7057), True, 'import matplotlib.pyplot as plt\n'), ((7059, 7109), 'matplotlib.pyplot.title', 'plt.title', (['"""Similarity with original fold-changes"""'], {}), "('Similarity with original fold-changes')\n", (7068, 7109), True, 'import matplotlib.pyplot as plt\n'), ((8588, 8609), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(None, 0.8)'], {}), '((None, 0.8))\n', (8596, 8609), True, 'import matplotlib.pyplot as plt\n'), ((8613, 8634), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(None, 0.8)'], {}), '((None, 0.8))\n', (8621, 8634), True, 'import matplotlib.pyplot as plt\n'), ((8725, 8800), 'matplotlib.pyplot.plot', 'plt.plot', (['lims', 'lims'], {'lw': '(0.5)', 'zorder': '(0)', 'ls': '""":"""', 'color': 'cy.QCplot.PAL_DBGD[2]'}), "(lims, lims, lw=0.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])\n", (8733, 8800), True, 'import matplotlib.pyplot as plt\n'), ((8805, 8876), 'matplotlib.pyplot.axhline', 'plt.axhline', (['(0.5)'], {'ls': '""":"""', 'lw': '(0.5)', 'color': 'cy.QCplot.PAL_DBGD[2]', 'zorder': '(0)'}), "(0.5, ls=':', lw=0.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)\n", (8816, 8876), True, 'import matplotlib.pyplot as plt\n'), ((8880, 8951), 'matplotlib.pyplot.axvline', 'plt.axvline', (['(0.5)'], {'ls': '""":"""', 'lw': '(0.5)', 'color': 'cy.QCplot.PAL_DBGD[2]', 'zorder': '(0)'}), "(0.5, ls=':', lw=0.5, color=cy.QCplot.PAL_DBGD[2], zorder=0)\n", (8891, 8951), True, 'import matplotlib.pyplot as plt\n'), ((9079, 9119), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""CERES\ncopy-number AURC"""'], {}), '("""CERES\ncopy-number AURC""")\n', (9089, 9119), True, 'import matplotlib.pyplot as plt\n'), ((9121, 9162), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Crispy\ncopy-number AURC"""'], {}), '("""Crispy\ncopy-number AURC""")\n', (9131, 9162), True, 'import matplotlib.pyplot as plt\n'), ((9164, 9199), 'matplotlib.pyplot.title', 'plt.title', (['"""Copy-number enrichment"""'], {}), "('Copy-number enrichment')\n", (9173, 9199), True, 'import matplotlib.pyplot as plt\n'), ((9260, 9274), 'analysis.DataImporter.DataImporter', 'DataImporter', ([], {}), '()\n', (9272, 9274), False, 'from analysis.DataImporter import DataImporter\n'), ((9763, 9814), 'pandas.read_csv', 'pd.read_csv', (['"""data/analysis/gene_ess_ness_aucs.csv"""'], {}), "('data/analysis/gene_ess_ness_aucs.csv')\n", (9774, 9814), True, 'import pandas as pd\n'), ((10208, 10317), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_ceres_essentiality.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_ceres_essentiality.pdf',\n bbox_inches='tight', transparent=True)\n", (10219, 10317), True, 'import matplotlib.pyplot as plt\n'), ((10318, 10334), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (10327, 10334), True, 'import matplotlib.pyplot as plt\n'), ((10502, 10609), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_ceres_replicates.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_ceres_replicates.pdf',\n bbox_inches='tight', transparent=True)\n", (10513, 10609), True, 'import matplotlib.pyplot as plt\n'), ((10610, 10626), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (10619, 10626), True, 'import matplotlib.pyplot as plt\n'), ((10818, 10925), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_ceres_similarity.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_ceres_similarity.pdf',\n bbox_inches='tight', transparent=True)\n", (10829, 10925), True, 'import matplotlib.pyplot as plt\n'), ((10926, 10942), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (10935, 10942), True, 'import matplotlib.pyplot as plt\n'), ((11050, 11152), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_ceres_aucs.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_ceres_aucs.pdf', bbox_inches=\n 'tight', transparent=True)\n", (11061, 11152), True, 'import matplotlib.pyplot as plt\n'), ((11152, 11168), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (11161, 11168), True, 'import matplotlib.pyplot as plt\n'), ((11338, 11440), 'crispy.QCplot.bias_boxplot', 'cy.QCplot.bias_boxplot', (['plot_df'], {'x': '"""feature_value"""', 'y': '"""auc"""', 'notch': '(True)', 'add_n': '(True)', 'n_text_y': '(0.05)'}), "(plot_df, x='feature_value', y='auc', notch=True,\n add_n=True, n_text_y=0.05)\n", (11360, 11440), True, 'import crispy as cy\n'), ((11533, 11564), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Copy-number ratio"""'], {}), "('Copy-number ratio')\n", (11543, 11564), True, 'import matplotlib.pyplot as plt\n'), ((11569, 11604), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""AURC (per cell line)"""'], {}), "(f'AURC (per cell line)')\n", (11579, 11604), True, 'import matplotlib.pyplot as plt\n'), ((11609, 11675), 'matplotlib.pyplot.title', 'plt.title', (['"""Copy-number effect on CRISPR-Cas9\nCERES corrected"""'], {}), '("""Copy-number effect on CRISPR-Cas9\nCERES corrected""")\n', (11618, 11675), True, 'import matplotlib.pyplot as plt\n'), ((11714, 11824), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_aucs_ceres_boxplots.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_aucs_ceres_boxplots.pdf',\n bbox_inches='tight', transparent=True)\n", (11725, 11824), True, 'import matplotlib.pyplot as plt\n'), ((11825, 11841), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (11834, 11841), True, 'import matplotlib.pyplot as plt\n'), ((12016, 12118), 'crispy.QCplot.bias_boxplot', 'cy.QCplot.bias_boxplot', (['plot_df'], {'x': '"""feature_value"""', 'y': '"""auc"""', 'notch': '(True)', 'add_n': '(True)', 'n_text_y': '(0.05)'}), "(plot_df, x='feature_value', y='auc', notch=True,\n add_n=True, n_text_y=0.05)\n", (12038, 12118), True, 'import crispy as cy\n'), ((12211, 12242), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Copy-number ratio"""'], {}), "('Copy-number ratio')\n", (12221, 12242), True, 'import matplotlib.pyplot as plt\n'), ((12247, 12282), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""AURC (per cell line)"""'], {}), "(f'AURC (per cell line)')\n", (12257, 12282), True, 'import matplotlib.pyplot as plt\n'), ((12287, 12354), 'matplotlib.pyplot.title', 'plt.title', (['"""Copy-number effect on CRISPR-Cas9\nCrispy corrected"""'], {}), '("""Copy-number effect on CRISPR-Cas9\nCrispy corrected""")\n', (12296, 12354), True, 'import matplotlib.pyplot as plt\n'), ((12393, 12500), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_crispy_boxplots.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_crispy_boxplots.pdf', bbox_inches\n ='tight', transparent=True)\n", (12404, 12500), True, 'import matplotlib.pyplot as plt\n'), ((12500, 12516), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (12509, 12516), True, 'import matplotlib.pyplot as plt\n'), ((12619, 12689), 'pandas.pivot_table', 'pd.pivot_table', (['plot_df'], {'index': '"""sample"""', 'columns': '"""type"""', 'values': '"""aurc"""'}), "(plot_df, index='sample', columns='type', values='aurc')\n", (12633, 12689), True, 'import pandas as pd\n'), ((12695, 12818), 'matplotlib.pyplot.scatter', 'plt.scatter', (["plot_df['original']", "plot_df['corrected']"], {'c': 'cy.QCplot.PAL_DBGD[0]', 'alpha': '(0.7)', 'lw': '(0.1)', 'edgecolors': '"""white"""'}), "(plot_df['original'], plot_df['corrected'], c=cy.QCplot.PAL_DBGD\n [0], alpha=0.7, lw=0.1, edgecolors='white')\n", (12706, 12818), True, 'import matplotlib.pyplot as plt\n'), ((12903, 12978), 'matplotlib.pyplot.plot', 'plt.plot', (['lims', 'lims'], {'lw': '(0.5)', 'zorder': '(0)', 'ls': '""":"""', 'color': 'cy.QCplot.PAL_DBGD[2]'}), "(lims, lims, lw=0.5, zorder=0, ls=':', color=cy.QCplot.PAL_DBGD[2])\n", (12911, 12978), True, 'import matplotlib.pyplot as plt\n'), ((12983, 13018), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Original fold-changes"""'], {}), "('Original fold-changes')\n", (12993, 13018), True, 'import matplotlib.pyplot as plt\n'), ((13023, 13066), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Crispy corrected fold-changes"""'], {}), "('Crispy corrected fold-changes')\n", (13033, 13066), True, 'import matplotlib.pyplot as plt\n'), ((13071, 13108), 'matplotlib.pyplot.title', 'plt.title', (['"""AURCs of essential genes"""'], {}), "('AURCs of essential genes')\n", (13080, 13108), True, 'import matplotlib.pyplot as plt\n'), ((13150, 13256), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_essential_aucs.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_essential_aucs.pdf', bbox_inches=\n 'tight', transparent=True)\n", (13161, 13256), True, 'import matplotlib.pyplot as plt\n'), ((13256, 13272), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (13265, 13272), True, 'import matplotlib.pyplot as plt\n'), ((13388, 13495), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/analysis/comparison_copynumber_bias.pdf"""'], {'bbox_inches': '"""tight"""', 'transparent': '(True)'}), "(f'reports/analysis/comparison_copynumber_bias.pdf', bbox_inches\n ='tight', transparent=True)\n", (13399, 13495), True, 'import matplotlib.pyplot as plt\n'), ((13495, 13511), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (13504, 13511), True, 'import matplotlib.pyplot as plt\n'), ((3998, 4074), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['x', 'y'], {'yerr': 'yerr', 'xerr': 'xerr', 'c': 'pal[i]', 'label': 'i', 'fmt': '"""o"""', 'lw': '(0.3)'}), "(x, y, yerr=yerr, xerr=xerr, c=pal[i], label=i, fmt='o', lw=0.3)\n", (4010, 4074), True, 'import matplotlib.pyplot as plt\n'), ((4149, 4159), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (4157, 4159), True, 'import matplotlib.pyplot as plt\n'), ((4161, 4171), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (4169, 4171), True, 'import matplotlib.pyplot as plt\n'), ((5217, 5227), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (5225, 5227), True, 'import matplotlib.pyplot as plt\n'), ((5229, 5239), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (5237, 5239), True, 'import matplotlib.pyplot as plt\n'), ((6707, 6721), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xlim'], {}), '(xlim)\n', (6715, 6721), True, 'import matplotlib.pyplot as plt\n'), ((6756, 6770), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ylim'], {}), '(ylim)\n', (6764, 6770), True, 'import matplotlib.pyplot as plt\n'), ((6797, 6807), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (6805, 6807), True, 'import matplotlib.pyplot as plt\n'), ((6809, 6819), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (6817, 6819), True, 'import matplotlib.pyplot as plt\n'), ((8507, 8583), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['x', 'y'], {'yerr': 'yerr', 'xerr': 'xerr', 'c': 'pal[i]', 'label': 'i', 'fmt': '"""o"""', 'lw': '(0.3)'}), "(x, y, yerr=yerr, xerr=xerr, c=pal[i], label=i, fmt='o', lw=0.3)\n", (8519, 8583), True, 'import matplotlib.pyplot as plt\n'), ((8660, 8670), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (8668, 8670), True, 'import matplotlib.pyplot as plt\n'), ((8672, 8682), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (8680, 8682), True, 'import matplotlib.pyplot as plt\n'), ((12838, 12848), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (12846, 12848), True, 'import matplotlib.pyplot as plt\n'), ((12850, 12860), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (12858, 12860), True, 'import matplotlib.pyplot as plt\n'), ((2857, 2963), 'pandas.pivot_table', 'pd.pivot_table', (['plot_df'], {'index': '"""feature_value"""', 'columns': '"""fold_change"""', 'values': '"""auc"""', 'aggfunc': 'np.median'}), "(plot_df, index='feature_value', columns='fold_change',\n values='auc', aggfunc=np.median)\n", (2871, 2963), True, 'import pandas as pd\n'), ((7375, 7481), 'pandas.pivot_table', 'pd.pivot_table', (['plot_df'], {'index': '"""feature_value"""', 'columns': '"""fold_change"""', 'values': '"""auc"""', 'aggfunc': 'np.median'}), "(plot_df, index='feature_value', columns='fold_change',\n values='auc', aggfunc=np.median)\n", (7389, 7481), True, 'import pandas as pd\n'), ((9526, 9590), 'pandas.read_csv', 'pd.read_csv', (['"""data/analysis/replicates_correlation_sgrna_fc.csv"""'], {}), "('data/analysis/replicates_correlation_sgrna_fc.csv')\n", (9537, 9590), True, 'import pandas as pd\n'), ((10172, 10181), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (10179, 10181), True, 'import matplotlib.pyplot as plt\n'), ((10466, 10475), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (10473, 10475), True, 'import matplotlib.pyplot as plt\n'), ((10782, 10791), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (10789, 10791), True, 'import matplotlib.pyplot as plt\n'), ((11014, 11023), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (11021, 11023), True, 'import matplotlib.pyplot as plt\n'), ((11678, 11687), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (11685, 11687), True, 'import matplotlib.pyplot as plt\n'), ((12357, 12366), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (12364, 12366), True, 'import matplotlib.pyplot as plt\n'), ((13114, 13123), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (13121, 13123), True, 'import matplotlib.pyplot as plt\n'), ((13352, 13361), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (13359, 13361), True, 'import matplotlib.pyplot as plt\n'), ((13910, 13974), 'pandas.read_csv', 'pd.read_csv', (['f"""data/analysis/replicates_correlation_gene_fc.csv"""'], {}), "(f'data/analysis/replicates_correlation_gene_fc.csv')\n", (13921, 13974), True, 'import pandas as pd\n'), ((1414, 1501), 'crispy.QCplot.bias_boxplot', 'cy.QCplot.bias_boxplot', (['cn_aucs_df'], {'x': 'x_var', 'notch': '(False)', 'add_n': '(True)', 'n_text_y': '(0.05)'}), '(cn_aucs_df, x=x_var, notch=False, add_n=True,\n n_text_y=0.05)\n', (1436, 1501), True, 'import crispy as cy\n'), ((1693, 1717), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['f"""{x_label}"""'], {}), "(f'{x_label}')\n", (1703, 1717), True, 'import matplotlib.pyplot as plt\n'), ((1735, 1770), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""AURC (per {groupby})"""'], {}), "(f'AURC (per {groupby})')\n", (1745, 1770), True, 'import matplotlib.pyplot as plt\n'), ((1788, 1834), 'matplotlib.pyplot.title', 'plt.title', (['"""Copy-number effect on CRISPR-Cas9"""'], {}), "('Copy-number effect on CRISPR-Cas9')\n", (1797, 1834), True, 'import matplotlib.pyplot as plt\n'), ((1900, 2012), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""reports/gdsc/bias_copynumber_{groupby}_{y_label}_{x_label}.png"""'], {'bbox_inches': '"""tight"""', 'dpi': '(600)'}), "(f'reports/gdsc/bias_copynumber_{groupby}_{y_label}_{x_label}.png',\n bbox_inches='tight', dpi=600)\n", (1911, 2012), True, 'import matplotlib.pyplot as plt\n'), ((2025, 2041), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2034, 2041), True, 'import matplotlib.pyplot as plt\n'), ((2097, 2163), 'pandas.melt', 'pd.melt', (['cn_aucs_df'], {'id_vars': "['sample', x_var]", 'value_vars': "['auc']"}), "(cn_aucs_df, id_vars=['sample', x_var], value_vars=['auc'])\n", (2104, 2163), True, 'import pandas as pd\n'), ((3763, 3803), 'numpy.array', 'np.array', (['[y - y_err_min, y_err_max - y]'], {}), '([y - y_err_min, y_err_max - y])\n', (3771, 3803), True, 'import numpy as np\n'), ((3933, 3973), 'numpy.array', 'np.array', (['[x - x_err_min, x_err_max - x]'], {}), '([x - x_err_min, x_err_max - x])\n', (3941, 3973), True, 'import numpy as np\n'), ((8278, 8318), 'numpy.array', 'np.array', (['[y - y_err_min, y_err_max - y]'], {}), '([y - y_err_min, y_err_max - y])\n', (8286, 8318), True, 'import numpy as np\n'), ((8442, 8482), 'numpy.array', 'np.array', (['[x - x_err_min, x_err_max - x]'], {}), '([x - x_err_min, x_err_max - x])\n', (8450, 8482), True, 'import numpy as np\n'), ((4445, 4522), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""Copy-number ratio"""', 'loc': '(2)', 'frameon': '(False)', 'prop': "{'size': 6}"}), "(title='Copy-number ratio', loc=2, frameon=False, prop={'size': 6})\n", (4455, 4522), True, 'import matplotlib.pyplot as plt\n'), ((8956, 9033), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'title': '"""Copy-number ratio"""', 'loc': '(2)', 'frameon': '(False)', 'prop': "{'size': 6}"}), "(title='Copy-number ratio', loc=2, frameon=False, prop={'size': 6})\n", (8966, 9033), True, 'import matplotlib.pyplot as plt\n'), ((1852, 1861), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (1859, 1861), True, 'import matplotlib.pyplot as plt\n'), ((3180, 3200), 'numpy.percentile', 'np.percentile', (['v', '(25)'], {}), '(v, 25)\n', (3193, 3200), True, 'import numpy as np\n'), ((3426, 3446), 'numpy.percentile', 'np.percentile', (['v', '(75)'], {}), '(v, 75)\n', (3439, 3446), True, 'import numpy as np\n'), ((4886, 4936), 'crispy.QCplot.recall_curve', 'cy.QCplot.recall_curve', (['beds_gene[s][f]', 'essential'], {}), '(beds_gene[s][f], essential)\n', (4908, 4936), True, 'import crispy as cy\n'), ((7698, 7718), 'numpy.percentile', 'np.percentile', (['v', '(25)'], {}), '(v, 25)\n', (7711, 7718), True, 'import numpy as np\n'), ((7944, 7964), 'numpy.percentile', 'np.percentile', (['v', '(75)'], {}), '(v, 75)\n', (7957, 7964), True, 'import numpy as np\n'), ((1227, 1297), 'crispy.QCplot.recall_curve_discretise', 'cy.QCplot.recall_curve_discretise', (['df[s][y_var]', 'df[s][x_var]', 'x_thres'], {}), '(df[s][y_var], df[s][x_var], x_thres)\n', (1260, 1297), True, 'import crispy as cy\n')] |
""" .. _admitsegment:
ADMITSegmentFinder --- Finds segments of emission within a spectrum.
--------------------------------------------------------------------
This module defines the class for spectral line segment detection.
"""
# system imports
import math
import numpy as np
import numpy.ma as ma
# ADMIT imports
from admit.util import stats
from admit.util import utils
from admit.util import Segments
from admit.util.AdmitLogging import AdmitLogging as logging
class ADMITSegmentFinder(object):
"""Define segments of 'line' emission where segments from data appear to be
above a threshold. This routine comes out of ASTUTE, some parameters below
are hardcoded.
Parameters
----------
freq : float array
Frequencies, GHz.
spec : float array
The y component of the spectrum (arbitrary units, could be linear,
could be log).
f : float
Robustness parameter [1.5].
pmin : float
Signal above cuttoff, rmean+pmin*rstd.
minchan : int
Minimum number of channels needed for a line.
maxgap : int
Allowed channels with signal below cutoff [0].
nomean : bool
Remove the mean from any noise and cutoff calculations. This is useful
if PVCorr based spectra are being processed to get a correct noise level.
Default: False.
Returns
-------
4-tuple
channel_segments[], cutoff, noise, mean
"""
###
### @todo symmetrize the attributes with the vals[]list ? -> spec and nsigma not set
###
def __init__(self, **keyval):
self.peak = None ##
self.f = 1.5 ## standard robust
self.hanning = False # @todo not in vals[]
self.bottom = True ##
self.abs = False ##
self.loglevel = 20 # @todo why it's own loglevel? do we still need this
self.pvc = False ##
self.freq = [] ##
# self.spec = [] ##
self.maxgap = 0 ## 0 the default ?
self.minchan = 3 ##
self.pmin = 0.0 ## 0.0 the default ?
self.nomean = False ## this is the csub parameter in e.g. LineID, another beautiful double negative here
self.noise = None ##
# self.nsigma ## is this pmin? shouldn't nsigma be gone from the vals[] list?
self.vals = ["freq", "spec", "pmin", "peak", "f", "nsigma",\
"minchan", "maxgap", "abs", "pvc", "bottom", "nomean",\
"noise"]
self.set_options(**keyval)
def line_segments(self, spec, cutoff):
""" Method to find segments that where lines are located
[ [start1,end1], [start2,end2], ....]
This function assumes you've subtracted a possible continuum (see the nomean
parameter), and applied the absolute value, because this routine only
segments above the cutoff.
Need some explanation on the use of abs here.
Parameters
----------
spec : numpy array (with a mask)
The spectrum to analyze
cutoff : float
The cutoff to use (line segments must be higher than this value)
Returns
-------
List of segment start and end channels, e.g. [[10,20],[30,40]]
"""
def index(w, start, value):
""" Method to find the index of a specific value, starting at
a specified index
w : list
The list to search for the value
start : int
Index to start searching at
value :
The value to search for
Returns
-------
Int containing the matching index, or -1 if not found.
"""
#@todo
# how about something cleaner:
# try:
# return w[start:].index(value)+start
# except ValueError:
# return -1
n = len(w)
i = start
while i < n:
if w[i] == value:
return i
i = i + 1
return -1
def setval(w, start, end, value):
""" Method to set a range of indices to a specific value
Parameters
----------
w : list
The list to modify
start : int
The index to start at
end : int
The index to end at
value : varies
The value to insert into to specified indicies
Returns
-------
None
"""
for i in range(start, end):
w[i] = value
# -- start of line_segment --
#print "PJT line_segment: ",spec.min(),spec.max(),cutoff,self.minchan,self.maxgap,self.abs
s = [] # accumulate segments
n = len(spec)
w = range(n) # @todo use masking operations, so no loops are needed. this now should work though.
if True:
# here's the old one
w1 = [-1] * n
for i in range(n):
if not self.abs and abs(spec[i]) < cutoff:
w1[i] = 0
elif self.abs and spec[i] < cutoff:
w1[i] = 0
else:
if spec.mask[i]:
w1[i] = 0
else:
w1[i] = 1
#print "PJTW1:",w1
if False:
# here's the new one
w2 = [-1] * n
if self.abs:
for i in range(n):
if spec.mask[i]:
w2[i] = 0
continue
if abs(spec[i]) < cutoff:
w2[i] = 0
else:
w2[i] = 1
else:
for i in range(n):
if spec.mask[i]:
w2[i] = 0
continue
if spec[i] < cutoff:
w2[i] = 0
else:
w2[i] = 1
sum0 = abs(np.array(w2)-np.array(w1)).sum()
#print "PJTW2:",w2,sum0
# pick your method (w1 = original, w2 = peter's )
w = w1
#
i0 = 0
while i0 >= 0:
i1 = index(w, i0, 1)
if i1 < 0:
break
t = index(w, i1 + 1, 1)
if t - i1 > 1:
i0 = i1 + 1
continue
i2 = index(w, i1, 0)
if i2 < 0:
break
i3 = index(w, i2, 1)
if i3 < 0:
il = i2 - i1
if il >= self.minchan:
s.append([i1, i2 - 1])
break
i4 = index(w, i3, 0)
if i4 < 0:
i4 = n - 1
#
ig = i3 - i2
if (ig <= self.maxgap and i4 - i3 > self.minchan) or ig <= 1:
# fill the gap, it's small
setval(w, i2, i3, 1)
i0 = i1
continue
else:
il = i2 - i1
if il >= self.minchan:
s.append([i1, i2 - 1])
i0 = i2
continue
return s
def set_options(self, **keyval):
""" Set the options for the line finding algorithm.
Parameters
----------
freq : float array
Frequencies, GHz.
spec : float array
The y component of the spectrum (arbitrary units, could
be linear, could be log)
f : float
Robustness parameter [1.5]
pmin : float
Signal above cuttoff, rmean+pmin*rstd
minchan : int
Minimum number of channels needed for a line
maxgap : int
Allowed channels with signal below cutoff [0]
"""
for v in self.vals:
try:
setattr(self, v, keyval[v])
except KeyError:
pass
def find(self):
""" Method that does the segment finding
Parameters
----------
None
Returns
-------
Tuple containing a list of the segments, the cutoff used, the
noise level, and a mean baseline.
"""
if self.abs:
self.spec = abs(self.spec)
temp = np.zeros(len(self.spec))
#self.see = ma.masked_array(temp, mask=self.spec.mask)
# parameters (some now from the function argument)
logging.debug("MIN/MAX " + str(self.spec.min()) + " / " +\
str(self.spec.max()))
n = len(self.spec) # data and freq assumed to be same size
if self.hanning:
h = np.hanning(5) / 2 # normalize the convolution array
h = np.array([0.25, 0.5, 0.25])
data2 = np.convolve(self.spec, h, 'same')
else:
data2 = self.spec
if len(data2) != len(self.freq):
raise Exception("ulines: data2 and freq not same array")
# do the work
dr = stats.robust(data2, self.f)
noise = dr.std()
logging.debug("ROBUST: (mean/median/noise) " + \
str(dr.mean()) + " / " + str(ma.median(dr)) + " / " + str(noise))
#print "\n\nD2",data2,"\n"
data3 = ma.masked_invalid(data2)
#print "\n\nD3\n",data3,"\n"
ddiff = data3[1:n] - data3[0:n-1]
logging.debug("DIFF: (mean/stdev) " + str(ddiff.mean()) +\
" / " + str(ddiff.std()))
#print "\n\n",ddiff,"\n",self.f,"\n"
ddr = stats.robust(ddiff, self.f)
logging.debug("RDIFF: (mean/median/stdev) " + \
str(ddr.mean()) + " / " + str(ma.median(ddr)) + " / " + \
str(ddr.std()))
#plt.show()
if self.bottom:
# first remind the classic
dmean1 = dr.mean()
dstd1 = dr.std()
logging.debug("CLASSIC MEAN/SIGMA: " + str(dmean1) + \
" / " + str(dstd1))
# see if we can find a better one?
# k should really depend on nchan, (like an nsigma), 2-3 should be ok for most.
k = 2.5
dmin = dr.min()
dmax = dr.min() + 2 * k * ddr.std() / 1.414214
logging.debug("DMIN/DMAX: " + str(dmin) + " / " + \
str(dmax))
dm = ma.masked_outside(dr, dmin, dmax)
dmean = max(0.0, dm.mean()) # ensure that the mean is positive or 0.0
dstd = dm.std()
if self.noise is not None:
cutoff = self.pmin * self.noise
elif self.nomean:
cutoff = self.pmin * dstd
else:
cutoff = dmean + self.pmin * dstd
logging.debug("BETTER MEAN/SIGMA: " + str(dmean) + \
" / " + str(dstd))
else:
# classic simple, but fails when robust didn't kill off (enough of) the signal
# sigma will be too high, cutoff too high and you could have no lines if there
# is one strong lines
dmean = dr.mean()
dstd = dr.std()
if self.noise is not None:
cutoff = self.pmin * self.noise
elif self.nomean:
cutoff = self.pmin * dstd
else:
cutoff = dmean + self.pmin * dstd
logging.debug("CLASSIC MEAN/SIGMA: " + str(dmean) + \
" / " + str(dstd))
logging.debug("SEGMENTS: f=%g pmin=%g maxgap=%d minchan=%d" % \
(self.f, self.pmin, self.maxgap, self.minchan))
#print "\nDATA\n\n",data2,"\n\n"
segments = self.line_segments(data2, cutoff)
#print "SEGMENTS",segments
nlines = len(segments)
logging.debug("Found %d segments above cutoff %f" % \
(nlines, cutoff))
segp = []
rmax = data2.max() + 0.1 # + 0.05*(data2.max()-data2.min())
segp.append([self.freq[0], self.freq[n - 1], cutoff, cutoff])
segp.append([self.freq[0], self.freq[n - 1], dmean, dmean])
for (l, s) in zip(range(nlines), segments):
ch0 = s[0]
ch1 = s[1]
sum0 = sum(data2[ch0:ch1+1])
sum1 = sum(self.freq[ch0:ch1+1] * data2[ch0:ch1+1])
sum2 = sum(self.freq[ch0:ch1+1] * self.freq[ch0:ch1+1] * data2[ch0:ch1+1])
lmean = sum1 / sum0
# this fails for weaker lines, so wrapped it in a abs
lsigma = math.sqrt(abs(sum2 / sum0 - lmean * lmean))
lmax = max(data2[ch0:ch1+1])
if self.peak != None:
lpeak = 1000*max(self.peak[ch0:ch1+1])
else:
lpeak = max(self.spec[ch0:ch1+1])
# @todo if we ever allow minchan=1 lsigma would be 0.0.... should we adopt channel width?
lfwhm = 2.355 * lsigma / lmean * utils.c
logging.debug(
"Line in %2d channels %4d - %4d @ %.4f GHz +/- %.4f GHz log(S/N) = %.2f FWHM %5.1f km/s %.2f" % \
(ch1 - ch0 + 1, ch0, ch1, lmean, lsigma, lmax, lfwhm, lpeak))
segp.append([self.freq[ch0], self.freq[ch1], rmax, rmax])
segp.append([lmean, lmean, rmax - 0.1, rmax + 0.05])
return Segments.Segments(segments, nchan=len(self.spec)), cutoff, dstd, dmean
| [
"numpy.ma.median",
"numpy.ma.masked_outside",
"numpy.hanning",
"numpy.ma.masked_invalid",
"numpy.array",
"admit.util.AdmitLogging.AdmitLogging.debug",
"numpy.convolve",
"admit.util.stats.robust"
] | [((9404, 9431), 'admit.util.stats.robust', 'stats.robust', (['data2', 'self.f'], {}), '(data2, self.f)\n', (9416, 9431), False, 'from admit.util import stats\n'), ((9643, 9667), 'numpy.ma.masked_invalid', 'ma.masked_invalid', (['data2'], {}), '(data2)\n', (9660, 9667), True, 'import numpy.ma as ma\n'), ((9911, 9938), 'admit.util.stats.robust', 'stats.robust', (['ddiff', 'self.f'], {}), '(ddiff, self.f)\n', (9923, 9938), False, 'from admit.util import stats\n'), ((11789, 11903), 'admit.util.AdmitLogging.AdmitLogging.debug', 'logging.debug', (["('SEGMENTS: f=%g pmin=%g maxgap=%d minchan=%d' % (self.f, self.pmin, self.\n maxgap, self.minchan))"], {}), "('SEGMENTS: f=%g pmin=%g maxgap=%d minchan=%d' % (self.f, self\n .pmin, self.maxgap, self.minchan))\n", (11802, 11903), True, 'from admit.util.AdmitLogging import AdmitLogging as logging\n'), ((12088, 12157), 'admit.util.AdmitLogging.AdmitLogging.debug', 'logging.debug', (["('Found %d segments above cutoff %f' % (nlines, cutoff))"], {}), "('Found %d segments above cutoff %f' % (nlines, cutoff))\n", (12101, 12157), True, 'from admit.util.AdmitLogging import AdmitLogging as logging\n'), ((9132, 9159), 'numpy.array', 'np.array', (['[0.25, 0.5, 0.25]'], {}), '([0.25, 0.5, 0.25])\n', (9140, 9159), True, 'import numpy as np\n'), ((9180, 9213), 'numpy.convolve', 'np.convolve', (['self.spec', 'h', '"""same"""'], {}), "(self.spec, h, 'same')\n", (9191, 9213), True, 'import numpy as np\n'), ((10693, 10726), 'numpy.ma.masked_outside', 'ma.masked_outside', (['dr', 'dmin', 'dmax'], {}), '(dr, dmin, dmax)\n', (10710, 10726), True, 'import numpy.ma as ma\n'), ((13215, 13397), 'admit.util.AdmitLogging.AdmitLogging.debug', 'logging.debug', (["('Line in %2d channels %4d - %4d @ %.4f GHz +/- %.4f GHz log(S/N) = %.2f FWHM %5.1f km/s %.2f'\n % (ch1 - ch0 + 1, ch0, ch1, lmean, lsigma, lmax, lfwhm, lpeak))"], {}), "(\n 'Line in %2d channels %4d - %4d @ %.4f GHz +/- %.4f GHz log(S/N) = %.2f FWHM %5.1f km/s %.2f'\n % (ch1 - ch0 + 1, ch0, ch1, lmean, lsigma, lmax, lfwhm, lpeak))\n", (13228, 13397), True, 'from admit.util.AdmitLogging import AdmitLogging as logging\n'), ((9056, 9069), 'numpy.hanning', 'np.hanning', (['(5)'], {}), '(5)\n', (9066, 9069), True, 'import numpy as np\n'), ((6308, 6320), 'numpy.array', 'np.array', (['w2'], {}), '(w2)\n', (6316, 6320), True, 'import numpy as np\n'), ((6321, 6333), 'numpy.array', 'np.array', (['w1'], {}), '(w1)\n', (6329, 6333), True, 'import numpy as np\n'), ((9555, 9568), 'numpy.ma.median', 'ma.median', (['dr'], {}), '(dr)\n', (9564, 9568), True, 'import numpy.ma as ma\n'), ((10037, 10051), 'numpy.ma.median', 'ma.median', (['ddr'], {}), '(ddr)\n', (10046, 10051), True, 'import numpy.ma as ma\n')] |
import pytest
from gpu_pairwise import pairwise_distance
from scipy.spatial.distance import cdist, squareform
import numpy as np
from numpy.testing import assert_allclose
SCIPY_METRICS = [
'euclidean',
'sqeuclidean',
'cityblock',
'braycurtis',
'canberra',
'chebyshev',
]
# def test_simple_call():
# distances = pairwise_distance([[1, 0], [1, 1]])
# assert (distances == [[0, 0.5], [0.5, 0]]).all()
# def test_non_contiguous_call():
# source = np.transpose(np.array([[0] * 9, [1] * 9, [0] * 9] * 9, dtype=np.bool_))
# print(source.astype(int))
# print(_pack64(source))
# def test_squareform():
# distances = pairwise_distance([
# [0, 0],
# [1, 0],
# [0, 0],
# [1, 1],
# [1, 0],
# [0, 0],
# ], metric='equal', out_dtype='bool', squareform=True)
# assert (list(distances) == [
# False, True, False, False, True,
# False, False, True, False,
# False, False, True,
# False, False,
# False
# ])
# def test_squareform_jaccard():
# data = [
# [0, 0, 1],
# [0, 1, 1],
# [1, 1, 1],
# [0, 0, 0],
# ]
# distances_norm = pairwise_distance(data, metric='jaccard')
# distances_square = pairwise_distance(data, metric='jaccard', squareform=True)
# assert list(squareform(distances_norm)) == list(distances_square)
# # def test_equal():
# # distances = pairwise_distance([
# # [0, 0],
# # [1, 0],
# # [0, 0],
# # [1, 1],
# # [1, 0],
# # [0, 0],
# # ], metric='equal')
# # assert (distances == [
# # [1, 0, 1, 0, 0, 1],
# # [0, 1, 0, 0, 1, 0],
# # [1, 0, 1, 0, 0, 1],
# # [0, 0, 0, 1, 0, 0],
# # [0, 1, 0, 0, 1, 0],
# # [1, 0, 1, 0, 0, 1],
# # ]).all()
@pytest.mark.parametrize("matrix", [
[[1, 0], [0, 1]],
[[0, 0], [0, 0]],
[[0,], [10,]],
[[2, 0.2], [1, 1]],
[[1.1, 100], [100, 1.1]],
np.random.randint(2, size=(100, 2)),
np.random.rand(50, 50) * 100,
np.random.rand(2, 100),
])
@pytest.mark.parametrize("metric", SCIPY_METRICS)
def test_orig(matrix, metric):
ours = pairwise_distance(matrix, metric=metric)
matrix = np.asarray(matrix)
theirs = cdist(matrix, matrix, metric=metric)
np.fill_diagonal(theirs, 0)
assert_allclose(ours, theirs)
# @pytest.mark.parametrize("matrix", [
# [[1, 0], [0, 1]],
# [[0, 0], [0, 0]],
# [[0,], [1,]],
# [[1, 0], [1, 1]],
# [[1, 1], [1, 1]],
# #[[], []],
# np.random.randint(2, size=(9, 9)),
# np.random.randint(2, size=(100, 2)),
# np.random.randint(2, size=(50, 50)),
# np.random.randint(2, size=(2, 100)),
# ])
# @pytest.mark.parametrize("metric", SCIPY_METRICS)
# def test_squareform_variations(matrix, metric):
# ours_normal = pairwise_distance(matrix, metric=metric)
# ours_square = pairwise_distance(matrix, metric=metric, squareform=True)
# theirs_square = squareform(ours_normal, checks=False)
# assert_allclose(ours_square, theirs_square)
# @pytest.mark.parametrize("matrix, weights", [
# ([[1, 0], [0, 1]], [0.5, 1]),
# ([[0, 0], [0, 0]], [1, 1]),
# ([[0,], [1,]], [1]),
# ([[1, 0], [1, 1]], [1, 0.2]),
# ([[1, 1], [1, 1]], [0.5, 0.5]),
# (np.random.randint(2, size=(100, 2)), np.random.rand(2)),
# (np.random.randint(2, size=(50, 50)), np.random.rand(50)),
# (np.random.randint(2, size=(2, 100)), np.random.rand(100)),
# ])
# @pytest.mark.parametrize("metric", SCIPY_METRICS)
# def test_weight(matrix, weights, metric):
# if metric == 'sokalsneath' and any(np.asarray(matrix).sum(axis=1) == 0):
# return
# if metric == 'sokalmichener':
# pytest.skip("scipy bug #13693")
# ours = pairwise_distance(matrix, metric=metric, weights=weights)
# matrix = np.asarray(matrix)
# weights = np.asarray(weights)
# theirs = cdist(matrix, matrix, metric=metric, w=weights)
# assert_allclose(ours, theirs)
# @pytest.mark.parametrize("matrix, weights", [
# ([[1, 0], [0, 1]], [0.5, 1]),
# ([[0, 0], [0, 0]], [1, 1]),
# ([[0,], [1,]], [1]),
# ([[1, 0], [1, 1]], [1, 0.2]),
# ([[1, 1], [1, 1]], [0.5, 0.5]),
# (np.random.randint(2, size=(9, 9)), np.random.rand(9)),
# (np.random.randint(2, size=(100, 2)), np.random.rand(2)),
# (np.random.randint(2, size=(50, 50)), np.random.rand(50)),
# (np.random.randint(2, size=(2, 100)), np.random.rand(100)),
# ])
# @pytest.mark.parametrize("metric", SCIPY_METRICS)
# @pytest.mark.parametrize("dtype, scale", [
# ('float32', 1),
# ('float64', 1),
# ('uint8', 255),
# ('uint16', 65535)
# ])
# def test_weight_dtypes(matrix, weights, metric, dtype, scale):
# if metric == 'sokalsneath' and any(np.asarray(matrix).sum(axis=1) == 0):
# return
# if metric == 'sokalmichener':
# pytest.skip("scipy bug #13693")
# ours = pairwise_distance(matrix, metric=metric, weights=weights, out_dtype=dtype)
# matrix = np.asarray(matrix)
# weights = np.asarray(weights)
# theirs = cdist(matrix, matrix, metric=metric, w=weights)
# if scale != 1:
# theirs = np.nan_to_num(theirs, nan=0)
# assert_allclose(ours, theirs * scale, atol=1, )
# @pytest.mark.parametrize("matrix", [
# [[1, 0], [0, 1]],
# [[0, 0], [0, 0]],
# [[0,], [1,]],
# [[1, 0], [1, 1]],
# [[1, 1], [1, 1]],
# #[[], []],
# np.random.randint(2, size=(9, 9)),
# np.random.randint(2, size=(100, 2)),
# np.random.randint(2, size=(50, 50)),
# np.random.randint(2, size=(2, 100)),
# ])
# @pytest.mark.parametrize("metric", SCIPY_METRICS)
# @pytest.mark.parametrize("dtype, scale", [
# ('float32', 1),
# ('float64', 1),
# ('uint8', 255),
# ('uint16', 65535)
# ])
# def test_noweight_dtypes(matrix, metric, dtype, scale):
# ours = pairwise_distance(matrix, metric=metric, out_dtype=dtype)
# matrix = np.asarray(matrix)
# theirs = cdist(matrix, matrix, metric=metric)
# if scale != 1:
# theirs = np.nan_to_num(theirs, nan=0)
# assert_allclose(ours, theirs * scale, atol=1.)
| [
"scipy.spatial.distance.cdist",
"numpy.fill_diagonal",
"numpy.asarray",
"numpy.testing.assert_allclose",
"gpu_pairwise.pairwise_distance",
"numpy.random.randint",
"numpy.random.rand",
"pytest.mark.parametrize"
] | [((2130, 2178), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', 'SCIPY_METRICS'], {}), "('metric', SCIPY_METRICS)\n", (2153, 2178), False, 'import pytest\n'), ((2221, 2261), 'gpu_pairwise.pairwise_distance', 'pairwise_distance', (['matrix'], {'metric': 'metric'}), '(matrix, metric=metric)\n', (2238, 2261), False, 'from gpu_pairwise import pairwise_distance\n'), ((2275, 2293), 'numpy.asarray', 'np.asarray', (['matrix'], {}), '(matrix)\n', (2285, 2293), True, 'import numpy as np\n'), ((2307, 2343), 'scipy.spatial.distance.cdist', 'cdist', (['matrix', 'matrix'], {'metric': 'metric'}), '(matrix, matrix, metric=metric)\n', (2312, 2343), False, 'from scipy.spatial.distance import cdist, squareform\n'), ((2348, 2375), 'numpy.fill_diagonal', 'np.fill_diagonal', (['theirs', '(0)'], {}), '(theirs, 0)\n', (2364, 2375), True, 'import numpy as np\n'), ((2380, 2409), 'numpy.testing.assert_allclose', 'assert_allclose', (['ours', 'theirs'], {}), '(ours, theirs)\n', (2395, 2409), False, 'from numpy.testing import assert_allclose\n'), ((2027, 2062), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': '(100, 2)'}), '(2, size=(100, 2))\n', (2044, 2062), True, 'import numpy as np\n'), ((2102, 2124), 'numpy.random.rand', 'np.random.rand', (['(2)', '(100)'], {}), '(2, 100)\n', (2116, 2124), True, 'import numpy as np\n'), ((2068, 2090), 'numpy.random.rand', 'np.random.rand', (['(50)', '(50)'], {}), '(50, 50)\n', (2082, 2090), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from pandas.core.base import PandasObject
from scipy.optimize import minimize
from decorator import decorator
from sklearn.covariance import ledoit_wolf
@decorator
def mean_var_weights(func_covar, *args, **kwargs):
"""
Calculates the mean-variance weights given a DataFrame of returns.
Args:
* args[0]: returns (DataFrame): Returns for multiple securities.
* args[1]: weight_bounds ((low, high)): Weigh limits for optimization.
* args[2]: rf (float): `Risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ used in utility calculation
* args[3]: options (dict): options for minimizing, e.g. {'maxiter': 10000 }
Returns:
Series {col_name: weight}
"""
if len(args)<4:
raise Exception("Not Enough Parameters")
returns = args[0]
weight_bounds = args[1]
rf = args[2]
options = args[3]
def fitness(weights, exp_rets, covar, rf):
# portfolio mean
mean = sum(exp_rets * weights)
# portfolio var
var = np.dot(np.dot(weights, covar), weights)
# utility - i.e. sharpe ratio
util = (mean - rf) / np.sqrt(var)
# negative because we want to maximize and optimizer
# minimizes metric
return -util
n = len(returns.columns)
# expected return defaults to mean return by default
exp_rets = returns.mean()
# calc covariance matrix
covar = func_covar(returns)
weights = np.ones([n]) / n
bounds = [weight_bounds for i in range(n)]
# sum of weights must be equal to 1
constraints = ({'type': 'eq', 'fun': lambda W: sum(W) - 1.})
optimized = minimize(fitness, weights, (exp_rets, covar, rf),
method='SLSQP', constraints=constraints,
bounds=bounds, options=options)
# check if success
if not optimized.success:
raise Exception(optimized.message)
# return weight vector
return pd.Series({returns.columns[i]: optimized.x[i] for i in range(n)})
@mean_var_weights
def mvw_standard(prices,
weight_bounds=(0.,1.),
rf = 0.,
options = None):
"""
Calculates the mean-variance weights given a DataFrame of returns.
Wraps mean_var_weights with standard covariance calculation method
Args:
* prices (DataFrame): Prices for multiple securities.
* weight_bounds ((low, high)): Weigh limits for optimization.
* rf (float): `Risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ used in utility calculation
* options (dict): options for minimizing, e.g. {'maxiter': 10000 }
Returns:
Series {col_name: weight}
"""
r = prices.to_returns().dropna()
covar = r.cov()
return covar
@mean_var_weights
def mvw_ledoit_wolf(prices,
weight_bounds=(0.,1.),
rf = 0.,
options = None):
"""
Calculates the mean-variance weights given a DataFrame of returns.
Wraps mean_var_weights with ledoit_wolf covariance calculation method
Args:
* prices (DataFrame): Prices for multiple securities.
* weight_bounds ((low, high)): Weigh limits for optimization.
* rf (float): `Risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ used in utility calculation
* options (dict): options for minimizing, e.g. {'maxiter': 10000 }
Returns:
Series {col_name: weight}
"""
r = prices.to_returns().dropna()
covar = ledoit_wolf(r)[0]
return covar
def _erc_weights_ccd(x0,
cov,
b,
maximum_iterations,
tolerance):
"""
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
* cov (np.array): covariance matrix.
* b (np.array): Risk target weights.
* maximum_iterations (int): Maximum iterations in iterative solutions.
* tolerance (float): Tolerance level in iterative solutions.
Returns:
np.array {weight}
Reference:
Griveau-Billion, Theophile and Richard, Jean-Charles and Roncalli,
Thierry, A Fast Algorithm for Computing High-Dimensional Risk Parity
Portfolios (2013).
Available at SSRN: https://ssrn.com/abstract=2325255
"""
n = len(x0)
x = x0.copy()
var = np.diagonal(cov)
ctr = cov.dot(x)
sigma_x = np.sqrt(x.T.dot(ctr))
for iteration in range(maximum_iterations):
for i in range(n):
alpha = var[i]
beta = ctr[i] - x[i] * alpha
gamma = -b[i] * sigma_x
x_tilde = (-beta + np.sqrt(
beta * beta - 4 * alpha * gamma)) / (2 * alpha)
x_i = x[i]
ctr = ctr - cov[i] * x_i + cov[i] * x_tilde
sigma_x = sigma_x * sigma_x - 2 * x_i * cov[i].dot(
x) + x_i * x_i * var[i]
x[i] = x_tilde
sigma_x = np.sqrt(sigma_x + 2 * x_tilde * cov[i].dot(
x) - x_tilde * x_tilde * var[i])
# check convergence
if np.power((x - x0) / x.sum(), 2).sum() < tolerance:
return x / x.sum()
x0 = x.copy()
# no solution found
raise ValueError('No solution found after {0} iterations.'.format(
maximum_iterations))
@decorator
def risk_parity_weights(func_covar, *args, **kwargs):
"""
Calculates the equal risk contribution / risk parity weights given a
DataFrame of returns.
Args:
* args[0]: returns (DataFrame): Returns or Prices for multiple securities.
* args[1]: initial_weights (list): Starting asset weights [default inverse vol].
* args[2]: risk_weights (list): Risk target weights [default equal weight].
* args[3]: risk_parity_method (str): Risk parity estimation method.
Currently supported:
- ccd (cyclical coordinate descent)[default]
* args[4]: maximum_iterations (int): Maximum iterations in iterative solutions.
* args[5]: tolerance (float): Tolerance level in iterative solutions.
Returns:
Series {col_name: weight}
"""
if len(args)<8:
raise Exception("Not Enough Parameters")
returns = args[0]
initial_weights = args[1]
risk_weights = args[2]
risk_parity_method = args[3]
maximum_iterations = args[4]
tolerance = args[5]
min_n = args[6]
max_n = args[7]
n = len(returns.columns)
# calc covariance matrix
covar = func_covar(returns)
# initial weights (default to inverse vol)
if initial_weights is None:
inv_vol = 1. / np.sqrt(np.diagonal(covar))
initial_weights = inv_vol / inv_vol.sum()
# default to equal risk weight
if risk_weights is None:
risk_weights = np.ones(n) / n
if risk_weights is not None:
min_n = min(n, min_n)
max_n = min(n, max_n)
if max_n>min_n:
#
if len(risk_weights)<n:
for i in range(min_n, n):
risk_weights.append(0.0)
else:
for i in range(min_n, n):
risk_weights[i] = 0.0
#
left_risk = 1-sum(risk_weights)
distribute_risk = left_risk/(max_n-min_n)
#
min_idx = np.argsort([covar[i,i] for i in range(min_n, len(covar))])[:max_n-min_n] + min_n
for i in min_idx:
risk_weights[i] = distribute_risk
# calc risk parity weights matrix
if risk_parity_method == 'ccd':
# cyclical coordinate descent implementation
erc_weights = _erc_weights_ccd(
initial_weights,
covar,
risk_weights,
maximum_iterations,
tolerance
)
else:
raise NotImplementedError('risk_parity_method not implemented')
# return erc weights vector
return pd.Series(erc_weights, index=returns.columns, name='erc')
@risk_parity_weights
def rpw_standard(prices,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 100,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
"""
Calculates the equal risk contribution / risk parity weights given a
DataFrame of returns.
Wraps mean_var_weights with standard covariance calculation method
Args:
* prices (DataFrame): Prices for multiple securities.
* initial_weights (list): Starting asset weights [default inverse vol].
* risk_weights (list): Risk target weights [default equal weight].
* risk_parity_method (str): Risk parity estimation method.
Currently supported:
- ccd (cyclical coordinate descent)[default]
* maximum_iterations (int): Maximum iterations in iterative solutions.
* tolerance (float): Tolerance level in iterative solutions.
* min_assets_number: mininial assets number in portfolio at time t
* max_assets_number: maxinial assets number in portfolio at time t
Returns:
Series {col_name: weight}
"""
r = prices.to_returns().dropna()
covar = r.cov().values
return covar
@risk_parity_weights
def rpw_ledoit_wolf(prices,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 100,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
"""
Calculates the equal risk contribution / risk parity weights given a
DataFrame of returns.
Wraps mean_var_weights with ledoit_wolf covariance calculation method
Args:
* prices (DataFrame): Prices for multiple securities.
* initial_weights (list): Starting asset weights [default inverse vol].
* risk_weights (list): Risk target weights [default equal weight].
* risk_parity_method (str): Risk parity estimation method.
Currently supported:
- ccd (cyclical coordinate descent)[default]
* maximum_iterations (int): Maximum iterations in iterative solutions.
* tolerance (float): Tolerance level in iterative solutions.
* min_assets_number: mininial assets number in portfolio at time t
* max_assets_number: maxinial assets number in portfolio at time t
Returns:
Series {col_name: weight}
"""
r = prices.to_returns().dropna()
covar = ledoit_wolf(r)[0]
return covar
@risk_parity_weights
def rpw_mean_var(covar,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 100,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
'''r = prices.to_returns().dropna()
covar = r.cov().values
mv = []
for e in r.columns:
mv_tmp = r[e].var()*2+r[e].mean()
mv.append(mv_tmp)
for i in range(len(r.columns)):
if mv[i]<0:
f = 1 + np.sin(mv[i]*100)
covar[i,i] = covar[i,i] * f
return covar'''
return covar.values
from pyetf.algos import forecast_var_from_garch
@risk_parity_weights
def rpw_garch(prices,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 1000,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
r = prices.to_returns().dropna()
covar = ledoit_wolf(r)[0]
for i in range(len(r.columns)):
var, _ = forecast_var_from_garch(100.0*r[r.columns[i]])
covar[i,i] += (var/10000.0) #**(0.5)
return covar
from pyetf.algos import future_mean_var
@risk_parity_weights
def rpw_future(prices,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 100,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
r = prices.to_returns().dropna()
covar = ledoit_wolf(r)[0]
for i in range(len(r.columns)):
_, var = future_mean_var(prices[prices.columns[i]].values)
covar[i,i] = var*100
return covar
@risk_parity_weights
def rpw_lstm(covar,
initial_weights = None,
risk_weights = None,
risk_parity_method = 'ccd',
maximum_iterations = 100,
tolerance = 1E-8,
min_assets_number = 2,
max_assets_number = 6
):
return covar.values
from pyetf.algos import forecast_var_from_lstm
from pyetf.algos import forecast_cov_from_lstm
from pyetf.keras_model import addFeatures
def to_weights(
prices,
func_weighting=rpw_standard,
hist_length=200,
model=None,
*args, **kwargs):
"""
Calculates the weights of each asset in portfolio.
Use historical data since 0:hist_length-1 to calculate weights at hist_length
In Python, data in [0:hist_length] -> weights stored at [hist_length-1]
Ex:
prices.to_weights()
prices.to_weights(func_weighting=rpw_ledoit_wolf, risk_weights=mc)
Args:
* prices (DataFrame): Prices for multiple securities.
* func_weighting (function): function to use to estimate covariance
[default rpw_standard].
* hist_length: Length of data to use [default 200].
if hist_length < 0: Use future data i.e. hist_length=-30
* other paramters: Used in func_weighting.
i.e. mc=[0.5, 0.3, 0.2]
risk_weights=mc
Returns:
Pandas Dataframe
"""
w = prices.copy()
for e in w.columns:
w[e] = np.nan
if model is None:
if hist_length > 0:
m = hist_length
# 0:m -> m
# python - [0:m] -> [m-1]
for t in range(0, len(prices)-m+1):
p = prices.iloc[t:t+m]
w.iloc[t+m-1] = func_weighting(p, *args, **kwargs)
elif hist_length < 0: # hist_length < 0 : use future data
m = -hist_length
for t in range(0, len(prices)-m+1):
p = prices.iloc[t:t+m]
w.iloc[t] = func_weighting(p, *args, **kwargs)
else:
if model == "lstm":
var = prices.copy()
for e in prices.columns:
var[e] = forecast_var_from_lstm(addFeatures, prices[e])
if hist_length > 0:
m = hist_length
for t in range(0, len(prices)-m+1):
p = prices.iloc[t:t+m]
v = var.iloc[t:t+m]
r = p.to_returns().dropna()
covar = ledoit_wolf(r)[0]
for i in range(len(v.columns)):
covar[i,i] += max(0,(v[v.columns[i]].iloc[-1]/10000.0))
pd_covar = pd.DataFrame(data=covar, columns=prices.columns)
w.iloc[t+m-1] = func_weighting(pd_covar, *args, **kwargs)
elif model == "lstm_cov":
pastDays=30
r = prices.to_returns().dropna()
covar = r.cov().values
cov = covar.tolist()
for i in range(len(prices.columns)):
for j in range(0, i+1):
cov[i][j] = forecast_cov_from_lstm(addFeatures, prices[prices.columns[i]], prices[prices.columns[j]], pastDays)
if i!=j:
cov[j][i] = cov[i][j]
m = hist_length+pastDays
for t in range(m+30, len(prices)):
for i in range(len(prices.columns)):
for j in range(len(prices.columns)):
covar[i][j] = cov[i][j][t]
pd_covar = pd.DataFrame(data=covar, columns=prices.columns)
w.iloc[t] = func_weighting(pd_covar, *args, **kwargs)
elif model == "mean_var":
if hist_length > 0:
m = hist_length
mv = []
for t in range(0, len(prices)-m+1):
p = prices.iloc[t:t+m]
r = p.to_returns().dropna()
v = []
for e in r.columns:
v_tmp = r[e].var()*2+r[e].mean()
v.append(v_tmp)
mv.append(v)
mv = pd.DataFrame(data=mv, index=prices.index[len(prices)-len(mv):len(prices)], columns=prices.columns)
mv_t = mv.copy()
uplevel=0.001
for e in r.columns:
for t in range(1, len(mv[e])):
if mv_t[e][t-1]<0:
if mv[e][t]<mv_t[e][t-1]:
mv_t[e][t]=mv[e][t]
elif mv[e][t]<uplevel:
mv_t[e][t]=mv_t[e][t-1]
for t in range(0, len(prices)-m+1):
p = prices.iloc[t:t+m]
r = p.to_returns().dropna()
covar = ledoit_wolf(r)[0]
for i in range(len(r.columns)):
if mv_t[r.columns[i]][t]<0:
f = 1 + np.sin(mv_t[r.columns[i]][t]*100)
covar[i,i] = covar[i,i] * f
pd_covar = pd.DataFrame(data=covar, columns=r.columns)
w.iloc[t+m-1] = func_weighting(pd_covar, *args, **kwargs)
return w
def to_NAV(prices, weights, init_cash=1000000):
portfolio = prices.copy()
w = weights.copy()
portfolio['NAV'] = w.sum(axis=1)
# cut nan
portfolio = portfolio[portfolio.NAV>0]
w = w.dropna()
portfolio.iloc[0].NAV = init_cash
s = w.copy()
for e in w.columns:
s.iloc[0][e] = 0.
for t in range(1, len(w)):
nav = portfolio.iloc[t-1].NAV
for e in w.columns:
s.iloc[t][e] = nav * w.iloc[t-1][e] / portfolio.iloc[t-1][e]
nav = 0.
for e in w.columns:
nav += s.iloc[t][e] * portfolio.iloc[t][e]
portfolio.iloc[t].NAV = nav
return portfolio
def to_NAV2(prices, weights, init_cash=1000000, commission=0.01):
portfolio = prices.copy()
w = weights.copy()
portfolio['NAV'] = w.sum(axis=1)
portfolio = portfolio[portfolio.NAV>0]
w = w.dropna()
portfolio.iloc[0].NAV = init_cash
s = to_shares(prices, weights)
cash = init_cash
for t in range(1, len(w)):
nav = 0.
for e in w.columns:
nav += s.iloc[t][e] * portfolio.iloc[t][e]
delta_cash = -(s.iloc[t][e]-s.iloc[t-1][e]) * portfolio.iloc[t][e]
cash += delta_cash - abs(delta_cash)*commission
portfolio.iloc[t].NAV = nav + cash
return portfolio
def to_shares(prices, weights, init_cash=1000000, nShares=100):
portfolio = prices.copy()
w = weights.copy()
portfolio['NAV'] = w.sum(axis=1)
portfolio = portfolio[portfolio.NAV>0]
w = w.dropna()
s = w.copy()
portfolio.iloc[0].NAV = init_cash
for e in w.columns:
s.iloc[0][e] = 0.
for t in range(1, len(w)):
nav = portfolio.iloc[t-1].NAV
for e in w.columns:
s.iloc[t][e] = nav * w.iloc[t-1][e] / portfolio.iloc[t-1][e]
nav = 0.
for e in w.columns:
nav += s.iloc[t][e] * portfolio.iloc[t][e]
portfolio.iloc[t].NAV = nav
s = s // nShares * nShares
return s
def to_shares2(prices, weights, init_cash=1000000, nShares=100):
portfolio = prices.copy()
w = weights.copy()
portfolio['NAV'] = w.sum(axis=1)
portfolio = portfolio[portfolio.NAV>0]
w = w.dropna()
s = w.copy()
portfolio.iloc[0].NAV = init_cash
for e in w.columns:
s.iloc[0][e] = 0.
for t in range(1, len(w)):
nav = portfolio.iloc[t-1].NAV
for e in w.columns:
s.iloc[t][e] = nav * w.iloc[t-1][e] / portfolio.iloc[t-1][e]
nav = 0.
for e in w.columns:
nav += s.iloc[t][e] * portfolio.iloc[t][e]
s.iloc[t][e] = (s.iloc[t][e]//nShares)*nShares
portfolio.iloc[t].NAV = nav
return s
def extend_pandas():
"""
Extends pandas function, i.e. display items
Ex:
prices.to_weights()
(where prices would be a DataFrame)
"""
PandasObject.to_weights = to_weights
PandasObject.to_shares = to_shares
PandasObject.to_NAV = to_NAV
PandasObject.to_NAV2 = to_NAV2 | [
"pandas.DataFrame",
"pyetf.algos.future_mean_var",
"scipy.optimize.minimize",
"sklearn.covariance.ledoit_wolf",
"pyetf.algos.forecast_var_from_garch",
"pyetf.algos.forecast_var_from_lstm",
"numpy.ones",
"numpy.sin",
"pyetf.algos.forecast_cov_from_lstm",
"pandas.Series",
"numpy.dot",
"numpy.sqr... | [((1723, 1849), 'scipy.optimize.minimize', 'minimize', (['fitness', 'weights', '(exp_rets, covar, rf)'], {'method': '"""SLSQP"""', 'constraints': 'constraints', 'bounds': 'bounds', 'options': 'options'}), "(fitness, weights, (exp_rets, covar, rf), method='SLSQP',\n constraints=constraints, bounds=bounds, options=options)\n", (1731, 1849), False, 'from scipy.optimize import minimize\n'), ((4566, 4582), 'numpy.diagonal', 'np.diagonal', (['cov'], {}), '(cov)\n', (4577, 4582), True, 'import numpy as np\n'), ((8156, 8213), 'pandas.Series', 'pd.Series', (['erc_weights'], {'index': 'returns.columns', 'name': '"""erc"""'}), "(erc_weights, index=returns.columns, name='erc')\n", (8165, 8213), True, 'import pandas as pd\n'), ((1538, 1550), 'numpy.ones', 'np.ones', (['[n]'], {}), '([n])\n', (1545, 1550), True, 'import numpy as np\n'), ((3627, 3641), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (3638, 3641), False, 'from sklearn.covariance import ledoit_wolf\n'), ((10914, 10928), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (10925, 10928), False, 'from sklearn.covariance import ledoit_wolf\n'), ((12068, 12082), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (12079, 12082), False, 'from sklearn.covariance import ledoit_wolf\n'), ((12139, 12187), 'pyetf.algos.forecast_var_from_garch', 'forecast_var_from_garch', (['(100.0 * r[r.columns[i]])'], {}), '(100.0 * r[r.columns[i]])\n', (12162, 12187), False, 'from pyetf.algos import forecast_var_from_garch\n'), ((12667, 12681), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (12678, 12681), False, 'from sklearn.covariance import ledoit_wolf\n'), ((12738, 12787), 'pyetf.algos.future_mean_var', 'future_mean_var', (['prices[prices.columns[i]].values'], {}), '(prices[prices.columns[i]].values)\n', (12753, 12787), False, 'from pyetf.algos import future_mean_var\n'), ((1114, 1136), 'numpy.dot', 'np.dot', (['weights', 'covar'], {}), '(weights, covar)\n', (1120, 1136), True, 'import numpy as np\n'), ((1214, 1226), 'numpy.sqrt', 'np.sqrt', (['var'], {}), '(var)\n', (1221, 1226), True, 'import numpy as np\n'), ((7015, 7025), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (7022, 7025), True, 'import numpy as np\n'), ((6857, 6875), 'numpy.diagonal', 'np.diagonal', (['covar'], {}), '(covar)\n', (6868, 6875), True, 'import numpy as np\n'), ((15046, 15092), 'pyetf.algos.forecast_var_from_lstm', 'forecast_var_from_lstm', (['addFeatures', 'prices[e]'], {}), '(addFeatures, prices[e])\n', (15068, 15092), False, 'from pyetf.algos import forecast_var_from_lstm\n'), ((4853, 4893), 'numpy.sqrt', 'np.sqrt', (['(beta * beta - 4 * alpha * gamma)'], {}), '(beta * beta - 4 * alpha * gamma)\n', (4860, 4893), True, 'import numpy as np\n'), ((15561, 15609), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'covar', 'columns': 'prices.columns'}), '(data=covar, columns=prices.columns)\n', (15573, 15609), True, 'import pandas as pd\n'), ((16427, 16475), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'covar', 'columns': 'prices.columns'}), '(data=covar, columns=prices.columns)\n', (16439, 16475), True, 'import pandas as pd\n'), ((15380, 15394), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (15391, 15394), False, 'from sklearn.covariance import ledoit_wolf\n'), ((15980, 16084), 'pyetf.algos.forecast_cov_from_lstm', 'forecast_cov_from_lstm', (['addFeatures', 'prices[prices.columns[i]]', 'prices[prices.columns[j]]', 'pastDays'], {}), '(addFeatures, prices[prices.columns[i]], prices[\n prices.columns[j]], pastDays)\n', (16002, 16084), False, 'from pyetf.algos import forecast_cov_from_lstm\n'), ((18028, 18071), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'covar', 'columns': 'r.columns'}), '(data=covar, columns=r.columns)\n', (18040, 18071), True, 'import pandas as pd\n'), ((17705, 17719), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['r'], {}), '(r)\n', (17716, 17719), False, 'from sklearn.covariance import ledoit_wolf\n'), ((17880, 17915), 'numpy.sin', 'np.sin', (['(mv_t[r.columns[i]][t] * 100)'], {}), '(mv_t[r.columns[i]][t] * 100)\n', (17886, 17915), True, 'import numpy as np\n')] |
# routines for generating a list of coordinate offsets for various template structures
import numpy as np
class Template:
"""Class template for generating lists of template voxels
Parameters
----------
type: string
Required by constructor. The type of template currently available types are:
- 'RectBox' - rectangular box (1,2,3,4 dimensions) template origin is center of box
- 'RectShell' - shell of rectangular box (1,2,3,4 dimensions) template origin is center of shell
- 'Ellipsoid' - ellispoid (1,2,3,4 dimensions) template origin is center of ellipsoid
- 'EllipsoidShell' - ellipsoidal shell (1,2,3,4 dimensions) template origin is center of shell
- 'Line' - linear template template origin is first point of line
- 'Notch' - notch template template origin is point about which notch is built
- 'Cone' - cone template template origin is start of half cone
sizes: 1D int array (can be empty)
Attributes of sizes required for constructing template
dimension: int
Dimension of template
inclusion: bool
Whether or not to include anchor point (i.e. [0], [0,0],...)
handedness: 1D int array
If there are axial asymetries in the template (e.g. Notch) can pass in a vector with +1 for 'right' and -1
for 'left' (default is [1], or [1,1], or...)
axbase: List of ints (each list of length = dimension)
Basis vector specifying axis, when appropriate, for direction of template (can be empty) - component lengths
will be ignored; only whether the component is zero or nonzero, and the sign will be
considered (i.e. only co-ordinate axes and '45 degree' lines will be considered as template axes), so e.g::
[1,0] ~ [10,0] ~ x-axis in 2D
[0,1,0] ~ [0,33,0] ~ y-axis in 3D
[1,-1] ~ [30,-20] ~ [108,-1] ~ 135 degree axis in 2
if axbase is empty template will pick axes according to following conventions:
- templates requiring single axis specification (e.g. line, notch, cone) will always use positivedirection of first dimension
- templates requiring multiple axis specification, e.g. rectangular parallelipipeds and ellipsoids will choose:
- largest dimension (e.g. semi-major axis) in positive direction of first dimension
- next largest dimension (e.g. semi-minor axis) in positive direction of second dimension
- etc.
anchoff: list of ints
Offset of anchor point from template [0,0,0] in template (usually assume [0,0,0])
shift: List of int
List of ints to use if you
want to shift all points in offset array - useful, e.g.
if you want to build cooccurence arrays from offset
templates - build one template (set of offsets with no shift
and another with an appropriate shift; those can each be passed
to the feature space cluster algorithm, then those
to the cooccurence matrix builder, and that to the texture
measure generator.
"""
def __init__(self, type, sizes, dimension, inclusion, handedness=None, axbase=None, anchoff=None, shift=None):
self.type = type
self.sizes = sizes
self.dim = dimension
self.me = inclusion
self.handedness = handedness
self.offsets = []
self.axbase = axbase
self.anchoff = anchoff
self.shift = shift
# Set up default handedness
if self.handedness is None: # Nothing passed in to constructor
if self.dim == 1:
self.handedness = [1]
if self.dim == 2:
self.handedness = [1, 1]
if self.dim == 3:
self.handedness = [1, 1, 1]
if self.dim == 4:
self.handedness = [1, 1, 1, 1]
# Set up default axis directions
if self.axbase is None: # Nothing passed in to constructor
if self.dim == 1:
# pick convention for 1 dimension of positve = 1
# negative = -1
self.axbase = [1]
if self.dim == 2:
self.axbase = [1, 0]
if self.dim == 3:
self.axbase = [1, 0, 0]
if self.dim == 4:
self.axbase = [1, 0, 0, 0]
# Set up anchor point offset
if self.anchoff is None: # Nothing passed in to constructor
if self.dim == 1:
self.anchoff = [0]
if self.dim == 2:
self.anchoff = [0, 0]
if self.dim == 3:
self.anchoff = [0, 0, 0]
if self.dim == 4:
self.anchoff = [0, 0, 0, 0]
# Set up shift
if self.shift is None: # Nothing passed in to constructor
if self.dim == 1:
self.shift = [0]
if self.dim == 2:
self.shift = [0, 0]
if self.dim == 3:
self.shift = [0, 0, 0]
if self.dim == 4:
self.shift = [0, 0, 0, 0]
################# RECTBOX #######################
if type == "RectBox":
if len(self.sizes) != self.dim:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
# Calculate box limits
lims = np.zeros((self.dim, 2), int)
for i in range(self.dim):
lims[i, 0] = -(self.sizes[0] / 2)
if self.sizes[0] % 2 == 0:
lims[i, 1] = self.sizes[0] / 2
else:
lims[i, 1] = (self.sizes[0] / 2) + 1
if self.dim == 1:
for i in range(lims[0, 0], lims[0, 1]):
self.offsets.append([i])
if [0] in self.offsets:
self.offsets.remove([0]) # might put back later
if self.dim == 2:
for i in range(lims[0, 0], lims[0, 1]):
for j in range(lims[1, 0], lims[1, 1]):
self.offsets.append([i, j])
if [0, 0] in self.offsets:
self.offsets.remove([0, 0]) # might put back later
if self.dim == 3:
for i in range(lims[0, 0], lims[0, 1]):
for j in range(lims[1, 0], lims[1, 1]):
for k in range(lims[2, 0], lims[2, 1]):
self.offsets.append([i, j, k])
if [0, 0, 0] in self.offsets:
self.offsets.remove([0, 0, 0]) # might put back later
if self.dim == 4:
for i in range(lims[0, 0], lims[0, 1]):
for j in range(lims[1, 0], lims[1, 1]):
for k in range(lims[2, 0], lims[2, 1]):
for t in range(lims[3, 0], lims[3, 1]):
self.offsets.append([i, j, k, t])
if [0, 0, 0, 0] in self.offsets:
self.offsets.remove([0, 0, 0, 0]) # might put back later
################# RECTSHELL #######################
elif type == "RectShell":
if len(self.sizes) != self.dim:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
if self.dim == 1:
sub = self.sizes[0] / 2
for i in range(self.sizes[0]):
if (i == 0 or i == self.sizes[0] - 1):
self.offsets.append([i - sub])
if self.dim == 2:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
if (i == 0 or i == self.sizes[0] - 1 or j == 0 or j == self.sizes[1] - 1):
self.offsets.append([i - sub0, j - sub1])
if self.dim == 3:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
sub2 = self.sizes[2] / 2
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
for k in range(self.sizes[2]):
if (i == 0 or i == self.sizes[0] - 1 or j == 0 or j == self.sizes[1] - 1 or k == 0 or k ==
self.sizes[2] - 1):
self.offsets.append([i - sub0, j - sub1, k - sub2])
if self.dim == 4:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
sub2 = self.sizes[2] / 2
sub3 = self.sizes[3] / 2
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
for k in range(self.sizes[2]):
for t in range(self.sizes[3]):
if (i == 0 or i == self.sizes[0] - 1 or j == 0 or j == self.sizes[1] - 1 or
k == 0 or k == self.sizes[2] - 1 or t == 0 or t == self.sizes[3] - 1):
self.offsets.append([i - sub0, j - sub1, k - sub2, t - sub3])
################# ELLIPSOID #######################
elif type == "Ellipsoid":
if len(self.sizes) != self.dim:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
# sys.exit(-1)
if self.dim == 1: # same as 1D rectangular box
sub = self.sizes[0] / 2
for i in range(self.sizes[0]):
self.offsets.append([i - sub])
if self.dim == 2:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
s02 = self.sizes[0] * self.sizes[0]
s12 = self.sizes[1] * self.sizes[1]
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
bounder = ((i - sub0) * (i - sub0)) / s02 + ((j - sub1) * (j - sub1)) / s12
if (bounder <= 1.0):
self.offsets.append([i - sub0, j - sub1])
if self.dim == 3:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
sub2 = self.sizes[2] / 2
s02 = self.sizes[0] * self.sizes[0]
s12 = self.sizes[1] * self.sizes[1]
s22 = self.sizes[2] * self.sizes[2]
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
for k in range(self.sizes[2]):
bounder = ((i - sub0) * (i - sub0)) / s02 + ((j - sub1) * (j - sub1)) / s12 + (
(k - sub2) * (
k - sub2)) / s22
if (bounder <= 1.0):
self.offsets.append([i - sub0, j - sub1, k - sub2])
if self.dim == 4:
print
"Sorry 4D ellipsoids not yet implemented"
# sys.exit(-1)
################# ELLIPSOIDSHELL #######################
elif type == "EllipsoidShell":
if len(self.sizes) != self.dim:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
# sys.exit(-1)
if self.dim == 1: # Same as 1D rectangular shell
sub = self.sizes[0] / 2
for i in range(self.sizes[0]):
if (i == 0 or i == self.sizes[0] - 1):
self.offsets.append([i - sub])
# FIX ME !!! - Haven't used or tested 2,3 dim ellipsoidal shells
if self.dim == 2:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
s02 = self.sizes[0] * self.sizes[0]
s12 = self.sizes[1] * self.sizes[1]
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
bounder = ((i - sub0) * (i - sub0)) / s02 + ((j - sub1) * (j - sub1)) / s12
if (bounder > 0.9 and bounder < 1.1): # Need to figure
self.offsets.append([i - sub0, j - sub1]) # out these bounds
if self.dim == 3:
sub0 = self.sizes[0] / 2
sub1 = self.sizes[1] / 2
sub2 = self.sizes[2] / 2
s02 = self.sizes[0] * self.sizes[0]
s12 = self.sizes[1] * self.sizes[1]
s22 = self.sizes[2] * self.sizes[2]
for i in range(self.sizes[0]):
for j in range(self.sizes[1]):
for k in range(self.sizes[2]):
bounder = ((i - sub0) * (i - sub0)) / s02 + ((j - sub1) * (j - sub1)) / s12 + (
(k - sub2) * (
k - sub2)) / s22
if (bounder > 0.9 and bounder < 1.1): # Need to figure
self.offsets.append([i - sub0, j - sub1, k - sub2]) # out these bounds
if self.dim == 4:
print("Sorry 4D ellipsoidal shells not yet implemented")
# sys.exit(-1)
################# LINE #######################
elif type == "Line":
if len(self.sizes) != 1:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
proto = np.sign(self.axbase) # Generate axis (rely on dimension
# being correct re. above check)
for i in range(1, self.sizes[0] + 1):
self.offsets.append(list(i * proto))
################ NOTCH #######################
elif type == "Notch":
if len(self.sizes) != 1:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
proto = list(np.sign(self.axbase))
if self.dim == 1:
print
"Sorry, no definition for 1 dimensional notches"
# sys.exit(-1)
if self.dim == 2:
# proto must be one of [1,0],[-1,0],[0,1],[0,-1]
# if not assume [1,0]
protoset = [[1, 0], [-1, 0], [0, 1], [0, -1]]
if proto not in protoset:
proto = [1, 0]
if proto == [1, 0]:
for i in range(self.sizes[0] + 1):
for j in range(-self.sizes[0], self.sizes[0] + 1):
if (i > 0 or j <= 0):
self.offsets.append([i, j])
if proto == [-1, 0]:
for i in range(-self.sizes[0], 1):
for j in range(-self.sizes[0], self.sizes[0] + 1):
if (i < 0 or j <= 0):
self.offsets.append([i, j])
if proto == [0, 1]:
for i in range(-self.sizes[0], self.sizes[0] + 1):
for j in range(self.sizes[0] + 1):
if (j > 0 or i >= 0):
self.offsets.append([i, j])
if proto == [0, -1]:
for i in range(-self.sizes[0], self.sizes[0] + 1):
for j in range(-self.sizes[0], 1):
if (j < 0 or i >= 0):
self.offsets.append([i, j])
if self.dim == 3:
protoset = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]
if proto not in protoset:
proto = [1, 0, 0]
if proto == [1, 0, 0]:
for i in range(self.sizes[0] + 1):
for j in range(-self.sizes[0], self.sizes[0] + 1):
for k in range(-self.sizes[0], self.sizes[0] + 1):
if (i > 0 or (i >= 0 and j > 0) or (j >= 0 and k > 0)):
self.offsets.append([i, j, k])
if proto == [-1, 0, 0]:
for i in range(-self.sizes[0], self.sizes[0]):
for j in range(-self.sizes[0], self.sizes[0] + 1):
for k in range(-self.sizes[0], self.sizes[0] + 1):
if (i < 0 or (i <= 0 and j < 0) or (j <= 0 and k < 0)):
self.offsets.append([i, j, k])
if proto == [0, 1, 0]:
for j in range(self.sizes[0] + 1):
for k in range(-self.sizes[0], self.sizes[0] + 1):
for i in range(-self.sizes[0], self.sizes[0] + 1):
if (j > 0 or (j >= 0 and i > 0) or (i >= 0 and k < 0)):
self.offsets.append([i, j, k])
if proto == [0, -1, 0]:
for j in range(-self.sizes[0], self.sizes[0]):
for k in range(-self.sizes[0], self.sizes[0] + 1):
for i in range(-self.sizes[0], self.sizes[0] + 1):
if (j < 0 or (j <= 0 and i > 0) or (i >= 0 and k < 0)):
self.offsets.append([i, j, k])
if proto == [0, 0, 1]:
for k in range(self.sizes[0] + 1):
for i in range(-self.sizes[0], self.sizes[0] + 1):
for j in range(-self.sizes[0], self.sizes[0] + 1):
if (k > 0 or (k >= 0 and j < 0) or (j <= 0 and i > 0)):
self.offsets.append([i, j, k])
if proto == [0, 0, -1]:
for k in range(-self.sizes[0], self.sizes[0]):
for i in range(-self.sizes[0], self.sizes[0] + 1):
for j in range(-self.sizes[0], self.sizes[0] + 1):
if (k < 0 or (k <= 0 and j > 0) or (j >= 0 and i < 0)):
self.offsets.append([i, j, k])
if self.dim == 4:
print
"Sorry 4D notches not yet implemented"
# sys.exit(-1)
################# CONE #######################
elif type == "Cone":
# currently only cones along coordinate axis are supported
if len(self.sizes) != 1:
print(f"sizes array is of length {len(self.sizes)} but must be of length {self.dim} for type {type}")
proto = list(np.sign(self.axbase))
if self.dim == 1:
for i in range(self.sizes[0]):
self.offsets.append([i])
if self.dim == 2:
protoset = [[1, 0], [-1, 0], [0, 1], [0, -1]]
if proto not in protoset:
proto = [1, 0]
if proto == [1, 0]:
for i in range(self.sizes[0]):
for j in range(-i, i + 1):
self.offsets.append([i, j])
if proto == [-1, 0]:
for i in range(self.sizes[0]):
for j in range(-i, i + 1):
self.offsets.append([-i, j])
if proto == [0, 1]:
for j in range(self.sizes[0]):
for i in range(-j, j + 1):
self.offsets.append([i, j])
if proto == [0, -1]:
for j in range(self.sizes[0]):
for i in range(-j, j + 1):
self.offsets.append([i, -j])
if self.dim == 3:
protoset = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]
if proto not in protoset:
proto = [1, 0, 0]
if proto == [1, 0, 0]:
for i in range(self.sizes[0]):
for j in range(-i, i + 1):
for k in range(-i, i + 1):
self.offsets.append([i, j, k])
if proto == [-1, 0, 0]:
for i in range(self.sizes[0]):
for j in range(-i, i + 1):
for k in range(-i, i + 1):
self.offsets.append([-i, j, k])
if proto == [0, 1, 0]:
for j in range(self.sizes[0]):
for k in range(-j, j + 1):
for i in range(-j, j + 1):
self.offsets.append([i, j, k])
if proto == [0, -1, 0]:
for j in range(self.sizes[0]):
for k in range(-j, j + 1):
for i in range(-j, j + 1):
self.offsets.append([i, -j, k])
if proto == [0, 0, 1]:
for k in range(self.sizes[0]):
for i in range(-k, k + 1):
for j in range(-k, k + 1):
self.offsets.append([i, j, k])
if proto == [0, 0, -1]:
for k in range(self.sizes[0]):
for i in range(-k, k + 1):
for j in range(-k, k + 1):
self.offsets.append([i, j, -k])
if self.dim == 4:
# just do it in 4th dimension for now
protoset = [[0, 0, 0, 1], [0, 0, 0, -1]]
if proto not in protoset:
proto = [0, 0, 0, 1]
if proto == [0, 0, 0, 1]:
for t in range(self.sizes[0]):
for i in range(-t, t + 1):
for j in range(-t, t + 1):
for k in range(-t, t + 1):
self.offsets.append([i, j, k, t])
if proto == [0, 0, 0, -1]:
for t in range(self.sizes[0]):
for i in range(-t, t + 1):
for j in range(-t, t + 1):
for k in range(-t, t + 1):
self.offsets.append([i, j, k, -t])
else:
print(f"Type {type} unknow")
for i in range(len(self.offsets)):
self.offsets[i] = list(np.array(self.offsets[i]) + np.array(self.shift))
# Add/Remove anchor point as requested
if inclusion and (self.anchoff not in self.offsets):
self.offsets.append(self.anchoff)
if (not inclusion) and (self.anchoff in self.offsets):
self.offsets.remove(self.anchoff)
# Apply handedness
tempoff = []
for off in self.offsets:
tempoff.append(list(np.array(off) * np.array(self.handedness)))
self.offsets = tempoff
| [
"numpy.array",
"numpy.zeros",
"numpy.sign"
] | [((5458, 5486), 'numpy.zeros', 'np.zeros', (['(self.dim, 2)', 'int'], {}), '((self.dim, 2), int)\n', (5466, 5486), True, 'import numpy as np\n'), ((23117, 23142), 'numpy.array', 'np.array', (['self.offsets[i]'], {}), '(self.offsets[i])\n', (23125, 23142), True, 'import numpy as np\n'), ((23145, 23165), 'numpy.array', 'np.array', (['self.shift'], {}), '(self.shift)\n', (23153, 23165), True, 'import numpy as np\n'), ((23545, 23558), 'numpy.array', 'np.array', (['off'], {}), '(off)\n', (23553, 23558), True, 'import numpy as np\n'), ((23561, 23586), 'numpy.array', 'np.array', (['self.handedness'], {}), '(self.handedness)\n', (23569, 23586), True, 'import numpy as np\n'), ((14060, 14080), 'numpy.sign', 'np.sign', (['self.axbase'], {}), '(self.axbase)\n', (14067, 14080), True, 'import numpy as np\n'), ((14535, 14555), 'numpy.sign', 'np.sign', (['self.axbase'], {}), '(self.axbase)\n', (14542, 14555), True, 'import numpy as np\n'), ((19232, 19252), 'numpy.sign', 'np.sign', (['self.axbase'], {}), '(self.axbase)\n', (19239, 19252), True, 'import numpy as np\n')] |
import numpy as np
from astropy import units as u
from astropy.cosmology import Planck15
from scipy.constants import c
class Converter(object):
def __init__(self):
pass
class HIConverter(object):
def __init__(self, mode='relativistic'):
# HI restframe
self.nu0 = 1420.4058
self.nu0_u = self.nu0 * u.MHz
# full mode for Minkowski space time
if mode.lower() == 'relativistic':
self.v_frame = u.doppler_relativistic(self.nu0_u)
# radio definition
elif mode.lower() == 'radio':
self.v_frame = u.doppler_radio(self.nu0_u)
# velo = c * (1. - nu/nu0)
# optical definition
elif mode.lower() == 'optical':
self.v_frame = u.doppler_optical(self.nu0_u)
self.mode = mode
return None
# velocity-redshift conversions
###############################
def velo2z(self, velo):
"""
Converts radial velocities to redshifts
Input
-----
velo : float or ndarray
Radial velocity in km/s
Returns
-------
z : float or ndarray, same shape as velo
Redshift
"""
if hasattr(velo, '__iter__'):
velo = np.array(velo)
velo *= 1.e3 # from km/s to m/s
v_over_z = velo / c
z = np.sqrt((1. + v_over_z) / (1. - v_over_z)) - 1.
return z
def z2velo(self, z):
"""
Converts redshifts to radial velocities
Input
-----
z : float or ndarray
Redshift
Returns
-------
velo : float or ndarray, same shape as z
Radial velocity in km/s
"""
if hasattr(z, '__iter__'):
z = np.array(z)
velo = (c * z**2. + 2. * c * z) / (z**2. + 2. * z + 2.)
velo /= 1.e3 # from m/s to km/s
return velo
# frequency-redshift conversions
###############################
def z2nu(self, z):
"""
Converts redshifts to HI frequencies
Input
-----
z : float or ndarray
Redshift
Returns
-------
nu : float or ndarray, same shape as z
Observed frequency of HI emission in MHz
"""
if hasattr(z, '__iter__'):
z = np.array(z)
nu = self.nu0 / (1. + z)
return nu
def nu2z(self, nu):
"""
Converts HI frequencies to redshifts
Input
-----
nu : float or ndarray
Observed frequency of HI emission in MHz
Returns
-------
z : float or ndarray, same shape as nu
Redshift
"""
if hasattr(nu, '__iter__'):
nu = np.array(nu)
z = (self.nu0 / nu) - 1.
return z
# velocity-frequency conversions
###############################
def nu2velo(self, nu):
"""
Converts HI frequencies to radial velocities
Input
-----
nu : float or ndarray
HI frequency
Returns
-------
velo : float or ndarray, same shape as nu
Radial velocity in km/s
"""
if hasattr(nu, '__iter__'):
nu = np.array(nu)
nu_u = nu * u.MHz
velo = nu_u.to(u.km / u.s, equivalencies=self.v_frame).value
return velo
def velo2nu(self, velo):
"""
Converts radial velocities to HI frequencies
Input
-----
velo : float or ndarray
Radial velocity in km/s
Returns
-------
nu : float or ndarray, same shape as nu
HI frequency
"""
if hasattr(velo, '__iter__'):
velo = np.array(velo)
velo_u = velo * u.km / u.s
nu = velo_u.to(u.MHz, equivalencies=self.v_frame).value
return nu
# redshift-distance conversions
###############################
def z2d(self, z, local=False):
"""
Converts redshifts into luminosity distances
Input
-----
z : float or ndarray
Redshift
local : bool, optional
If True, assumes a local Hubble law (v = H0 * D). Otherwise,
assume a proper luminosity distance. Either way, the Planck 2015
cosmology is used.
Returns
-------
d : float or ndarray, same shape as z
Luminosity distance in Mpc
"""
if local:
d = c / 1.e3 * z / Planck15.H0.value
else:
d = Planck15.luminosity_distance(z).value
return d
| [
"astropy.cosmology.Planck15.luminosity_distance",
"astropy.units.doppler_relativistic",
"numpy.array",
"astropy.units.doppler_radio",
"astropy.units.doppler_optical",
"numpy.sqrt"
] | [((463, 497), 'astropy.units.doppler_relativistic', 'u.doppler_relativistic', (['self.nu0_u'], {}), '(self.nu0_u)\n', (485, 497), True, 'from astropy import units as u\n'), ((1262, 1276), 'numpy.array', 'np.array', (['velo'], {}), '(velo)\n', (1270, 1276), True, 'import numpy as np\n'), ((1359, 1403), 'numpy.sqrt', 'np.sqrt', (['((1.0 + v_over_z) / (1.0 - v_over_z))'], {}), '((1.0 + v_over_z) / (1.0 - v_over_z))\n', (1366, 1403), True, 'import numpy as np\n'), ((1771, 1782), 'numpy.array', 'np.array', (['z'], {}), '(z)\n', (1779, 1782), True, 'import numpy as np\n'), ((2339, 2350), 'numpy.array', 'np.array', (['z'], {}), '(z)\n', (2347, 2350), True, 'import numpy as np\n'), ((2765, 2777), 'numpy.array', 'np.array', (['nu'], {}), '(nu)\n', (2773, 2777), True, 'import numpy as np\n'), ((3265, 3277), 'numpy.array', 'np.array', (['nu'], {}), '(nu)\n', (3273, 3277), True, 'import numpy as np\n'), ((3763, 3777), 'numpy.array', 'np.array', (['velo'], {}), '(velo)\n', (3771, 3777), True, 'import numpy as np\n'), ((590, 617), 'astropy.units.doppler_radio', 'u.doppler_radio', (['self.nu0_u'], {}), '(self.nu0_u)\n', (605, 617), True, 'from astropy import units as u\n'), ((4591, 4622), 'astropy.cosmology.Planck15.luminosity_distance', 'Planck15.luminosity_distance', (['z'], {}), '(z)\n', (4619, 4622), False, 'from astropy.cosmology import Planck15\n'), ((754, 783), 'astropy.units.doppler_optical', 'u.doppler_optical', (['self.nu0_u'], {}), '(self.nu0_u)\n', (771, 783), True, 'from astropy import units as u\n')] |
#Python wrapper / library for Einstein Analytics API
#core libraries
import sys
import logging
import json
import time
from dateutil import tz
import re
from decimal import Decimal
import base64
import csv
import math
import pkg_resources
# installed libraries
import browser_cookie3
import requests
import unicodecsv
from unidecode import unidecode
import datetime
import pandas as pd
from pandas import json_normalize
import numpy as np
#init logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
logging.basicConfig(format="%(levelname)s: %(message)s")
class salesforceEinsteinAnalytics(object):
def __init__(self, env_url, browser, rawcookie=None, cookiefile=None, logLevel='WARN'):
self.setLogLvl(level=logLevel)
self.env_url = env_url
#Check if package is current version
response = requests.get('https://pypi.org/pypi/SalesforceEinsteinAnalytics/json')
latest_version = response.json()['info']['version']
curr_version = pkg_resources.get_distribution("SalesforceEinsteinAnalytics").version
if curr_version != latest_version:
logging.warning('New version available. Use "pip install SalesforceEinsteinAnalytics --upgrade" to upgrade.')
#get browser cookie to use in request header
if rawcookie != None:
self.header = {'Authorization': 'Bearer '+rawcookie, 'Content-Type': 'application/json'}
elif cookiefile != None:
print('using cookiefile')
try:
if browser == 'chrome':
cj = browser_cookie3.chrome(domain_name=env_url[8:], cookie_file=cookiefile)
my_cookies = requests.utils.dict_from_cookiejar(cj)
self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}
elif browser == 'firefox':
cj = browser_cookie3.firefox(domain_name=env_url[8:], cookie_file=cookiefile)
my_cookies = requests.utils.dict_from_cookiejar(cj)
self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}
else:
logging.error('Please select a valid browser (chrome or firefox)')
sys.exit(1)
except:
logging.error('ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox).')
sys.exit(1)
else:
try:
if browser == 'chrome':
cj = browser_cookie3.chrome(domain_name=env_url[8:]) #remove first 8 characters since browser cookie does not expect "https://"
my_cookies = requests.utils.dict_from_cookiejar(cj)
self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}
elif browser == 'firefox':
cj = browser_cookie3.firefox(domain_name=env_url[8:])
my_cookies = requests.utils.dict_from_cookiejar(cj)
self.header = {'Authorization': 'Bearer '+my_cookies['sid'], 'Content-Type': 'application/json'}
else:
logging.error('Please select a valid browser (chrome or firefox)')
sys.exit(1)
except:
logging.error('ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox).')
sys.exit(1)
def setLogLvl(self, level='WARN'):
if level == 'DEBUG':
logging.getLogger().setLevel(logging.DEBUG)
elif level == 'INFO':
logging.getLogger().setLevel(logging.INFO)
elif level == 'WARN':
logging.getLogger().setLevel(logging.WARN)
else:
logging.getLogger().setLevel(logging.ERROR)
def get_local_time(self, add_sec=None, timeFORfile=False):
#set timezone for displayed operation start time
curr_time = datetime.datetime.utcnow().replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal())
if add_sec is not None:
return (curr_time + datetime.timedelta(seconds=add_sec)).strftime("%I:%M:%S %p")
elif timeFORfile == True:
return curr_time.strftime("%m_%d_%Y__%I%p")
else:
return curr_time.strftime("%I:%M:%S %p")
def get_dataset_id(self, dataset_name, search_type='API Name', verbose=False):
params = {'pageSize': 50, 'sort': 'Mru', 'hasCurrentOnly': 'true', 'q': dataset_name}
dataset_json = requests.get(self.env_url+'/services/data/v46.0/wave/datasets', headers=self.header, params=params)
dataset_df = json_normalize(json.loads(dataset_json.text)['datasets'])
#check if the user wants to seach by API name or label name
if search_type == 'UI Label':
dataset_df = dataset_df[dataset_df['label'] == dataset_name]
else:
dataset_df = dataset_df[dataset_df['name'] == dataset_name]
#show user how many matches that they got. Might want to use exact API name if getting multiple matches for label search.
if verbose == True:
print('Found '+str(dataset_df.shape[0])+' matching datasets.')
#if dataframe is empty then return not found message or return the dataset ID
if dataset_df.empty == True:
logging.warning('Dataset not found. Please check name or API name in Einstein Analytics.')
sys.exit(1)
else:
dsnm = dataset_df['name'].tolist()[0]
dsid = dataset_df['id'].tolist()[0]
#get dataset version ID
r = requests.get(self.env_url+'/services/data/v46.0/wave/datasets/'+dsid, headers=self.header)
dsvid = json.loads(r.text)['currentVersionId']
return dsnm, dsid, dsvid
def run_saql_query(self, saql, save_path=None, verbose=False):
'''
This function takes a saql query as an argument and returns a dataframe or saves to csv
The query can be in JSON form or can be in the UI SAQL form
load statements must have the appropreate spaces: =_load_\"datasetname\";
'''
if verbose == True:
start = time.time()
print('Checking SAQL and Finding Dataset IDs...')
print('Process started at: '+str(self.get_local_time()))
saql = saql.replace('\"','\\"') #convert UI saql query to JSON format
#create a dictionary with all datasets used in the query
load_stmt_old = re.findall(r"(= load )(.*?)(;)", saql)
load_stmt_new = load_stmt_old.copy()
for ls in range(0,len(load_stmt_new)):
load_stmt_old[ls] = ''.join(load_stmt_old[ls])
dsnm, dsid, dsvid = self.get_dataset_id(dataset_name=load_stmt_new[ls][1].replace('\\"',''), verbose=verbose)
load_stmt_new[ls] = ''.join(load_stmt_new[ls])
load_stmt_new[ls] = load_stmt_new[ls].replace(dsnm, dsid+'/'+dsvid)
#update saql with dataset ID and version ID
for i in range(0,len(load_stmt_new)):
saql = saql.replace(load_stmt_old[i], load_stmt_new[i])
saql = saql.replace('\\"','\"')
if verbose == True:
print('Running SAQL Query...')
#run query and return dataframe or save as csv
payload = {"query":saql}
r = requests.post(self.env_url+'/services/data/v46.0/wave/query', headers=self.header, data=json.dumps(payload) )
df = json_normalize(json.loads(r.text)['results']['records'])
if save_path is not None:
if verbose == True:
print('Saving result to CSV...')
df.to_csv(save_path, index=False)
if verbose == True:
end = time.time()
print('Dataframe saved to CSV...')
print('Completed in '+str(round(end-start,3))+'sec')
return df
else:
if verbose == True:
end = time.time()
print('Completed in '+str(round(end-start,3))+'sec')
return df
def restore_previous_dashboard_version(self, dashboard_id, version_num=None, save_json_path=None):
'''
version number goes backwards 0 = current version 20 is max oldest version.
Typically best practice to run the function and view the history first before supplying a version number.
'''
#get broken dashboard version history
r = requests.get(self.env_url+'/services/data/v46.0/wave/dashboards/'+dashboard_id+'/histories', headers=self.header)
history_df = json_normalize(json.loads(r.text)['histories'])
if save_json_path is not None and version_num is not None:
preview_link = history_df['previewUrl'].tolist()[version_num]
r_restore = requests.get(self.env_url+preview_link, headers=self.header)
with open(save_json_path, 'w', encoding='utf-8') as f:
json.dump(r_restore.json(), f, ensure_ascii=False, indent=4)
elif version_num is not None:
payload = { "historyId": history_df['id'].tolist()[version_num] }
fix = requests.put(self.env_url+history_df['revertUrl'].tolist()[version_num], headers=self.header, data=json.dumps(payload))
else:
return history_df
def get_app_user_list(self, app_id=None, save_path=None, verbose=False, max_request_attempts=3):
if verbose == True:
start = time.time()
progress_counter = 0
print('Getting app user list and access details...')
print('Process started at: '+str(self.get_local_time()))
if app_id is None:
'''ALERT: CURRENTLY GETTING AN ERROR FOR ALL APP REQUEST
ERROR = OpenSSL.SSL.SysCallError: (-1, 'Unexpected EOF')
Proposed Solution is to add a try/except block to handle the error
'''
app_user_df = pd.DataFrame()
attempts = 0
while attempts < max_request_attempts:
try:
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders', headers=self.header)
response = json.loads(r.text)
total_size = response['totalSize']
next_page = response['nextPageUrl']
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
for app in response['folders']:
attempts = 0
while attempts < max_request_attempts:
try:
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app["id"], headers=self.header)
users = json.loads(r.text)['shares']
for u in users:
app_user_df = app_user_df.append( { "AppId": app['id'],
"AppName": app['name'],
"UserId": u['sharedWithId'],
"UserName": u['sharedWithLabel'],
"AccessType": u['accessType'],
"UserType": u['shareType']
}, ignore_index=True)
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
#continue to pull data from next page
attempts = 0 # reset attempts for additional pages
while next_page is not None:
progress_counter += 25
if verbose == True:
print('Progress: '+str(round(progress_counter/total_size*100,1))+'%', end='', flush=True)
while attempts < max_request_attempts:
try:
np = requests.get(self.env_url+next_page, headers=self.header)
response = json.loads(np.text)
next_page = response['nextPageUrl']
break
except KeyError:
next_page = None
logging.error(sys.exc_info()[0])
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
while attempts < max_request_attempts:
try:
for app in response['folders']:
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app["id"], headers=self.header)
users = json.loads(r.text)['shares']
for u in users:
app_user_df = app_user_df.append( { "AppId": app['id'],
"AppName": app['name'],
"UserId": u['sharedWithId'],
"UserName": u['sharedWithLabel'],
"AccessType": u['accessType'],
"UserType": u['shareType']
}, ignore_index=True)
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
elif app_id is not None:
app_user_df = pd.DataFrame()
if type(app_id) is list or type(app_id) is tuple:
for app in app_id:
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app, headers=self.header)
response = json.loads(r.text)
for u in response['shares']:
app_user_df = app_user_df.append( { "AppId": app,
"AppName": response['name'],
"UserId": u['sharedWithId'],
"UserName": u['sharedWithLabel'],
"AccessType": u['accessType'],
"UserType": u['shareType']
}, ignore_index=True)
else:
logging.error('Please input a list or tuple of app Ids')
sys.exit(1)
if save_path is not None:
if verbose == True:
print('Saving result to CSV...')
app_user_df.to_csv(save_path, index=False)
if verbose == True:
end = time.time()
print('Dataframe saved to CSV...')
print('Completed in '+str(round(end-start,3))+'sec')
return app_user_df
else:
if verbose == True:
end = time.time()
print('Completed in '+str(round(end-start,3))+'sec')
return app_user_df
def update_app_access(self, user_dict, app_id, update_type, verbose=False):
'''
update types include: addNewUsers, fullReplaceAccess, removeUsers, updateUsers
'''
if verbose == True:
start = time.time()
print('Updating App Access...')
print('Process started at: '+str(self.get_local_time()))
if update_type == 'fullReplaceAccess':
shares = user_dict
elif update_type == 'addNewUsers':
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app_id, headers=self.header)
response = json.loads(r.text)
shares = response['shares']
#remove fields in the JSON that we don't want
for s in shares:
try:
del s['sharedWithLabel']
except:
pass
try:
del s['imageUrl']
except:
pass
shares = shares + user_dict
elif update_type == 'removeUsers':
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app_id, headers=self.header)
response = json.loads(r.text)
shares = response['shares']
to_remove = []
for u in user_dict:
to_remove.append(u['sharedWithId'])
for s in shares:
if s['sharedWithId'] in to_remove:
shares.remove(s)
#remove fields in the JSON that we don't want
for s in shares:
try:
del s['sharedWithLabel']
except:
pass
try:
del s['imageUrl']
except:
pass
elif update_type == 'updateUsers':
r = requests.get(self.env_url+'/services/data/v46.0/wave/folders/'+app_id, headers=self.header)
response = json.loads(r.text)
shares = response['shares']
to_update = []
for u in user_dict:
to_update.append(u['sharedWithId'])
for s in range(0,len(shares)):
if shares[s]['sharedWithId'] in to_update:
shares[s] = next(item for item in user_dict if item["sharedWithId"] == shares[s]['sharedWithId'])
#remove fields in the JSON that we don't want
for s in shares:
try:
del s['sharedWithLabel']
except:
pass
try:
del s['imageUrl']
except:
pass
else:
shares = None
logging.error('Please choose a user update operation. Options are: addNewUsers, fullReplaceAccess, removeUsers, updateUsers')
sys.exit(1)
if shares is not None:
payload = {"shares": shares}
r = requests.patch(self.env_url+'/services/data/v46.0/wave/folders/'+app_id, headers=self.header, data=json.dumps(payload))
if verbose == True:
end = time.time()
print('User Access Updated')
print('Completed in '+str(round(end-start,3))+'sec')
def update_dashboard_access(self, update_df, update_type, verbose=True):
'''
Function to make it easier to update access using dashboard names vs finding all apps needed.
update dataframe should have the following columns: Dashboard Id, Access Type, and User Id
'''
pass
def remove_non_ascii(self, df, columns=None):
if columns == None:
columns = df.columns
else:
columns = columns
for c in columns:
if df[c].dtype == "O":
df[c] = df[c].apply(lambda x: unidecode(x).replace("?",""))
def create_xmd(self, df, dataset_label, useNumericDefaults=True, default_measure_val="0.0", default_measure_fmt="0.0#", charset="UTF-8", deliminator=",", lineterminator="\r\n"):
dataset_label = dataset_label
dataset_api_name = dataset_label.replace(" ","_")
fields = []
for c in df.columns:
if df[c].dtype == "datetime64[ns]":
name = c.replace(" ","_")
name = name.replace("__","_")
date = {
"fullyQualifiedName": name,
"name": name,
"type": "Date",
"label": c,
"format": "yyyy-MM-dd HH:mm:ss"
}
fields.append(date)
elif np.issubdtype(df[c].dtype, np.number):
if useNumericDefaults == True:
precision = 18
scale = 2
elif useNumericDefaults == False:
precision = df[c].astype('str').apply(lambda x: len(x.replace('.', ''))).max()
scale = -df[c].astype('str').apply(lambda x: Decimal(x).as_tuple().exponent).min()
name = c.replace(" ","_")
name = name.replace("__","_")
measure = {
"fullyQualifiedName": name,
"name": name,
"type": "Numeric",
"label": c,
"precision": precision,
"defaultValue": default_measure_val,
"scale": scale,
"format": default_measure_fmt,
"decimalSeparator": "."
}
fields.append(measure)
else:
name = c.replace(" ","_")
name = name.replace("__","_")
dimension = {
"fullyQualifiedName": name,
"name": name,
"type": "Text",
"label": c
}
fields.append(dimension)
xmd = {
"fileFormat": {
"charsetName": charset,
"fieldsDelimitedBy": deliminator,
"linesTerminatedBy": lineterminator
},
"objects": [
{
"connector": "CSV",
"fullyQualifiedName": dataset_api_name,
"label": dataset_label,
"name": dataset_api_name,
"fields": fields
}
]
}
return str(xmd).replace("'",'"')
def load_df_to_EA(self, df, dataset_api_name, xmd=None, encoding='UTF-8', operation='Overwrite', useNumericDefaults=True, default_measure_val="0.0", max_request_attempts=3,
default_measure_fmt="0.0#", charset="UTF-8", deliminator=",", lineterminator="\r\n", removeNONascii=True, ascii_columns=None, fillna=True, dataset_label=None, verbose=False):
'''
field names will show up exactly as the column names in the supplied dataframe
'''
if verbose == True:
start = time.time()
print('Loading Data to Einstein Analytics...')
print('Process started at: '+str(self.get_local_time()))
dataset_api_name = dataset_api_name.replace(" ","_")
if fillna == True:
for c in df.columns:
if df[c].dtype == "O":
df[c].fillna('NONE', inplace=True)
elif np.issubdtype(df[c].dtype, np.number):
df[c].fillna(0, inplace=True)
elif df[c].dtype == "datetime64[ns]":
df[c].fillna(pd.to_datetime('1900-01-01 00:00:00'), inplace=True)
if ascii_columns is not None:
self.remove_non_ascii(df, columns=ascii_columns)
elif removeNONascii == True:
self.remove_non_ascii(df)
# Upload Config Steps
if xmd is not None:
xmd64 = base64.urlsafe_b64encode(json.dumps(xmd).encode(encoding)).decode()
else:
xmd64 = base64.urlsafe_b64encode(self.create_xmd(df, dataset_api_name, useNumericDefaults=useNumericDefaults, default_measure_val=default_measure_val,
default_measure_fmt=default_measure_fmt, charset=charset, deliminator=deliminator, lineterminator=lineterminator).encode(encoding)).decode()
upload_config = {
'Format' : 'CSV',
'EdgemartAlias' : dataset_api_name,
'Operation' : operation,
'Action' : 'None',
'MetadataJson': xmd64
}
r1 = requests.post(self.env_url+'/services/data/v46.0/sobjects/InsightsExternalData', headers=self.header, data=json.dumps(upload_config))
try:
json.loads(r1.text)['success'] == True
except:
logging.error(' Upload Config Failed', exc_info=True)
logging.error(r1.text)
sys.exit(1)
if verbose == True:
print('Upload Configuration Complete...')
print('Chunking and Uploading Data Parts...')
MAX_FILE_SIZE = 10 * 1000 * 1000 - 49
df_memory = sys.getsizeof(df)
rows_in_part = math.ceil(df.shape[0] / math.ceil(df_memory / MAX_FILE_SIZE))
partnum = 0
range_start = 0
max_data_part = rows_in_part
for chunk in range(0, math.ceil(df_memory / MAX_FILE_SIZE)):
df_part = df.iloc[range_start:max_data_part,:]
if chunk == 0:
data_part64 = base64.b64encode(df_part.to_csv(index=False, quotechar='"', quoting=csv.QUOTE_MINIMAL).encode('UTF-8')).decode()
else:
data_part64 = base64.b64encode(df_part.to_csv(index=False, header=False, quotechar='"',quoting=csv.QUOTE_MINIMAL).encode('UTF-8')).decode()
range_start += rows_in_part
max_data_part += rows_in_part
partnum += 1
if verbose == True:
print('\rChunk '+str(chunk+1)+' of '+str(math.ceil(df_memory / MAX_FILE_SIZE))+' completed', end='', flush=True)
payload = {
"InsightsExternalDataId" : json.loads(r1.text)['id'],
"PartNumber" : str(partnum),
"DataFile" : data_part64
}
attempts = 0
while attempts < max_request_attempts:
try:
r2 = requests.post(self.env_url+'/services/data/v46.0/sobjects/InsightsExternalDataPart', headers=self.header, data=json.dumps(payload))
json.loads(r2.text)['success'] == True
break
except:
attempts += 1
logging.error('\n Datapart Upload Failed', exc_info=True)
logging.debug(r2.text)
if verbose == True:
print('\nDatapart Upload Complete...')
payload = {
"Action" : "Process"
}
attempts = 0
while attempts < max_request_attempts:
try:
r3 = requests.patch(self.env_url+'/services/data/v46.0/sobjects/InsightsExternalData/'+json.loads(r1.text)['id'], headers=self.header, data=json.dumps(payload))
break
except TimeoutError as e:
attempts += 1
logging.debug(sys.exc_info()[0])
logging.warning("Connection Timeout Error. Trying again...")
if verbose == True:
end = time.time()
print('Data Upload Process Started. Check Progress in Data Monitor.')
print('Job ID: '+str(json.loads(r1.text)['id']))
print('Completed in '+str(round(end-start,3))+'sec')
def addArchivePrefix(self, warnList, prefix='[ARCHIVE] ', removePrefix=False, verbose=False):
'''
Function to add a warning that an asset will soon be archived.
The name of the dashboard will have the chosen prefix added.
max label length is 80 chars and is right trimmed if longer possibly erasing the original title
Adds prefix to existing label so running twice could overwrite original title
'''
for a in range(0,len(warnList)):
try:
r = requests.get(self.env_url+'/services/data/v46.0/wave/dashboards/'+warnList[a], headers=self.header)
currentLabel = json.loads(r.text)['label']
if removePrefix == True:
if currentLabel[:len(prefix)] == prefix: #adding check to make sure original lable isn't overwritten
newLabel = currentLabel[len(prefix):]
else:
newLabel = prefix+currentLabel
payload = {'label': newLabel[0:79]}
r = requests.patch(self.env_url+'/services/data/v46.0/wave/dashboards/'+warnList[a], headers=self.header, data=json.dumps(payload))
if json.loads(r.text)['label'] == prefix+currentLabel:
logging.debug('Successfully updated asset name for: '+warnList[a])
if verbose == True:
print('Progress: '+str(round(a/len(warnList)*100,1))+'%', end='', flush=True)
except:
try:
r = requests.get(self.env_url+'/services/data/v46.0/wave/lenses/'+warnList[a], headers=self.header)
currentLabel = json.loads(r.text)['label']
if removePrefix == True:
if currentLabel[:len(prefix)] == prefix: #adding check to make sure original lable isn't overwritten
newLabel = currentLabel[len(prefix):]
else:
newLabel = prefix+currentLabel
payload = {'label': newLabel[0:79]} #max char len for label = 80
r = requests.patch(self.env_url+'/services/data/v46.0/wave/lenses/'+warnList[a], headers=self.header, data=json.dumps(payload))
#debugging code that should be removed
if json.loads(r.text)['label'] == prefix+currentLabel:
logging.debug('Successfully updated asset name for: '+warnList[a])
##########################################
if verbose == True:
print('Progress: '+str(round(a/len(warnList)*100,1))+'%', end='', flush=True)
except:
logging.warning(' could not update asset label: '+warnList[a])
def archiveAssets(self, archiveAppId, ToMoveList, verbose=False):
'''
ToMoveList can be the Ids for either a dashboard or a lens
'''
payload = {'folder': {'id':archiveAppId} }
for a in range(0,len(ToMoveList)):
try:
r = requests.patch(self.env_url+'/services/data/v46.0/wave/dashboards/'+ToMoveList[a], headers=self.header, data=json.dumps(payload) )
if json.loads(r.text)['folder']['id'] == archiveAppId: #check to ensure response has new folder id
if verbose == True:
print('Progress: '+str(round(a/len(ToMoveList)*100,1))+'%', end='', flush=True)
logging.debug('Successfully archived (type=dashboard): '+ToMoveList[a])
except:
# if response does not contain the new folder id then try same command for a lens
try:
r = requests.patch(self.env_url+'/services/data/v46.0/wave/lenses/'+ToMoveList[a], headers=self.header, data=json.dumps(payload) )
if json.loads(r.text)['folder']['id'] == archiveAppId: #check to ensure response has new folder id
if verbose == True:
print('Progress: '+str(round(a/len(ToMoveList)*100,1))+'%', end='', flush=True)
logging.debug('Successfully archived (type=lens): '+ToMoveList[a])
except:
logging.warning(' could not move asset: '+ToMoveList[a])
def getMetaData(self, appIdList, objectList=['dashboards','lenses','datasets'], max_request_attempts=3, verbose=False):
progress_counter = 0
convertToDateList = ['createdDate','lastModifiedDate','refreshDate']
assets_df = pd.DataFrame()
for a in appIdList:
if verbose == True:
progress_counter += 1
print('Progress: '+str(round(progress_counter/len(appIdList)*100,1))+'%', end='', flush=True)
params = {'pageSize': 50, 'sort': 'Mru', 'hasCurrentOnly': 'true', 'folderId': a}
for obj in objectList:
attempts = 0
while attempts < max_request_attempts:
try:
r1 = requests.get(self.env_url+'/services/data/v46.0/wave/'+obj, headers=self.header, params=params)
response = json.loads(r1.text)
app_assets_df = json_normalize(response[obj])
total_size = response['totalSize']
try:
next_page = json.loads(r1.text)['nextPageUrl']
except KeyError as e:
logging.debug(e)
next_page = None
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
assets_df = assets_df.append(app_assets_df, ignore_index=True)
#continue to pull data from next page if found
attempts = 0 # reset attempts for additional pages
while next_page is not None:
while attempts < max_request_attempts:
try:
r1 = requests.get(self.env_url+next_page, headers=self.header, params=params)
app_assets_df = json_normalize(json.loads(r1.text)[obj])
try:
next_page = json.loads(r1.text)['nextPageUrl']
except KeyError as e:
logging.debug(e)
next_page = None
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
assets_df = assets_df.append(app_assets_df, ignore_index=True)
for i in convertToDateList:
assets_df[i].fillna('1900-01-01T00:00:00.000Z', inplace=True)
assets_df[i] = assets_df[i].apply(lambda x: pd.to_datetime(x))
return assets_df
def getAssetCounts(self, appIdList=None, countsToReturn=['dashboards','lenses','datasets'], max_request_attempts=3, verbose=False):
if appIdList is not None:
df = self.getMetaData(appIdList=appIdList, objectList=countsToReturn, verbose=verbose)
df = df.groupby(['folder.id','folder.label','type'], as_index=True).agg({'id':['count']})
df = df.pivot_table('id', ['folder.id', 'folder.label'], 'type')
df.columns = df.columns.droplevel()
df = df.reset_index()
updateColNames = {
'dashboard': 'dashboardCount',
'dataset': 'datasetCount',
'lens': 'lensCount',
}
df.rename(columns=updateColNames, inplace=True)
df.columns.names = ['index']
else:
progress_counter = 0
params = {'pageSize': 50}
# get list of all folders that the user has access to
r = requests.get(self.env_url+'/services/data/v48.0/wave/folders', headers=self.header, params=params)
response = json.loads(r.text)
apps_df = pd.json_normalize(response['folders'])
total_size = response['totalSize']
next_page = response['nextPageUrl']
#continue to pull data from next page if found
attempts = 0 # reset attempts for additional pages
while next_page is not None:
progress_counter += 50
if verbose == True:
print('Collecting App List Progress: '+str(round(progress_counter/total_size*100,1))+'%', end='', flush=True)
while attempts < max_request_attempts:
try:
r1 = requests.get(self.env_url+next_page, headers=self.header, params=params)
np_df = json_normalize(json.loads(r1.text)['folders'])
try:
next_page = json.loads(r1.text)['nextPageUrl']
except KeyError as e:
logging.debug(e)
next_page = None
break
except:
attempts += 1
logging.warning("Unexpected error:", sys.exc_info()[0])
logging.warning("Trying again...")
apps_df = apps_df.append(np_df, ignore_index=True)
if verbose == True:
print('Getting asset counts for '+len(apps_df['id'].tolist())+' apps.')
df = self.getMetaData(appIdList=apps_df['id'].tolist(), objectList=countsToReturn, verbose=verbose)
df = df.groupby(['folder.id','folder.label','type'], as_index=True).agg({'id':['count']})
df = df.pivot_table('id', ['folder.id', 'folder.label'], 'type')
df.columns = df.columns.droplevel()
df = df.reset_index()
updateColNames = {
'dashboard': 'dashboardCount',
'dataset': 'datasetCount',
'lens': 'lensCount',
}
df.rename(columns=updateColNames, inplace=True)
df.columns.names = ['index']
return df
if __name__ == '__main__':
pass
| [
"json.dumps",
"requests.utils.dict_from_cookiejar",
"datetime.datetime.utcnow",
"logging.NullHandler",
"sys.getsizeof",
"sys.exc_info",
"pandas.DataFrame",
"pkg_resources.get_distribution",
"logging.error",
"json.loads",
"logging.warning",
"dateutil.tz.tzlocal",
"re.findall",
"datetime.tim... | [((518, 574), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s: %(message)s"""'}), "(format='%(levelname)s: %(message)s')\n", (537, 574), False, 'import logging\n'), ((495, 516), 'logging.NullHandler', 'logging.NullHandler', ([], {}), '()\n', (514, 516), False, 'import logging\n'), ((456, 483), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (473, 483), False, 'import logging\n'), ((821, 891), 'requests.get', 'requests.get', (['"""https://pypi.org/pypi/SalesforceEinsteinAnalytics/json"""'], {}), "('https://pypi.org/pypi/SalesforceEinsteinAnalytics/json')\n", (833, 891), False, 'import requests\n'), ((4154, 4260), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/datasets')"], {'headers': 'self.header', 'params': 'params'}), "(self.env_url + '/services/data/v46.0/wave/datasets', headers=\n self.header, params=params)\n", (4166, 4260), False, 'import requests\n'), ((5917, 5954), 're.findall', 're.findall', (['"""(= load )(.*?)(;)"""', 'saql'], {}), "('(= load )(.*?)(;)', saql)\n", (5927, 5954), False, 'import re\n'), ((7580, 7703), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/dashboards/' + dashboard_id +\n '/histories')"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/dashboards/' +\n dashboard_id + '/histories', headers=self.header)\n", (7592, 7703), False, 'import requests\n'), ((19832, 19849), 'sys.getsizeof', 'sys.getsizeof', (['df'], {}), '(df)\n', (19845, 19849), False, 'import sys\n'), ((25695, 25709), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (25707, 25709), True, 'import pandas as pd\n'), ((963, 1024), 'pkg_resources.get_distribution', 'pkg_resources.get_distribution', (['"""SalesforceEinsteinAnalytics"""'], {}), "('SalesforceEinsteinAnalytics')\n", (993, 1024), False, 'import pkg_resources\n'), ((1073, 1192), 'logging.warning', 'logging.warning', (['"""New version available. Use "pip install SalesforceEinsteinAnalytics --upgrade" to upgrade."""'], {}), '(\n \'New version available. Use "pip install SalesforceEinsteinAnalytics --upgrade" to upgrade.\'\n )\n', (1088, 1192), False, 'import logging\n'), ((3687, 3699), 'dateutil.tz.tzlocal', 'tz.tzlocal', ([], {}), '()\n', (3697, 3699), False, 'from dateutil import tz\n'), ((4887, 4983), 'logging.warning', 'logging.warning', (['"""Dataset not found. Please check name or API name in Einstein Analytics."""'], {}), "(\n 'Dataset not found. Please check name or API name in Einstein Analytics.')\n", (4902, 4983), False, 'import logging\n'), ((4982, 4993), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4990, 4993), False, 'import sys\n'), ((5120, 5218), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/datasets/' + dsid)"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/datasets/' + dsid,\n headers=self.header)\n", (5132, 5218), False, 'import requests\n'), ((5637, 5648), 'time.time', 'time.time', ([], {}), '()\n', (5646, 5648), False, 'import time\n'), ((7902, 7964), 'requests.get', 'requests.get', (['(self.env_url + preview_link)'], {'headers': 'self.header'}), '(self.env_url + preview_link, headers=self.header)\n', (7914, 7964), False, 'import requests\n'), ((8489, 8500), 'time.time', 'time.time', ([], {}), '()\n', (8498, 8500), False, 'import time\n'), ((8879, 8893), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8891, 8893), True, 'import pandas as pd\n'), ((12920, 12931), 'time.time', 'time.time', ([], {}), '()\n', (12929, 12931), False, 'import time\n'), ((15116, 15127), 'time.time', 'time.time', ([], {}), '()\n', (15125, 15127), False, 'import time\n'), ((18105, 18116), 'time.time', 'time.time', ([], {}), '()\n', (18114, 18116), False, 'import time\n'), ((20017, 20053), 'math.ceil', 'math.ceil', (['(df_memory / MAX_FILE_SIZE)'], {}), '(df_memory / MAX_FILE_SIZE)\n', (20026, 20053), False, 'import math\n'), ((21706, 21717), 'time.time', 'time.time', ([], {}), '()\n', (21715, 21717), False, 'import time\n'), ((28434, 28539), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v48.0/wave/folders')"], {'headers': 'self.header', 'params': 'params'}), "(self.env_url + '/services/data/v48.0/wave/folders', headers=\n self.header, params=params)\n", (28446, 28539), False, 'import requests\n'), ((28547, 28565), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (28557, 28565), False, 'import json\n'), ((28579, 28617), 'pandas.json_normalize', 'pd.json_normalize', (["response['folders']"], {}), "(response['folders'])\n", (28596, 28617), True, 'import pandas as pd\n'), ((4285, 4314), 'json.loads', 'json.loads', (['dataset_json.text'], {}), '(dataset_json.text)\n', (4295, 4314), False, 'import json\n'), ((5222, 5240), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (5232, 5240), False, 'import json\n'), ((6732, 6751), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (6742, 6751), False, 'import json\n'), ((6987, 6998), 'time.time', 'time.time', ([], {}), '()\n', (6996, 6998), False, 'import time\n'), ((7150, 7161), 'time.time', 'time.time', ([], {}), '()\n', (7159, 7161), False, 'import time\n'), ((7724, 7742), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (7734, 7742), False, 'import json\n'), ((11598, 11612), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (11610, 11612), True, 'import pandas as pd\n'), ((12445, 12456), 'time.time', 'time.time', ([], {}), '()\n', (12454, 12456), False, 'import time\n'), ((12621, 12632), 'time.time', 'time.time', ([], {}), '()\n', (12630, 12632), False, 'import time\n'), ((13138, 13237), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app_id)"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app_id,\n headers=self.header)\n", (13150, 13237), False, 'import requests\n'), ((13244, 13262), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (13254, 13262), False, 'import json\n'), ((16322, 16359), 'numpy.issubdtype', 'np.issubdtype', (['df[c].dtype', 'np.number'], {}), '(df[c].dtype, np.number)\n', (16335, 16359), True, 'import numpy as np\n'), ((19470, 19495), 'json.dumps', 'json.dumps', (['upload_config'], {}), '(upload_config)\n', (19480, 19495), False, 'import json\n'), ((19560, 19613), 'logging.error', 'logging.error', (['""" Upload Config Failed"""'], {'exc_info': '(True)'}), "(' Upload Config Failed', exc_info=True)\n", (19573, 19613), False, 'import logging\n'), ((19617, 19639), 'logging.error', 'logging.error', (['r1.text'], {}), '(r1.text)\n', (19630, 19639), False, 'import logging\n'), ((19643, 19654), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (19651, 19654), False, 'import sys\n'), ((19891, 19927), 'math.ceil', 'math.ceil', (['(df_memory / MAX_FILE_SIZE)'], {}), '(df_memory / MAX_FILE_SIZE)\n', (19900, 19927), False, 'import math\n'), ((22372, 22479), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/dashboards/' + warnList[a])"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/dashboards/' +\n warnList[a], headers=self.header)\n", (22384, 22479), False, 'import requests\n'), ((3244, 3263), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3261, 3263), False, 'import logging\n'), ((6776, 6794), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (6786, 6794), False, 'import json\n'), ((8970, 9060), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders')"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders', headers=\n self.header)\n", (8982, 9060), False, 'import requests\n'), ((9070, 9088), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (9080, 9088), False, 'import json\n'), ((12198, 12254), 'logging.error', 'logging.error', (['"""Please input a list or tuple of app Ids"""'], {}), "('Please input a list or tuple of app Ids')\n", (12211, 12254), False, 'import logging\n'), ((12259, 12270), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (12267, 12270), False, 'import sys\n'), ((13562, 13661), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app_id)"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app_id,\n headers=self.header)\n", (13574, 13661), False, 'import requests\n'), ((13668, 13686), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (13678, 13686), False, 'import json\n'), ((15063, 15082), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (15073, 15082), False, 'import json\n'), ((18405, 18442), 'numpy.issubdtype', 'np.issubdtype', (['df[c].dtype', 'np.number'], {}), '(df[c].dtype, np.number)\n', (18418, 18442), True, 'import numpy as np\n'), ((19507, 19526), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (19517, 19526), False, 'import json\n'), ((20679, 20698), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (20689, 20698), False, 'import json\n'), ((21610, 21671), 'logging.warning', 'logging.warning', (['"""Connection Timeout Error. Trying again..."""'], {}), "('Connection Timeout Error. Trying again...')\n", (21625, 21671), False, 'import logging\n'), ((22491, 22509), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (22501, 22509), False, 'import json\n'), ((22984, 23052), 'logging.debug', 'logging.debug', (["('Successfully updated asset name for: ' + warnList[a])"], {}), "('Successfully updated asset name for: ' + warnList[a])\n", (22997, 23052), False, 'import logging\n'), ((24782, 24855), 'logging.debug', 'logging.debug', (["('Successfully archived (type=dashboard): ' + ToMoveList[a])"], {}), "('Successfully archived (type=dashboard): ' + ToMoveList[a])\n", (24795, 24855), False, 'import logging\n'), ((27511, 27528), 'pandas.to_datetime', 'pd.to_datetime', (['x'], {}), '(x)\n', (27525, 27528), True, 'import pandas as pd\n'), ((1460, 1531), 'browser_cookie3.chrome', 'browser_cookie3.chrome', ([], {'domain_name': 'env_url[8:]', 'cookie_file': 'cookiefile'}), '(domain_name=env_url[8:], cookie_file=cookiefile)\n', (1482, 1531), False, 'import browser_cookie3\n'), ((1556, 1594), 'requests.utils.dict_from_cookiejar', 'requests.utils.dict_from_cookiejar', (['cj'], {}), '(cj)\n', (1590, 1594), False, 'import requests\n'), ((2129, 2263), 'logging.error', 'logging.error', (['"""ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox)."""'], {}), "(\n 'ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox).'\n )\n", (2142, 2263), False, 'import logging\n'), ((2261, 2272), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2269, 2272), False, 'import sys\n'), ((2337, 2384), 'browser_cookie3.chrome', 'browser_cookie3.chrome', ([], {'domain_name': 'env_url[8:]'}), '(domain_name=env_url[8:])\n', (2359, 2384), False, 'import browser_cookie3\n'), ((2484, 2522), 'requests.utils.dict_from_cookiejar', 'requests.utils.dict_from_cookiejar', (['cj'], {}), '(cj)\n', (2518, 2522), False, 'import requests\n'), ((3033, 3167), 'logging.error', 'logging.error', (['"""ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox)."""'], {}), "(\n 'ERROR: Could not get session ID. Make sure you are logged into a live Salesforce session (chrome/firefox).'\n )\n", (3046, 3167), False, 'import logging\n'), ((3165, 3176), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3173, 3176), False, 'import sys\n'), ((3318, 3337), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3335, 3337), False, 'import logging\n'), ((3622, 3648), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (3646, 3648), False, 'import datetime\n'), ((3664, 3674), 'dateutil.tz.tzutc', 'tz.tzutc', ([], {}), '()\n', (3672, 3674), False, 'from dateutil import tz\n'), ((3759, 3794), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'add_sec'}), '(seconds=add_sec)\n', (3777, 3794), False, 'import datetime\n'), ((8298, 8317), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (8308, 8317), False, 'import json\n'), ((9278, 9312), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (9293, 9312), False, 'import logging\n'), ((9429, 9532), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app['id'])"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app['id'\n ], headers=self.header)\n", (9441, 9532), False, 'import requests\n'), ((10413, 10472), 'requests.get', 'requests.get', (['(self.env_url + next_page)'], {'headers': 'self.header'}), '(self.env_url + next_page, headers=self.header)\n', (10425, 10472), False, 'import requests\n'), ((10488, 10507), 'json.loads', 'json.loads', (['np.text'], {}), '(np.text)\n', (10498, 10507), False, 'import json\n'), ((11698, 11794), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app)"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app,\n headers=self.header)\n", (11710, 11794), False, 'import requests\n'), ((11803, 11821), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (11813, 11821), False, 'import json\n'), ((14115, 14214), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app_id)"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app_id,\n headers=self.header)\n", (14127, 14214), False, 'import requests\n'), ((14221, 14239), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (14231, 14239), False, 'import json\n'), ((14755, 14891), 'logging.error', 'logging.error', (['"""Please choose a user update operation. Options are: addNewUsers, fullReplaceAccess, removeUsers, updateUsers"""'], {}), "(\n 'Please choose a user update operation. Options are: addNewUsers, fullReplaceAccess, removeUsers, updateUsers'\n )\n", (14768, 14891), False, 'import logging\n'), ((14885, 14896), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (14893, 14896), False, 'import sys\n'), ((21075, 21135), 'logging.error', 'logging.error', (['"""\n Datapart Upload Failed"""'], {'exc_info': '(True)'}), '("""\n Datapart Upload Failed""", exc_info=True)\n', (21088, 21135), False, 'import logging\n'), ((21138, 21160), 'logging.debug', 'logging.debug', (['r2.text'], {}), '(r2.text)\n', (21151, 21160), False, 'import logging\n'), ((21491, 21510), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (21501, 21510), False, 'import json\n'), ((22899, 22918), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (22909, 22918), False, 'import json\n'), ((22927, 22945), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (22937, 22945), False, 'import json\n'), ((23188, 23292), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/lenses/' + warnList[a])"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/lenses/' + warnList[\n a], headers=self.header)\n", (23200, 23292), False, 'import requests\n'), ((24540, 24559), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (24550, 24559), False, 'import json\n'), ((26076, 26180), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/' + obj)"], {'headers': 'self.header', 'params': 'params'}), "(self.env_url + '/services/data/v46.0/wave/' + obj, headers=\n self.header, params=params)\n", (26088, 26180), False, 'import requests\n'), ((26189, 26208), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (26199, 26208), False, 'import json\n'), ((26231, 26260), 'pandas.json_normalize', 'json_normalize', (['response[obj]'], {}), '(response[obj])\n', (26245, 26260), False, 'from pandas import json_normalize\n'), ((29062, 29136), 'requests.get', 'requests.get', (['(self.env_url + next_page)'], {'headers': 'self.header', 'params': 'params'}), '(self.env_url + next_page, headers=self.header, params=params)\n', (29074, 29136), False, 'import requests\n'), ((1753, 1825), 'browser_cookie3.firefox', 'browser_cookie3.firefox', ([], {'domain_name': 'env_url[8:]', 'cookie_file': 'cookiefile'}), '(domain_name=env_url[8:], cookie_file=cookiefile)\n', (1776, 1825), False, 'import browser_cookie3\n'), ((1850, 1888), 'requests.utils.dict_from_cookiejar', 'requests.utils.dict_from_cookiejar', (['cj'], {}), '(cj)\n', (1884, 1888), False, 'import requests\n'), ((2021, 2087), 'logging.error', 'logging.error', (['"""Please select a valid browser (chrome or firefox)"""'], {}), "('Please select a valid browser (chrome or firefox)')\n", (2034, 2087), False, 'import logging\n'), ((2099, 2110), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2107, 2110), False, 'import sys\n'), ((2681, 2729), 'browser_cookie3.firefox', 'browser_cookie3.firefox', ([], {'domain_name': 'env_url[8:]'}), '(domain_name=env_url[8:])\n', (2704, 2729), False, 'import browser_cookie3\n'), ((2754, 2792), 'requests.utils.dict_from_cookiejar', 'requests.utils.dict_from_cookiejar', (['cj'], {}), '(cj)\n', (2788, 2792), False, 'import requests\n'), ((2925, 2991), 'logging.error', 'logging.error', (['"""Please select a valid browser (chrome or firefox)"""'], {}), "('Please select a valid browser (chrome or firefox)')\n", (2938, 2991), False, 'import logging\n'), ((3003, 3014), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3011, 3014), False, 'import sys\n'), ((3391, 3410), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3408, 3410), False, 'import logging\n'), ((3445, 3464), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (3462, 3464), False, 'import logging\n'), ((9538, 9556), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (9548, 9556), False, 'import json\n'), ((10039, 10073), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (10054, 10073), False, 'import logging\n'), ((10759, 10793), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (10774, 10793), False, 'import logging\n'), ((10898, 11001), 'requests.get', 'requests.get', (["(self.env_url + '/services/data/v46.0/wave/folders/' + app['id'])"], {'headers': 'self.header'}), "(self.env_url + '/services/data/v46.0/wave/folders/' + app['id'\n ], headers=self.header)\n", (10910, 11001), False, 'import requests\n'), ((11517, 11551), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (11532, 11551), False, 'import logging\n'), ((20962, 20981), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (20972, 20981), False, 'import json\n'), ((20988, 21007), 'json.loads', 'json.loads', (['r2.text'], {}), '(r2.text)\n', (20998, 21007), False, 'import json\n'), ((21438, 21457), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (21448, 21457), False, 'import json\n'), ((21587, 21601), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (21599, 21601), False, 'import sys\n'), ((21815, 21834), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (21825, 21834), False, 'import json\n'), ((23304, 23322), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (23314, 23322), False, 'import json\n'), ((23881, 23949), 'logging.debug', 'logging.debug', (["('Successfully updated asset name for: ' + warnList[a])"], {}), "('Successfully updated asset name for: ' + warnList[a])\n", (23894, 23949), False, 'import logging\n'), ((24124, 24188), 'logging.warning', 'logging.warning', (["(' could not update asset label: ' + warnList[a])"], {}), "(' could not update asset label: ' + warnList[a])\n", (24139, 24188), False, 'import logging\n'), ((24569, 24587), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (24579, 24587), False, 'import json\n'), ((25319, 25387), 'logging.debug', 'logging.debug', (["('Successfully archived (type=lens): ' + ToMoveList[a])"], {}), "('Successfully archived (type=lens): ' + ToMoveList[a])\n", (25332, 25387), False, 'import logging\n'), ((25403, 25461), 'logging.warning', 'logging.warning', (["(' could not move asset: ' + ToMoveList[a])"], {}), "(' could not move asset: ' + ToMoveList[a])\n", (25418, 25461), False, 'import logging\n'), ((26556, 26590), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (26571, 26590), False, 'import logging\n'), ((26865, 26939), 'requests.get', 'requests.get', (['(self.env_url + next_page)'], {'headers': 'self.header', 'params': 'params'}), '(self.env_url + next_page, headers=self.header, params=params)\n', (26877, 26939), False, 'import requests\n'), ((29450, 29484), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (29465, 29484), False, 'import logging\n'), ((9254, 9268), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (9266, 9268), False, 'import sys\n'), ((11008, 11026), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (11018, 11026), False, 'import json\n'), ((15708, 15720), 'unidecode.unidecode', 'unidecode', (['x'], {}), '(x)\n', (15717, 15720), False, 'from unidecode import unidecode\n'), ((18539, 18576), 'pandas.to_datetime', 'pd.to_datetime', (['"""1900-01-01 00:00:00"""'], {}), "('1900-01-01 00:00:00')\n", (18553, 18576), True, 'import pandas as pd\n'), ((18824, 18839), 'json.dumps', 'json.dumps', (['xmd'], {}), '(xmd)\n', (18834, 18839), False, 'import json\n'), ((20560, 20596), 'math.ceil', 'math.ceil', (['(df_memory / MAX_FILE_SIZE)'], {}), '(df_memory / MAX_FILE_SIZE)\n', (20569, 20596), False, 'import math\n'), ((23744, 23763), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (23754, 23763), False, 'import json\n'), ((23823, 23841), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (23833, 23841), False, 'import json\n'), ((25074, 25093), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (25084, 25093), False, 'import json\n'), ((26332, 26351), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (26342, 26351), False, 'import json\n'), ((26402, 26418), 'logging.debug', 'logging.debug', (['e'], {}), '(e)\n', (26415, 26418), False, 'import logging\n'), ((27266, 27300), 'logging.warning', 'logging.warning', (['"""Trying again..."""'], {}), "('Trying again...')\n", (27281, 27300), False, 'import logging\n'), ((29164, 29183), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (29174, 29183), False, 'import json\n'), ((29226, 29245), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (29236, 29245), False, 'import json\n'), ((29296, 29312), 'logging.debug', 'logging.debug', (['e'], {}), '(e)\n', (29309, 29312), False, 'import logging\n'), ((10014, 10028), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10026, 10028), False, 'import sys\n'), ((10627, 10641), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10639, 10641), False, 'import sys\n'), ((10734, 10748), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (10746, 10748), False, 'import sys\n'), ((11492, 11506), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (11504, 11506), False, 'import sys\n'), ((25104, 25122), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (25114, 25122), False, 'import json\n'), ((26531, 26545), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (26543, 26545), False, 'import sys\n'), ((26976, 26995), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (26986, 26995), False, 'import json\n'), ((27034, 27053), 'json.loads', 'json.loads', (['r1.text'], {}), '(r1.text)\n', (27044, 27053), False, 'import json\n'), ((27106, 27122), 'logging.debug', 'logging.debug', (['e'], {}), '(e)\n', (27119, 27122), False, 'import logging\n'), ((29425, 29439), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (29437, 29439), False, 'import sys\n'), ((27240, 27254), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (27252, 27254), False, 'import sys\n'), ((16603, 16613), 'decimal.Decimal', 'Decimal', (['x'], {}), '(x)\n', (16610, 16613), False, 'from decimal import Decimal\n')] |
import copy
import glob
import os
import re
from collections import defaultdict
from datetime import date
from datetime import datetime
import numpy
import pytz
from mxio import read_header
from mxdc.utils import misc
FRAME_NUMBER_DIGITS = 4
OUTLIER_DEVIATION = 50
class StrategyType(object):
SINGLE, FULL, SCREEN_1, SCREEN_2, SCREEN_3, SCREEN_4, POWDER = range(7)
Strategy = {
StrategyType.SINGLE: {
'range': 1.0, 'delta': 1.0, 'start': 0.0, 'inverse': False,
'desc': 'Single Frame',
'activity': 'test',
},
StrategyType.FULL: {
'range': 180,
'desc': 'Full Dataset',
'activity': 'data',
},
StrategyType.SCREEN_4: {
'delta': 0.5, 'range': 2, 'start': 0.0, 'inverse': False,
'desc': 'Screen 0°, 90°, 180°, 270°',
'activity': 'screen'
},
StrategyType.SCREEN_3: {
'delta': 0.5, 'range': 2, 'start': 0.0, 'inverse': False,
'desc': 'Screen 0°, 45°, 90°',
'activity': 'screen'
},
StrategyType.SCREEN_2: {
'delta': 0.5, 'range': 2, 'start': 0.0, 'inverse': False,
'desc': 'Screen 0°, 90°',
'activity': 'screen'
},
StrategyType.SCREEN_1: {
'delta': 0.5, 'range': 2, 'start': 0.0, 'inverse': False,
'desc': 'Screen 0°',
'activity': 'screen'
},
StrategyType.POWDER: {
'delta': 180.0, 'exposure': 30.0, 'range': 360.0, 'inverse': False,
'desc': 'Powder',
'activity': 'data'
}
}
StrategyDataType = {
StrategyType.SINGLE: 'SCREEN',
StrategyType.FULL: 'DATA',
StrategyType.SCREEN_4: 'SCREEN',
StrategyType.SCREEN_3: 'SCREEN',
StrategyType.SCREEN_2: 'SCREEN',
StrategyType.SCREEN_1: 'SCREEN',
StrategyType.POWDER: 'XRD'
}
StrategyProcType = {
StrategyType.SINGLE: '',
StrategyType.FULL: 'proc-native',
StrategyType.SCREEN_4: 'proc-screen',
StrategyType.SCREEN_3: 'proc-screen',
StrategyType.SCREEN_2: 'proc-screen',
StrategyType.SCREEN_1: 'proc-screen',
StrategyType.POWDER: 'proc-powder'
}
ScreeningRange = {
StrategyType.SCREEN_4: 315,
StrategyType.SCREEN_3: 135,
StrategyType.SCREEN_2: 135,
StrategyType.SCREEN_1: 45,
}
ScreeningAngles = {
StrategyType.SCREEN_4: (0, 90, 180, 270),
StrategyType.SCREEN_3: (0, 45, 90),
StrategyType.SCREEN_2: (0, 90),
StrategyType.SCREEN_1: (0,),
}
class AnalysisType:
MX_NATIVE, MX_ANOM, MX_SCREEN, RASTER, XRD = range(5)
def update_for_sample(info, sample=None, overwrite=True):
# Add directory and related auxillary information to dictionary
# provides values for {session} {sample}, {group}, {container}, {port}, {date}, {activity}
from mxdc.conf import settings
sample = {} if not sample else sample
params = copy.deepcopy(info)
params.update({
'session': settings.get_session(),
'sample': misc.slugify(sample.get('name', '')),
'group': misc.slugify(sample.get('group', '')),
'container': misc.slugify(sample.get('container', '')),
'port': sample.get('port', ''),
'position': '' if not sample.get('location', '') else sample['location'].zfill(2),
'date': date.today().strftime('%Y%m%d'),
'activity': params.get('activity', ''),
'sample_id': sample.get('id'),
})
template = settings.get_string('directory-template')
activity_template = template[1:] if template[0] == os.sep else template
activity_template = activity_template[:-1] if activity_template[-1] == os.sep else activity_template
dir_template = os.path.join(misc.get_project_home(), '{session}', activity_template)
params['directory'] = dir_template.format(**params).replace('//', '/').replace('//', '/')
if not overwrite and os.path.exists(params['directory']):
for i in range(99):
new_directory = '{}-{}'.format(params['directory'], i + 1)
if not os.path.exists(new_directory):
params['directory'] = new_directory
break
params['sample'] = sample
return params
class NameManager(object):
"""
An object which keeps track of dataset names in a run list and makes sure
unique names are generated
"""
def __init__(self, sample='test'):
self.sample = sample
self.history = defaultdict(list)
def reset(self, sample=None):
if sample is not None:
self.sample = sample
self.history = defaultdict(list)
def fix(self, name):
m = re.match(rf'^(.+)_(\d+)$', name)
if m:
root = m.group(1)
num = int(m.group(2))
else:
root = name
num = 0
if num not in self.history[root]:
new_num = num
else:
new_num = max(self.history[root]) + 1
self.history[root].append(new_num)
new_name = root if new_num == 0 else f'{root}_{new_num}'
return new_name
def get(self, name=None):
name = name if name else self.sample
return self.fix(name)
def summarize_list(values):
"""
Takes a list of integers such as [1,2,3,4,6,7,8] and summarises it as a string "1-4,6-8"
:param values:
:return: string
"""
sorted_values = numpy.array(sorted(values))
summaries = [
(f'{chunk[0]}-{chunk[-1]}' if len(chunk) > 1 else f'{chunk[0]}')
for chunk in numpy.split(sorted_values, numpy.where(numpy.diff(sorted_values) > 1)[0] + 1)
if len(chunk)
]
return ','.join(summaries)
def summarize_gaps(values):
"""
Takes a list of integers such as [1,2,3,4,7,8] and reduces it to the string of skipped regions such as "5-6"
:param values:
:return: string summary
"""
complete_set = set(range(1, max(values) + 1))
frame_set = set(values)
full_set = list(complete_set.difference(frame_set))
return summarize_list(full_set)
def generate_frames(wedge: dict):
"""
Generate individual frames for the given wedge
:param wedge: wedge information
:return: A generator of frame parameter dicts
"""
return ({
'name': wedge['name'],
'uuid': wedge.get('uuid'),
'saved': False,
'first': i + wedge['first'],
'start': wedge['start'] + i * wedge['delta'],
'delta': wedge['delta'],
'exposure': wedge['exposure'],
'energy': wedge['energy'],
'distance': wedge['distance'],
'two_theta': wedge.get('two_theta', 0.0),
'attenuation': wedge.get('attenuation', 0.0),
'directory': wedge['directory'],
}
for i in range(wedge['num_frames'])
)
def calc_range(run):
"""
Calculate the total range for the given strategy. For normal runs simply return the defined range. For
screening runs, the defined range in the ScreeningRange dictionary.
:param run: Run parameters (dict)
:return: a floating point angle in degrees
"""
if run.get('strategy') in [StrategyType.SCREEN_1, StrategyType.SCREEN_2, StrategyType.SCREEN_3, StrategyType.SCREEN_4]:
return ScreeningRange.get(run['strategy'], run.get('range', 180.))
else:
return run['range']
def calc_num_frames(strategy, delta, angle_range, skip=''):
"""
Count the number of frames in a dataset
:param strategy: run strategy
:param delta: delta angle
:param angle_range: angle range
:param skip: frames to skip
"""
if strategy in [StrategyType.SCREEN_1, StrategyType.SCREEN_2, StrategyType.SCREEN_3, StrategyType.SCREEN_4]:
total_range = ScreeningRange.get(strategy, angle_range)
else:
total_range = angle_range
return max(1, int(total_range / delta)) - count_frameset(skip)
def count_frames(run):
strategy = run.get('strategy', 0)
angle_range = run.get('range', 1)
delta = run.get('delta', 1)
return calc_num_frames(strategy, delta, angle_range, run.get('skip', ''))
def dataset_from_files(directory, file_glob):
"""
Given a file pattern and directory, read the header and dataset information for the dataset on disk
:param directory: directory containing the dataset
:param file_glob: pattern for matching files
:return: dataset dictionary. Expected fields are
'start_time': start time for the dataset
'frames': A frame list string, eg '1-5,8-10' or '1'
"""
file_pattern = re.compile(file_glob.replace('*', r'(\d{2,6})'))
data_files = sorted(glob.glob(os.path.join(directory, file_glob)))
start_time = None
if data_files:
start_time = datetime.fromtimestamp(
os.path.getmtime(os.path.join(directory, data_files[0])), tz=pytz.utc
)
full_set = [int(m.group(1)) for f in data_files for m in [file_pattern.search(f)] if m]
return {
'start_time': start_time,
'frames': summarize_list(full_set),
'num_frames': len(full_set),
}
def dataset_from_reference(reference_file):
"""
Given a reference file and directory, read the header and dataset information for the dataset on disk
:param reference_file: representative file from the dataset
:return: dataset dictionary. Expected fields are
'start_time': start time for the dataset
'frames': A frame list string, eg '1-5,8-10' or '1'
"""
header = read_header(reference_file)
sequence = header['dataset'].get('sequence', [])
return {
'start_time': header['dataset'].get('start_time', datetime.now(tz=pytz.utc)),
'frames': summarize_list(sequence),
'num_frames': len(sequence)
}
def frameset_to_list(frame_set):
frame_numbers = []
ranges = filter(None, frame_set.split(','))
wlist = [list(map(int, filter(None, w.split('-')))) for w in ranges]
for v in wlist:
if len(v) == 2:
frame_numbers.extend(range(v[0], v[1] + 1))
elif len(v) == 1:
frame_numbers.extend(v)
return frame_numbers
def count_pair(pair):
if pair == '':
return 0
elif not '-' in pair:
return 1
else:
lo, hi = pair.split('-')
return int(hi) - int(lo) + 1
def count_frameset(frame_set):
return sum(
count_pair(pair)
for pair in frame_set.split(',')
)
def merge_framesets(*args):
frame_set = ','.join(filter(None, args))
sequence = frameset_to_list(frame_set)
return summarize_list(sequence)
def make_file_template(name):
return '{}_{}'.format(name, '{{:0{}d}}'.format(FRAME_NUMBER_DIGITS))
def template_to_glob(template):
return re.sub(r'{[^{}]*}', '*', template)
def grid_frames(params: dict):
"""
Generate frame parameters for individual grid data frames when performed in step mode.
:param params: run parameters
:return: list of dictionaries representing a frame each
"""
return (
{
'name': params['name'],
'uuid': params['uuid'],
'saved': False,
'first': i + 1,
'start': params['angle'],
'delta': params['delta'],
'exposure': params['exposure'],
'energy': params['energy'],
'distance': params['distance'],
'two_theta': params.get('two_theta', 0.0),
'attenuation': params.get('attenuation', 0.0),
'directory': params['directory'],
'p0': point,
}
for i, point in enumerate(params['grid'])
)
def wedge_points(start, end, steps):
"""
Split the given starting and ending point into the given number of steps
:param start: start point coordinates (tuple of values) or None
:param end: end point coordinates (tuple of values) or None
:param steps: number of steps
:return: array of point pairs corresponding to the start and end of each sub section
"""
if not start:
points = numpy.array([None] * (steps + 1))
elif not end:
points = numpy.array([start] + [None] * (steps))
else:
points = numpy.linspace(start, end, steps + 1)
return numpy.take(points, [[i, i + 1] for i in range(points.shape[0] - 1)], axis=0)
def make_wedges(run: dict):
"""
Given run parameters, generate all wedges required to implement the experiment except for inverse beam
which is handled much later after interleaving. This includes calculating the starting point for multi-point/vector
data collection.
:param run: dictionary of run parameters.
:return: list of dictionaries each representing a wedge.
"""
delta = run.get('delta', 1.0)
total = calc_range(run)
first = run.get('first', 1)
# reconcile vector_size with requested wedge size. vector_size should be 1 for 4D helical scans
if run.get('vector_size') and run['vector_size'] > 1 and run.get('p1') is not None:
vector_slice = total // run['vector_size']
else:
vector_slice = total
slice = min(vector_slice, run.get('wedge', 180), total)
# determine start point, end point and list of frames for each wedge
num_wedges = int(total / slice)
positions = wedge_points(run.get('p0'), run.get('p1'), num_wedges)
wedge_frames = int(slice / delta)
wedge_numbers = numpy.arange(wedge_frames)
frames_points = [
(positions[i][0], positions[i][1], (first + i * wedge_frames + wedge_numbers).tolist())
for i in range(num_wedges)
]
# remove skipped or existing frames.
excluded = frameset_to_list(merge_framesets(run.get('skip', ''), run.get('existing', '')))
wedge_info = [
(start_pos, end_pos, numpy.array(sorted(set(frames) - set(excluded))))
for start_pos, end_pos, frames in frames_points
]
# split discontinuous sections into independent wedges
wedges = [
(start_pos, end_pos, chunk)
for start_pos, end_pos, frames in wedge_info
for chunk in numpy.split(frames, numpy.where(numpy.diff(frames) > 1)[0] + 1)
if frames.shape[0]
]
return [
{
'uuid': run.get('uuid'),
'name': run['name'],
'directory': run['directory'],
'start': run['start'] + (frames[0] - run['first']) * run['delta'],
'first': frames[0],
'num_frames': len(frames),
'delta': run['delta'],
'exposure': run['exposure'],
'distance': run['distance'],
'energy': run.get('energy', 12.658),
'two_theta': run.get('two_theta', 0.0),
'attenuation': run.get('attenuation', 0.0),
'p0': start_pos if start_pos is None else tuple(start_pos),
'p1': end_pos if end_pos is None else tuple(end_pos),
'inverse': run.get('inverse', False),
'weight': run['exposure'] * len(frames)
}
for start_pos, end_pos, frames in wedges
]
class WedgeDispenser(object):
"""
Given a data run, generate sequences of wedges to be interleaved. Typically the sequences
will contain a single wedge but when inverse beam is used, pairs are generated each time
:param run: run parameters
:param distinct: whether to use distinct dataset names for each wedge. If True, wedge names
will be suffixed with upper case letters to distinguish them from other wedges. Default is False
"""
def __init__(self, run: dict, distinct: bool = False):
self.details = run
self.sample = run.get('sample', {})
self.dispensed = []
# generate main wedges
self.wedges = make_wedges(self.details)
self.num_wedges = len(self.wedges)
self.pos = 0 # position in wedge list
self.distinct = distinct and (self.num_wedges > 1 or self.details.get('inverse'))
# total weights for progress
self.weight = sum(wedge['weight'] for wedge in self.wedges)
self.weight *= 2 if self.details.get('inverse') else 1 # inverse beam takes twice as long
# progress housekeeping
self.complete = 0
self.pending = 0
self.progress = 0.0
self.factor = 1
def set_progress(self, fraction):
"""
Set the percentage of the current wedge that has been completed
:param fraction: fraction of current pending workload that is complete set to 1 if complete.
"""
self.progress = (self.complete + (fraction * self.pending) / self.factor) / self.weight
if fraction == 1.0:
self.complete += (fraction * self.pending)/self.factor
def has_items(self):
"""
Check if wedges remain
"""
return self.pos < self.num_wedges
def get_details(self):
# """
# Yield a dictionary of details for each uniquely named wedge.
# """
for wedge in self.dispensed:
details = copy.deepcopy(self.details)
details.update(wedge)
yield details
def fetch(self):
"""
Produce collections of one or more wedges
"""
if self.pos >= self.num_wedges:
return ()
wedge = self.wedges[self.pos]
self.pending = wedge['weight']
if self.distinct:
name_suffix = chr(ord('A') + self.pos)
wedge['name'] += f"-{name_suffix}"
wedge['first'] = 1 # distinct wedges all start from frame 1 because they will be treated as
# unique datasets rather than frames from the same set.
self.pos += 1
# prepare inverse beam
if wedge['inverse']:
inv_wedge = copy.deepcopy(wedge)
if not self.distinct:
inv_wedge['first'] += int(180. / wedge['delta']) # only update first frame for non-distinct
inv_wedge['start'] += 180.
self.factor = 2
# additional numeric suffix for inverse beam
if self.distinct:
wedge['name'] += "1"
inv_wedge['name'] += "2"
self.dispensed.extend([wedge, inv_wedge])
return wedge, inv_wedge,
else:
self.factor = 1
self.dispensed.append(wedge)
return wedge,
def interleave(*datasets):
"""
For the provided Wedge dispensers, yield one wedge at a time in the right order
:param datasets: WedgeDispenser objects
:return: generator of wedge parameters
"""
while any(dataset.has_items() for dataset in datasets):
for dataset in datasets:
if dataset.has_items():
for wedge in dataset.fetch():
yield wedge | [
"copy.deepcopy",
"os.path.join",
"mxdc.conf.settings.get_session",
"os.path.exists",
"mxdc.conf.settings.get_string",
"re.match",
"datetime.datetime.now",
"collections.defaultdict",
"datetime.date.today",
"numpy.diff",
"numpy.arange",
"numpy.array",
"numpy.linspace",
"mxio.read_header",
... | [((2789, 2808), 'copy.deepcopy', 'copy.deepcopy', (['info'], {}), '(info)\n', (2802, 2808), False, 'import copy\n'), ((3339, 3380), 'mxdc.conf.settings.get_string', 'settings.get_string', (['"""directory-template"""'], {}), "('directory-template')\n", (3358, 3380), False, 'from mxdc.conf import settings\n'), ((9403, 9430), 'mxio.read_header', 'read_header', (['reference_file'], {}), '(reference_file)\n', (9414, 9430), False, 'from mxio import read_header\n'), ((10642, 10675), 're.sub', 're.sub', (['"""{[^{}]*}"""', '"""*"""', 'template'], {}), "('{[^{}]*}', '*', template)\n", (10648, 10675), False, 'import re\n'), ((13280, 13306), 'numpy.arange', 'numpy.arange', (['wedge_frames'], {}), '(wedge_frames)\n', (13292, 13306), False, 'import numpy\n'), ((3594, 3617), 'mxdc.utils.misc.get_project_home', 'misc.get_project_home', ([], {}), '()\n', (3615, 3617), False, 'from mxdc.utils import misc\n'), ((3770, 3805), 'os.path.exists', 'os.path.exists', (["params['directory']"], {}), "(params['directory'])\n", (3784, 3805), False, 'import os\n'), ((4324, 4341), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4335, 4341), False, 'from collections import defaultdict\n'), ((4464, 4481), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4475, 4481), False, 'from collections import defaultdict\n'), ((4520, 4552), 're.match', 're.match', (['f"""^(.+)_(\\\\d+)$"""', 'name'], {}), "(f'^(.+)_(\\\\d+)$', name)\n", (4528, 4552), False, 'import re\n'), ((11942, 11975), 'numpy.array', 'numpy.array', (['([None] * (steps + 1))'], {}), '([None] * (steps + 1))\n', (11953, 11975), False, 'import numpy\n'), ((2849, 2871), 'mxdc.conf.settings.get_session', 'settings.get_session', ([], {}), '()\n', (2869, 2871), False, 'from mxdc.conf import settings\n'), ((8548, 8582), 'os.path.join', 'os.path.join', (['directory', 'file_glob'], {}), '(directory, file_glob)\n', (8560, 8582), False, 'import os\n'), ((9555, 9580), 'datetime.datetime.now', 'datetime.now', ([], {'tz': 'pytz.utc'}), '(tz=pytz.utc)\n', (9567, 9580), False, 'from datetime import datetime\n'), ((12011, 12048), 'numpy.array', 'numpy.array', (['([start] + [None] * steps)'], {}), '([start] + [None] * steps)\n', (12022, 12048), False, 'import numpy\n'), ((12078, 12115), 'numpy.linspace', 'numpy.linspace', (['start', 'end', '(steps + 1)'], {}), '(start, end, steps + 1)\n', (12092, 12115), False, 'import numpy\n'), ((16882, 16909), 'copy.deepcopy', 'copy.deepcopy', (['self.details'], {}), '(self.details)\n', (16895, 16909), False, 'import copy\n'), ((17630, 17650), 'copy.deepcopy', 'copy.deepcopy', (['wedge'], {}), '(wedge)\n', (17643, 17650), False, 'import copy\n'), ((3925, 3954), 'os.path.exists', 'os.path.exists', (['new_directory'], {}), '(new_directory)\n', (3939, 3954), False, 'import os\n'), ((8702, 8740), 'os.path.join', 'os.path.join', (['directory', 'data_files[0]'], {}), '(directory, data_files[0])\n', (8714, 8740), False, 'import os\n'), ((3196, 3208), 'datetime.date.today', 'date.today', ([], {}), '()\n', (3206, 3208), False, 'from datetime import date\n'), ((5446, 5471), 'numpy.diff', 'numpy.diff', (['sorted_values'], {}), '(sorted_values)\n', (5456, 5471), False, 'import numpy\n'), ((13981, 13999), 'numpy.diff', 'numpy.diff', (['frames'], {}), '(frames)\n', (13991, 13999), False, 'import numpy\n')] |
import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from utils.early_stopping import EarlyStopping
import numpy as np
import copy
from tqdm import tqdm
from model.hrlce import HierarchicalPredictor, NUM_EMO
from sklearn.metrics import classification_report
from data.evaluate import load_dev_labels, get_metrics
import pickle as pkl
import sys
from allennlp.modules.elmo import Elmo, batch_to_ids
from copy import deepcopy
import argparse
import random
from utils.focalloss import FocalLoss
from torchmoji.sentence_tokenizer import SentenceTokenizer
from torchmoji.global_variables import PRETRAINED_PATH, VOCAB_PATH
from utils.tweet_processor import processing_pipeline
import json
parser = argparse.ArgumentParser(description='Options')
parser.add_argument('-folds', default=9, type=int,
help="num of folds")
parser.add_argument('-bs', default=128, type=int,
help="batch size")
parser.add_argument('-postname', default='', type=str,
help="name that will be added at the end of generated file")
parser.add_argument('-gamma', default=0.2, type=float,
help="the decay of the ")
parser.add_argument('-lr', default=5e-4, type=float,
help="learning rate")
parser.add_argument('-lbd1', default=0, type=float,
help="lambda1 is for MTL")
parser.add_argument('-lbd2', default=0, type=float,
help="lambda2 is for optimizing only the emotional labels")
parser.add_argument('-patience', default=1, type=int,
help="patience of early stopping")
parser.add_argument('-flat', default=1, type=float,
help="flatten para")
parser.add_argument('-focal', default=2, type=int,
help="gamma value for focal loss, default 2 ")
parser.add_argument('-w', default=2, type=int,
help="patience ")
parser.add_argument('-loss', default='ce', type=str,
help="ce or focal ")
parser.add_argument('-dim', default=1500, type=int,
help="post name")
parser.add_argument('-glovepath', type=str,
help="please specify the path to a GloVe 300d emb file")
opt = parser.parse_args()
NUM_OF_FOLD = opt.folds
learning_rate = opt.lr
MAX_EPOCH = 200
SENT_PAD_LEN = 30
EMOJ_SENT_PAD_LEN = 30
CONV_PAD_LEN = 3
FILL_VOCAB = True
BATCH_SIZE = opt.bs
SENT_EMB_DIM = 300
SENT_HIDDEN_SIZE = opt.dim
CLIP = 0.888
EARLY_STOP_PATIENCE = opt.patience
LAMBDA1 = opt.lbd1
LAMBDA2 = opt.lbd2
FLAT = opt.flat
EMOS = ['happy', 'angry', 'sad', 'others']
EMOS_DIC = {'happy': 0,
'angry': 1,
'sad': 2,
'others': 3}
# fix random seeds to ensure replicability
RANDOM_SEED = 0
torch.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed(RANDOM_SEED)
torch.cuda.manual_seed_all(RANDOM_SEED)
np.random.seed(RANDOM_SEED)
random.seed(RANDOM_SEED)
GLOVE_EMB_PATH = opt.glovepath
options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json"
weight_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_weights.hdf5"
elmo = Elmo(options_file, weight_file, 2, dropout=0).cuda()
elmo.eval()
print('Tokenizing using dictionary from {}'.format(VOCAB_PATH))
with open(VOCAB_PATH, 'r') as f:
vocabulary = json.load(f)
emoji_st = SentenceTokenizer(vocabulary, EMOJ_SENT_PAD_LEN)
def load_data_context(data_path='data/train.txt', is_train=True):
# data_path = 'data/train.txt'
data_list = []
target_list = []
f_data = open(data_path, 'r')
data_lines = f_data.readlines()
f_data.close()
for i, text in enumerate(data_lines):
# skip the first line
if i == 0:
continue
tokens = text.split('\t')
convers = tokens[1:CONV_PAD_LEN+1]
# normal preprocessing
raw_a = convers[0]
raw_b = convers[1]
raw_c = convers[2]
a = processing_pipeline(raw_a)
b = processing_pipeline(raw_b)
c = processing_pipeline(raw_c)
data_list.append((a, b, c, raw_a, raw_b, raw_c))
if is_train:
emo = tokens[CONV_PAD_LEN + 1].strip()
target_list.append(EMOS_DIC[emo])
if is_train:
return data_list, target_list
else:
return data_list
def build_vocab(data_list_list, vocab_size, fill_vocab=False):
all_str_list = []
for data_list in data_list_list:
for data in data_list:
all_str_list.append(data[0])
all_str_list.append(data[1])
all_str_list.append(data[2])
word_count = {}
word2id = {}
id2word = {}
for tokens in all_str_list:
for word in tokens.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
word_list = [x for x, _ in sorted(word_count.items(), key=lambda v: v[1], reverse=True)]
print('found', len(word_count), 'words')
if len(word_count) < vocab_size:
raise Exception('Vocab less than requested!!!')
# add <pad> first
word2id['<pad>'] = 0
id2word[0] = '<pad>'
word2id['<unk>'] = 1
id2word[1] = '<unk>'
word2id['<empty>'] = 2
id2word[2] = '<empty>'
n = len(word2id)
if not fill_vocab:
word_list = word_list[:vocab_size - n]
for word in word_list:
word2id[word] = n
id2word[n] = word
n += 1
if fill_vocab:
print('filling vocab to', len(id2word))
return word2id, id2word, len(id2word)
return word2id, id2word, len(word2id)
class TrainDataSet(Dataset):
def __init__(self, data_list, target_list, conv_pad_len, sent_pad_len, word2id, max_size=None, use_unk=False):
self.sent_pad_len = sent_pad_len
self.conv_pad_len = conv_pad_len
self.word2id = word2id
self.pad_int = word2id['<pad>']
self.use_unk = use_unk
# set max size for the purpose of testing
if max_size is not None:
self.data = self.data[:max_size]
self.target = self.target[:max_size]
# internal data
self.a = []
self.b = []
self.c = []
self.a_len = []
self.b_len = []
self.c_len = []
self.emoji_a = []
self.emoji_b = []
self.emoji_c = []
self.e_c = []
self.e_c_binary = []
self.e_c_emo = []
self.num_empty_lines = 0
self.weights = []
# prepare dataset
self.read_data(data_list, target_list)
def sent_to_ids(self, text):
tokens = text.split()
if self.use_unk:
tmp = [self.word2id[x] if x in self.word2id else self.word2id['<unk>'] for x in tokens]
else:
tmp = [self.word2id[x] for x in tokens if x in self.word2id]
if len(tmp) == 0:
tmp = [self.word2id['<empty>']]
self.num_empty_lines += 1
# PADDING
if len(tmp) > self.sent_pad_len:
tmp = tmp[: self.sent_pad_len]
text_len = len(tmp)
tmp = tmp + [self.pad_int] * (self.sent_pad_len - len(tmp))
return tmp, text_len
def read_data(self, data_list, target_list):
assert len(data_list) == len(target_list)
for X, y in zip(data_list, target_list):
clean_a, clean_b, clean_c, raw_a, raw_b, raw_c = X
a, a_len = self.sent_to_ids(clean_a)
b, b_len = self.sent_to_ids(clean_b)
c, c_len = self.sent_to_ids(clean_c)
self.a.append(a)
self.b.append(b)
self.c.append(c)
self.a_len.append(a_len)
self.b_len.append(b_len)
self.c_len.append(c_len)
self.emoji_a.append(emoji_st.tokenize_sentences([clean_a])[0].reshape((-1)).astype(np.int64))
self.emoji_b.append(emoji_st.tokenize_sentences([clean_b])[0].reshape((-1)).astype(np.int64))
self.emoji_c.append(emoji_st.tokenize_sentences([clean_c])[0].reshape((-1)).astype(np.int64))
self.e_c.append(int(y))
self.e_c_binary.append(1 if int(y) == len(EMOS) - 1 else 0)
e_c_emo = [0] * (len(EMOS) - 1)
if int(y) < len(EMOS) - 1: # i.e. only first three emotions
e_c_emo[int(y)] = 1
self.e_c_emo.append(e_c_emo)
print('num of empty lines,', self.num_empty_lines)
def __len__(self):
return len(self.a)
def __getitem__(self, idx):
return torch.LongTensor(self.a[idx]), torch.LongTensor([self.a_len[idx]]), \
torch.LongTensor(self.b[idx]), torch.LongTensor([self.b_len[idx]]), \
torch.LongTensor(self.c[idx]), torch.LongTensor([self.c_len[idx]]), \
torch.LongTensor(self.emoji_a[idx]), torch.LongTensor(self.emoji_b[idx]), torch.LongTensor(self.emoji_c[idx]), \
torch.LongTensor([self.e_c[idx]]), torch.LongTensor([self.e_c_binary[idx]]), \
torch.FloatTensor(self.e_c_emo[idx])
class TestDataSet(Dataset):
def __init__(self, data_list, conv_pad_len, sent_pad_len, word2id, id2word, use_unk=False):
self.sent_pad_len = sent_pad_len
self.conv_pad_len = conv_pad_len
self.word2id = word2id
self.pad_int = word2id['<pad>']
self.use_unk = use_unk
# internal data
self.a = []
self.b = []
self.c = []
self.a_len = []
self.b_len = []
self.c_len = []
self.emoji_a = []
self.emoji_b = []
self.emoji_c = []
self.num_empty_lines = 0
# prepare dataset
self.ex_word2id = copy.deepcopy(word2id)
self.ex_id2word = copy.deepcopy(id2word)
self.unk_words_idx = set()
self.read_data(data_list)
def sent_to_ids(self, text):
tokens = text.split()
if self.use_unk:
tmp = [self.word2id[x] if x in self.word2id else self.word2id['<unk>'] for x in tokens]
else:
tmp = [self.word2id[x] for x in tokens if x in self.word2id]
if len(tmp) == 0:
tmp = [self.word2id['<empty>']]
self.num_empty_lines += 1
# PADDING
if len(tmp) > self.sent_pad_len:
tmp = tmp[: self.sent_pad_len]
text_len = len(tmp)
tmp = tmp + [self.pad_int] * (self.sent_pad_len - len(tmp))
return tmp, text_len
def read_data(self, data_list):
for X in data_list:
clean_a, clean_b, clean_c, raw_a, raw_b, raw_c = X
a, a_len = self.sent_to_ids(clean_a)
b, b_len = self.sent_to_ids(clean_b)
c, c_len = self.sent_to_ids(clean_c)
self.a.append(a)
self.b.append(b)
self.c.append(c)
self.a_len.append(a_len)
self.b_len.append(b_len)
self.c_len.append(c_len)
self.emoji_a.append(emoji_st.tokenize_sentences([clean_a])[0].reshape((-1)).astype(np.int64))
self.emoji_b.append(emoji_st.tokenize_sentences([clean_b])[0].reshape((-1)).astype(np.int64))
self.emoji_c.append(emoji_st.tokenize_sentences([clean_c])[0].reshape((-1)).astype(np.int64))
print('num of empty lines,', self.num_empty_lines)
def __len__(self):
return len(self.a)
def __getitem__(self, idx):
return torch.LongTensor(self.a[idx]), torch.LongTensor([self.a_len[idx]]), \
torch.LongTensor(self.b[idx]), torch.LongTensor([self.b_len[idx]]), \
torch.LongTensor(self.c[idx]), torch.LongTensor([self.c_len[idx]]), \
torch.LongTensor(self.emoji_a[idx]), torch.LongTensor(self.emoji_b[idx]), torch.LongTensor(self.emoji_c[idx])
def to_categorical(vec):
to_ret = np.zeros((vec.shape[0], NUM_EMO))
for idx, val in enumerate(vec):
to_ret[idx, val] = 1
return to_ret
def build_embedding(id2word, fname, num_of_vocab):
"""
:param id2word, fname:
:return:
"""
import io
def load_vectors(fname):
print("Loading Glove Model")
f = open(fname, 'r', encoding='utf8')
model = {}
for line in tqdm(f.readlines(), total=2196017):
values = line.split(' ')
word = values[0]
try:
embedding = np.array(values[1:], dtype=np.float32)
model[word] = embedding
except ValueError:
print(len(values), values[0])
print("Done.", len(model), " words loaded!")
f.close()
return model
def get_emb(emb_dict, vocab_size, embedding_dim):
# emb_dict = load_vectors(fname)
all_embs = np.stack(emb_dict.values())
emb_mean, emb_std = all_embs.mean(), all_embs.std()
emb = np.random.normal(emb_mean, emb_std, (vocab_size, embedding_dim))
# emb = np.zeros((vocab_size, embedding_dim))
num_found = 0
print('loading glove')
for idx in tqdm(range(vocab_size)):
word = id2word[idx]
if word == '<pad>' or word == '<unk>':
emb[idx] = np.zeros([embedding_dim])
elif word in emb_dict:
emb[idx] = emb_dict[word]
num_found += 1
return emb, num_found
pkl_path = fname + '.pkl'
if not os.path.isfile(pkl_path):
print('creating pkl file for the emb text file')
emb_dict = load_vectors(fname)
with open(pkl_path, 'wb') as f:
pkl.dump(emb_dict, f)
else:
print('loading pkl file')
with open(pkl_path, 'rb') as f:
emb_dict = pkl.load(f)
print('loading finished')
emb, num_found = get_emb(emb_dict, num_of_vocab, SENT_EMB_DIM)
print(num_found, 'of', num_of_vocab, 'found', 'coverage', num_found/num_of_vocab)
return emb
def main():
num_of_vocab = 10000
# load data
train_file = 'data/train.txt'
data_list, target_list = load_data_context(data_path=train_file)
# dev set
dev_file = 'data/dev.txt'
dev_data_list, dev_target_list = load_data_context(data_path=dev_file)
# test set
test_file = 'data/test.txt'
test_data_list, test_target_list = load_data_context(data_path=test_file)
# load final test data
final_test_file = 'data/testwithoutlabels.txt'
final_test_data_list = load_data_context(data_path=final_test_file, is_train=False)
# build vocab
word2id, id2word, num_of_vocab = build_vocab([data_list, dev_data_list, test_data_list], num_of_vocab,
FILL_VOCAB)
emb = build_embedding(id2word, GLOVE_EMB_PATH, num_of_vocab)
gold_dev_data_set = TestDataSet(dev_data_list, CONV_PAD_LEN, SENT_PAD_LEN, word2id, id2word, use_unk=False)
gold_dev_data_loader = DataLoader(gold_dev_data_set, batch_size=BATCH_SIZE, shuffle=False)
print("Size of test data", len(gold_dev_data_set))
test_data_set = TestDataSet(test_data_list, CONV_PAD_LEN, SENT_PAD_LEN, word2id, id2word, use_unk=False)
test_data_loader = DataLoader(test_data_set, batch_size=BATCH_SIZE, shuffle=False)
print("Size of test data", len(test_data_set))
# ex_id2word, unk_words_idx = test_data_set.get_ex_id2word_unk_words()
final_test_data_set = TestDataSet(final_test_data_list, CONV_PAD_LEN, SENT_PAD_LEN, word2id, id2word, use_unk=False)
final_test_data_loader = DataLoader(final_test_data_set, batch_size=BATCH_SIZE, shuffle=False)
print("Size of final test data", len(final_test_data_set))
# final_ex_id2word, _ = final_test_data_set.get_ex_id2word_unk_words()
def glove_tokenizer(ids, __id2word):
return [__id2word[int(x)] for x in ids if x != 0]
def elmo_encode(data, __id2word=id2word):
data_text = [glove_tokenizer(x, __id2word) for x in data]
with torch.no_grad():
character_ids = batch_to_ids(data_text).cuda()
elmo_emb = elmo(character_ids)['elmo_representations']
elmo_emb = (elmo_emb[0] + elmo_emb[1]) / 2 # avg of two layers
return elmo_emb.cuda()
X = data_list
y = target_list
y = np.array(y)
combined = list(zip(X, y))
random.shuffle(combined)
X[:], y[:] = zip(*combined)
# train dev split
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=NUM_OF_FOLD, random_state=0)
all_fold_results = []
real_test_results = []
def one_fold(num_fold, train_index, dev_index):
print("Training on fold:", num_fold)
X_train, X_dev = [X[i] for i in train_index], [X[i] for i in dev_index]
y_train, y_dev = y[train_index], y[dev_index]
# construct data loader
train_data_set = TrainDataSet(X_train, y_train, CONV_PAD_LEN, SENT_PAD_LEN, word2id, use_unk=True)
dev_data_set = TrainDataSet(X_dev, y_dev, CONV_PAD_LEN, SENT_PAD_LEN, word2id, use_unk=True)
dev_data_loader = DataLoader(dev_data_set, batch_size=BATCH_SIZE, shuffle=False)
# device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
pred_list_test_best = None
final_pred_best = None
# This is to prevent model diverge, once happen, retrain
while True:
is_diverged = False
model = HierarchicalPredictor(SENT_EMB_DIM, SENT_HIDDEN_SIZE, num_of_vocab, USE_ELMO=True, ADD_LINEAR=False)
model.load_embedding(emb)
model.deepmoji_model.load_specific_weights(PRETRAINED_PATH, exclude_names=['output_layer'])
model.cuda()
# model = nn.DataParallel(model)
# model.to(device)
optimizer = optim.Adam(model.parameters(), lr=learning_rate, amsgrad=True) #
# optimizer = optim.SGD(model.parameters(), lr=learning_rate)
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=opt.gamma)
if opt.w == 1:
weight_list = [0.3, 0.3, 0.3, 1.7]
weight_list_binary = [2 - weight_list[-1], weight_list[-1]]
elif opt.w == 2:
weight_list = [0.3198680179, 0.246494733, 0.2484349259, 1.74527696]
weight_list_binary = [2 - weight_list[-1], weight_list[-1]]
else:
raise ValueError
weight_list = [x**FLAT for x in weight_list]
weight_label = torch.Tensor(weight_list).cuda()
weight_list_binary = [x**FLAT for x in weight_list_binary]
weight_binary = torch.Tensor(weight_list_binary).cuda()
print('classification reweight: ', weight_list)
print('binary loss reweight = weight_list_binary', weight_list_binary)
# loss_criterion_binary = nn.CrossEntropyLoss(weight=weight_list_binary) #
if opt.loss == 'focal':
loss_criterion = FocalLoss(gamma=opt.focal, reduce=False)
loss_criterion_binary = FocalLoss(gamma=opt.focal, reduce=False) #
elif opt.loss == 'ce':
loss_criterion = nn.CrossEntropyLoss(reduce=False)
loss_criterion_binary = nn.CrossEntropyLoss(reduce=False) #
loss_criterion_emo_only = nn.MSELoss()
es = EarlyStopping(patience=EARLY_STOP_PATIENCE)
# best_model = None
final_pred_list_test = None
pred_list_test = None
for num_epoch in range(MAX_EPOCH):
# to ensure shuffle at ever epoch
train_data_loader = DataLoader(train_data_set, batch_size=BATCH_SIZE, shuffle=True)
print('Begin training epoch:', num_epoch, end='...\t')
sys.stdout.flush()
# stepping scheduler
scheduler.step(num_epoch)
print('Current learning rate', scheduler.get_lr())
train_loss = 0
model.train()
for i, (a, a_len, b, b_len, c, c_len, emoji_a, emoji_b, emoji_c, e_c, e_c_binary, e_c_emo) \
in tqdm(enumerate(train_data_loader), total=len(train_data_set)/BATCH_SIZE):
optimizer.zero_grad()
elmo_a = elmo_encode(a)
elmo_b = elmo_encode(b)
elmo_c = elmo_encode(c)
pred, pred2, pred3 = model(a.cuda(), a_len, b.cuda(), b_len, c.cuda(), c_len,
emoji_a.cuda(), emoji_b.cuda(), emoji_c.cuda(),
elmo_a, elmo_b, elmo_c)
loss_label = loss_criterion(pred, e_c.view(-1).cuda()).cuda()
loss_label = torch.matmul(torch.gather(weight_label, 0, e_c.view(-1).cuda()), loss_label) / \
e_c.view(-1).shape[0]
loss_binary = loss_criterion_binary(pred2, e_c_binary.view(-1).cuda()).cuda()
loss_binary = torch.matmul(torch.gather(weight_binary, 0, e_c_binary.view(-1).cuda()),
loss_binary) / e_c.view(-1).shape[0]
loss_emo = loss_criterion_emo_only(pred3, e_c_emo.cuda())
loss = (loss_label + LAMBDA1 * loss_binary + LAMBDA2 * loss_emo) / float(1 + LAMBDA1 + LAMBDA2)
# loss = torch.matmul(torch.gather(weight, 0, trg.view(-1).cuda()), loss) / trg.view(-1).shape[0]
# training trilogy
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), CLIP)
optimizer.step()
train_loss += loss.data.cpu().numpy() * a.shape[0]
del pred, loss, elmo_a, elmo_b, elmo_c, e_c_emo, loss_binary, loss_label, loss_emo
# Evaluate
model.eval()
dev_loss = 0
# pred_list = []
# gold_list = []
for i, (a, a_len, b, b_len, c, c_len, emoji_a, emoji_b, emoji_c, e_c, e_c_binary, e_c_emo)\
in enumerate(dev_data_loader):
with torch.no_grad():
elmo_a = elmo_encode(a)
elmo_b = elmo_encode(b)
elmo_c = elmo_encode(c)
pred, pred2, pred3 = model(a.cuda(), a_len, b.cuda(), b_len, c.cuda(), c_len,
emoji_a.cuda(), emoji_b.cuda(), emoji_c.cuda(),
elmo_a, elmo_b, elmo_c)
loss_label = loss_criterion(pred, e_c.view(-1).cuda()).cuda()
loss_label = torch.matmul(torch.gather(weight_label, 0, e_c.view(-1).cuda()), loss_label) / e_c.view(-1).shape[0]
loss_binary = loss_criterion_binary(pred2, e_c_binary.view(-1).cuda()).cuda()
loss_binary = torch.matmul(torch.gather(weight_binary, 0, e_c_binary.view(-1).cuda()), loss_binary) / e_c.view(-1).shape[0]
loss_emo = loss_criterion_emo_only(pred3, e_c_emo.cuda())
loss = (loss_label + LAMBDA1 * loss_binary + LAMBDA2 * loss_emo) / float(1 + LAMBDA1 + LAMBDA2)
dev_loss += loss.data.cpu().numpy() * a.shape[0]
# pred_list.append(pred.data.cpu().numpy())
# gold_list.append(e_c.numpy())
del pred, loss, elmo_a, elmo_b, elmo_c, e_c_emo, loss_binary, loss_label, loss_emo
print('Training loss:', train_loss / len(train_data_set), end='\t')
print('Dev loss:', dev_loss / len(dev_data_set))
# print(classification_report(gold_list, pred_list, target_names=EMOS))
# get_metrics(pred_list, gold_list)
if dev_loss/len(dev_data_set) > 1.3 and num_epoch > 4:
print("Model diverged, retry")
is_diverged = True
break
if es.step(dev_loss): # overfitting
print('overfitting, loading best model ...')
break
else:
if es.is_best():
print('saving best model ...')
if final_pred_best is not None:
del final_pred_best
final_pred_best = deepcopy(final_pred_list_test)
if pred_list_test_best is not None:
del pred_list_test_best
pred_list_test_best = deepcopy(pred_list_test)
else:
print('not best model, ignoring ...')
if final_pred_best is None:
final_pred_best = deepcopy(final_pred_list_test)
if pred_list_test_best is None:
pred_list_test_best = deepcopy(pred_list_test)
# Gold Dev testing...
print('Gold Dev testing....')
pred_list_test = []
model.eval()
for i, (a, a_len, b, b_len, c, c_len, emoji_a, emoji_b, emoji_c) in enumerate(gold_dev_data_loader):
with torch.no_grad():
elmo_a = elmo_encode(a) # , __id2word=ex_id2word
elmo_b = elmo_encode(b)
elmo_c = elmo_encode(c)
pred, _, _ = model(a.cuda(), a_len, b.cuda(), b_len, c.cuda(), c_len,
emoji_a.cuda(), emoji_b.cuda(), emoji_c.cuda(),
elmo_a, elmo_b, elmo_c)
pred_list_test.append(pred.data.cpu().numpy())
del elmo_a, elmo_b, elmo_c, a, b, c, pred
pred_list_test = np.argmax(np.concatenate(pred_list_test, axis=0), axis=1)
# get_metrics(load_dev_labels('data/dev.txt'), pred_list_test)
# Testing
print('Gold test testing...')
final_pred_list_test = []
model.eval()
for i, (a, a_len, b, b_len, c, c_len, emoji_a, emoji_b, emoji_c) in enumerate(test_data_loader):
with torch.no_grad():
elmo_a = elmo_encode(a) # , __id2word=ex_id2word
elmo_b = elmo_encode(b)
elmo_c = elmo_encode(c)
pred, _, _ = model(a.cuda(), a_len, b.cuda(), b_len, c.cuda(), c_len,
emoji_a.cuda(), emoji_b.cuda(), emoji_c.cuda(),
elmo_a, elmo_b, elmo_c)
final_pred_list_test.append(pred.data.cpu().numpy())
del elmo_a, elmo_b, elmo_c, a, b, c, pred
final_pred_list_test = np.argmax(np.concatenate(final_pred_list_test, axis=0), axis=1)
# get_metrics(load_dev_labels('data/test.txt'), final_pred_list_test)
if is_diverged:
print("Reinitialize model ...")
del model
continue
all_fold_results.append(pred_list_test_best)
real_test_results.append(final_pred_best)
del model
break
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# Training the folds
for idx, (_train_index, _dev_index) in enumerate(skf.split(X, y)):
print('Train size:', len(_train_index), 'Dev size:', len(_dev_index))
one_fold(idx, _train_index, _dev_index)
# Function of majority voting
def find_majority(k):
myMap = {}
maximum = ('', 0) # (occurring element, occurrences)
for n in k:
if n in myMap:
myMap[n] += 1
else:
myMap[n] = 1
# Keep track of maximum on the go
if myMap[n] > maximum[1]: maximum = (n, myMap[n])
return maximum
all_fold_results = np.asarray(all_fold_results)
mj_dev = []
for col_num in range(all_fold_results.shape[1]):
a_mj = find_majority(all_fold_results[:, col_num])
mj_dev.append(a_mj[0])
print('FINAL gold DEV RESULTS')
get_metrics(load_dev_labels('data/dev.txt'), np.asarray(mj_dev))
real_test_results = np.asarray(real_test_results)
mj = []
for col_num in range(real_test_results.shape[1]):
a_mj = find_majority(real_test_results[:, col_num])
mj.append(a_mj[0])
print('FINAL TESTING RESULTS')
get_metrics(load_dev_labels('data/test.txt'), np.asarray(mj))
# MAKE SUBMISSION
# WRITE TO FILE
test_file = 'data/testwithoutlabels.txt'
f_in = open(test_file, 'r')
f_out = open('test_elmo_mtl' + opt.postname + '.txt', 'w')
data_lines = f_in.readlines()
for idx, text in enumerate(data_lines):
if idx == 0:
f_out.write(text.strip() + '\tlabel\n')
else:
f_out.write(text.strip() + '\t' + EMOS[mj[idx-1]] + '\n')
f_in.close()
f_out.close()
print('Final testing')
main()
| [
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"random.shuffle",
"model.hrlce.HierarchicalPredictor",
"torch.cuda.device_count",
"os.path.isfile",
"pickle.load",
"sys.stdout.flush",
"numpy.random.normal",
"torch.no_grad",
"torch.nn.MSELoss",
"torch.utils.data.DataLoader",
"... | [((806, 852), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Options"""'}), "(description='Options')\n", (829, 852), False, 'import argparse\n'), ((2841, 2871), 'torch.manual_seed', 'torch.manual_seed', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (2858, 2871), False, 'import torch\n'), ((2872, 2907), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (2894, 2907), False, 'import torch\n'), ((2908, 2947), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (2934, 2947), False, 'import torch\n'), ((2948, 2975), 'numpy.random.seed', 'np.random.seed', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (2962, 2975), True, 'import numpy as np\n'), ((2976, 3000), 'random.seed', 'random.seed', (['RANDOM_SEED'], {}), '(RANDOM_SEED)\n', (2987, 3000), False, 'import random\n'), ((3543, 3591), 'torchmoji.sentence_tokenizer.SentenceTokenizer', 'SentenceTokenizer', (['vocabulary', 'EMOJ_SENT_PAD_LEN'], {}), '(vocabulary, EMOJ_SENT_PAD_LEN)\n', (3560, 3591), False, 'from torchmoji.sentence_tokenizer import SentenceTokenizer\n'), ((3519, 3531), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3528, 3531), False, 'import json\n'), ((11973, 12006), 'numpy.zeros', 'np.zeros', (['(vec.shape[0], NUM_EMO)'], {}), '((vec.shape[0], NUM_EMO))\n', (11981, 12006), True, 'import numpy as np\n'), ((14997, 15064), 'torch.utils.data.DataLoader', 'DataLoader', (['gold_dev_data_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(False)'}), '(gold_dev_data_set, batch_size=BATCH_SIZE, shuffle=False)\n', (15007, 15064), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((15253, 15316), 'torch.utils.data.DataLoader', 'DataLoader', (['test_data_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(False)'}), '(test_data_set, batch_size=BATCH_SIZE, shuffle=False)\n', (15263, 15316), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((15594, 15663), 'torch.utils.data.DataLoader', 'DataLoader', (['final_test_data_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(False)'}), '(final_test_data_set, batch_size=BATCH_SIZE, shuffle=False)\n', (15604, 15663), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((16325, 16336), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (16333, 16336), True, 'import numpy as np\n'), ((16373, 16397), 'random.shuffle', 'random.shuffle', (['combined'], {}), '(combined)\n', (16387, 16397), False, 'import random\n'), ((16519, 16572), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': 'NUM_OF_FOLD', 'random_state': '(0)'}), '(n_splits=NUM_OF_FOLD, random_state=0)\n', (16534, 16572), False, 'from sklearn.model_selection import StratifiedKFold\n'), ((28258, 28286), 'numpy.asarray', 'np.asarray', (['all_fold_results'], {}), '(all_fold_results)\n', (28268, 28286), True, 'import numpy as np\n'), ((28578, 28607), 'numpy.asarray', 'np.asarray', (['real_test_results'], {}), '(real_test_results)\n', (28588, 28607), True, 'import numpy as np\n'), ((3339, 3384), 'allennlp.modules.elmo.Elmo', 'Elmo', (['options_file', 'weight_file', '(2)'], {'dropout': '(0)'}), '(options_file, weight_file, 2, dropout=0)\n', (3343, 3384), False, 'from allennlp.modules.elmo import Elmo, batch_to_ids\n'), ((4143, 4169), 'utils.tweet_processor.processing_pipeline', 'processing_pipeline', (['raw_a'], {}), '(raw_a)\n', (4162, 4169), False, 'from utils.tweet_processor import processing_pipeline\n'), ((4182, 4208), 'utils.tweet_processor.processing_pipeline', 'processing_pipeline', (['raw_b'], {}), '(raw_b)\n', (4201, 4208), False, 'from utils.tweet_processor import processing_pipeline\n'), ((4221, 4247), 'utils.tweet_processor.processing_pipeline', 'processing_pipeline', (['raw_c'], {}), '(raw_c)\n', (4240, 4247), False, 'from utils.tweet_processor import processing_pipeline\n'), ((9859, 9881), 'copy.deepcopy', 'copy.deepcopy', (['word2id'], {}), '(word2id)\n', (9872, 9881), False, 'import copy\n'), ((9908, 9930), 'copy.deepcopy', 'copy.deepcopy', (['id2word'], {}), '(id2word)\n', (9921, 9930), False, 'import copy\n'), ((12979, 13043), 'numpy.random.normal', 'np.random.normal', (['emb_mean', 'emb_std', '(vocab_size, embedding_dim)'], {}), '(emb_mean, emb_std, (vocab_size, embedding_dim))\n', (12995, 13043), True, 'import numpy as np\n'), ((13513, 13537), 'os.path.isfile', 'os.path.isfile', (['pkl_path'], {}), '(pkl_path)\n', (13527, 13537), False, 'import os\n'), ((17126, 17188), 'torch.utils.data.DataLoader', 'DataLoader', (['dev_data_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(False)'}), '(dev_data_set, batch_size=BATCH_SIZE, shuffle=False)\n', (17136, 17188), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((27518, 27543), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (27541, 27543), False, 'import torch\n'), ((28500, 28531), 'data.evaluate.load_dev_labels', 'load_dev_labels', (['"""data/dev.txt"""'], {}), "('data/dev.txt')\n", (28515, 28531), False, 'from data.evaluate import load_dev_labels, get_metrics\n'), ((28533, 28551), 'numpy.asarray', 'np.asarray', (['mj_dev'], {}), '(mj_dev)\n', (28543, 28551), True, 'import numpy as np\n'), ((28813, 28845), 'data.evaluate.load_dev_labels', 'load_dev_labels', (['"""data/test.txt"""'], {}), "('data/test.txt')\n", (28828, 28845), False, 'from data.evaluate import load_dev_labels, get_metrics\n'), ((28847, 28861), 'numpy.asarray', 'np.asarray', (['mj'], {}), '(mj)\n', (28857, 28861), True, 'import numpy as np\n'), ((8712, 8741), 'torch.LongTensor', 'torch.LongTensor', (['self.a[idx]'], {}), '(self.a[idx])\n', (8728, 8741), False, 'import torch\n'), ((8743, 8778), 'torch.LongTensor', 'torch.LongTensor', (['[self.a_len[idx]]'], {}), '([self.a_len[idx]])\n', (8759, 8778), False, 'import torch\n'), ((8797, 8826), 'torch.LongTensor', 'torch.LongTensor', (['self.b[idx]'], {}), '(self.b[idx])\n', (8813, 8826), False, 'import torch\n'), ((8828, 8863), 'torch.LongTensor', 'torch.LongTensor', (['[self.b_len[idx]]'], {}), '([self.b_len[idx]])\n', (8844, 8863), False, 'import torch\n'), ((8882, 8911), 'torch.LongTensor', 'torch.LongTensor', (['self.c[idx]'], {}), '(self.c[idx])\n', (8898, 8911), False, 'import torch\n'), ((8913, 8948), 'torch.LongTensor', 'torch.LongTensor', (['[self.c_len[idx]]'], {}), '([self.c_len[idx]])\n', (8929, 8948), False, 'import torch\n'), ((8967, 9002), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_a[idx]'], {}), '(self.emoji_a[idx])\n', (8983, 9002), False, 'import torch\n'), ((9004, 9039), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_b[idx]'], {}), '(self.emoji_b[idx])\n', (9020, 9039), False, 'import torch\n'), ((9041, 9076), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_c[idx]'], {}), '(self.emoji_c[idx])\n', (9057, 9076), False, 'import torch\n'), ((9095, 9128), 'torch.LongTensor', 'torch.LongTensor', (['[self.e_c[idx]]'], {}), '([self.e_c[idx]])\n', (9111, 9128), False, 'import torch\n'), ((9130, 9170), 'torch.LongTensor', 'torch.LongTensor', (['[self.e_c_binary[idx]]'], {}), '([self.e_c_binary[idx]])\n', (9146, 9170), False, 'import torch\n'), ((9189, 9225), 'torch.FloatTensor', 'torch.FloatTensor', (['self.e_c_emo[idx]'], {}), '(self.e_c_emo[idx])\n', (9206, 9225), False, 'import torch\n'), ((11568, 11597), 'torch.LongTensor', 'torch.LongTensor', (['self.a[idx]'], {}), '(self.a[idx])\n', (11584, 11597), False, 'import torch\n'), ((11599, 11634), 'torch.LongTensor', 'torch.LongTensor', (['[self.a_len[idx]]'], {}), '([self.a_len[idx]])\n', (11615, 11634), False, 'import torch\n'), ((11653, 11682), 'torch.LongTensor', 'torch.LongTensor', (['self.b[idx]'], {}), '(self.b[idx])\n', (11669, 11682), False, 'import torch\n'), ((11684, 11719), 'torch.LongTensor', 'torch.LongTensor', (['[self.b_len[idx]]'], {}), '([self.b_len[idx]])\n', (11700, 11719), False, 'import torch\n'), ((11738, 11767), 'torch.LongTensor', 'torch.LongTensor', (['self.c[idx]'], {}), '(self.c[idx])\n', (11754, 11767), False, 'import torch\n'), ((11769, 11804), 'torch.LongTensor', 'torch.LongTensor', (['[self.c_len[idx]]'], {}), '([self.c_len[idx]])\n', (11785, 11804), False, 'import torch\n'), ((11823, 11858), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_a[idx]'], {}), '(self.emoji_a[idx])\n', (11839, 11858), False, 'import torch\n'), ((11860, 11895), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_b[idx]'], {}), '(self.emoji_b[idx])\n', (11876, 11895), False, 'import torch\n'), ((11897, 11932), 'torch.LongTensor', 'torch.LongTensor', (['self.emoji_c[idx]'], {}), '(self.emoji_c[idx])\n', (11913, 11932), False, 'import torch\n'), ((13687, 13708), 'pickle.dump', 'pkl.dump', (['emb_dict', 'f'], {}), '(emb_dict, f)\n', (13695, 13708), True, 'import pickle as pkl\n'), ((13816, 13827), 'pickle.load', 'pkl.load', (['f'], {}), '(f)\n', (13824, 13827), True, 'import pickle as pkl\n'), ((16028, 16043), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (16041, 16043), False, 'import torch\n'), ((17475, 17579), 'model.hrlce.HierarchicalPredictor', 'HierarchicalPredictor', (['SENT_EMB_DIM', 'SENT_HIDDEN_SIZE', 'num_of_vocab'], {'USE_ELMO': '(True)', 'ADD_LINEAR': '(False)'}), '(SENT_EMB_DIM, SENT_HIDDEN_SIZE, num_of_vocab,\n USE_ELMO=True, ADD_LINEAR=False)\n', (17496, 17579), False, 'from model.hrlce import HierarchicalPredictor, NUM_EMO\n'), ((18006, 18072), 'torch.optim.lr_scheduler.ExponentialLR', 'torch.optim.lr_scheduler.ExponentialLR', (['optimizer'], {'gamma': 'opt.gamma'}), '(optimizer, gamma=opt.gamma)\n', (18044, 18072), False, 'import torch\n'), ((19369, 19381), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (19379, 19381), True, 'import torch.nn as nn\n'), ((19400, 19443), 'utils.early_stopping.EarlyStopping', 'EarlyStopping', ([], {'patience': 'EARLY_STOP_PATIENCE'}), '(patience=EARLY_STOP_PATIENCE)\n', (19413, 19443), False, 'from utils.early_stopping import EarlyStopping\n'), ((27576, 27601), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (27599, 27601), False, 'import torch\n'), ((12512, 12550), 'numpy.array', 'np.array', (['values[1:]'], {'dtype': 'np.float32'}), '(values[1:], dtype=np.float32)\n', (12520, 12550), True, 'import numpy as np\n'), ((13306, 13331), 'numpy.zeros', 'np.zeros', (['[embedding_dim]'], {}), '([embedding_dim])\n', (13314, 13331), True, 'import numpy as np\n'), ((19026, 19066), 'utils.focalloss.FocalLoss', 'FocalLoss', ([], {'gamma': 'opt.focal', 'reduce': '(False)'}), '(gamma=opt.focal, reduce=False)\n', (19035, 19066), False, 'from utils.focalloss import FocalLoss\n'), ((19107, 19147), 'utils.focalloss.FocalLoss', 'FocalLoss', ([], {'gamma': 'opt.focal', 'reduce': '(False)'}), '(gamma=opt.focal, reduce=False)\n', (19116, 19147), False, 'from utils.focalloss import FocalLoss\n'), ((19683, 19746), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data_set'], {'batch_size': 'BATCH_SIZE', 'shuffle': '(True)'}), '(train_data_set, batch_size=BATCH_SIZE, shuffle=True)\n', (19693, 19746), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((19835, 19853), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (19851, 19853), False, 'import sys\n'), ((16073, 16096), 'allennlp.modules.elmo.batch_to_ids', 'batch_to_ids', (['data_text'], {}), '(data_text)\n', (16085, 16096), False, 'from allennlp.modules.elmo import Elmo, batch_to_ids\n'), ((18553, 18578), 'torch.Tensor', 'torch.Tensor', (['weight_list'], {}), '(weight_list)\n', (18565, 18578), False, 'import torch\n'), ((18686, 18718), 'torch.Tensor', 'torch.Tensor', (['weight_list_binary'], {}), '(weight_list_binary)\n', (18698, 18718), False, 'import torch\n'), ((19219, 19252), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'reduce': '(False)'}), '(reduce=False)\n', (19238, 19252), True, 'import torch.nn as nn\n'), ((19293, 19326), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'reduce': '(False)'}), '(reduce=False)\n', (19312, 19326), True, 'import torch.nn as nn\n'), ((26052, 26090), 'numpy.concatenate', 'np.concatenate', (['pred_list_test'], {'axis': '(0)'}), '(pred_list_test, axis=0)\n', (26066, 26090), True, 'import numpy as np\n'), ((27090, 27134), 'numpy.concatenate', 'np.concatenate', (['final_pred_list_test'], {'axis': '(0)'}), '(final_pred_list_test, axis=0)\n', (27104, 27134), True, 'import numpy as np\n'), ((22274, 22289), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (22287, 22289), False, 'import torch\n'), ((24581, 24611), 'copy.deepcopy', 'deepcopy', (['final_pred_list_test'], {}), '(final_pred_list_test)\n', (24589, 24611), False, 'from copy import deepcopy\n'), ((24770, 24794), 'copy.deepcopy', 'deepcopy', (['pred_list_test'], {}), '(pred_list_test)\n', (24778, 24794), False, 'from copy import deepcopy\n'), ((25435, 25450), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (25448, 25450), False, 'import torch\n'), ((26461, 26476), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (26474, 26476), False, 'import torch\n'), ((24981, 25011), 'copy.deepcopy', 'deepcopy', (['final_pred_list_test'], {}), '(final_pred_list_test)\n', (24989, 25011), False, 'from copy import deepcopy\n'), ((25118, 25142), 'copy.deepcopy', 'deepcopy', (['pred_list_test'], {}), '(pred_list_test)\n', (25126, 25142), False, 'from copy import deepcopy\n')] |
# Created byMartin.cz
# Copyright (c) <NAME>. All rights reserved.
import unittest
import pero
import numpy
class TestCase(unittest.TestCase):
"""Test case for linear interpolator."""
def test_log10(self):
"""Tests whether interpolator works for log10 range."""
interpol = pero.LogInterpol()
# test inside
self.assertEqual(interpol.normalize(10, 1, 100), 0.5)
self.assertEqual(interpol.denormalize(0.5, 1, 100), 10)
# test left
self.assertAlmostEqual(interpol.normalize(0.1, 1, 100), -0.5, 10)
self.assertAlmostEqual(interpol.denormalize(-0.5, 1, 100), 0.1, 10)
# test right
self.assertAlmostEqual(interpol.normalize(1000, 1, 100), 1.5, 10)
self.assertAlmostEqual(interpol.denormalize(1.5, 1, 100), 1000, 10)
def test_log2(self):
"""Tests whether interpolator works for log2 range."""
interpol = pero.LogInterpol()
# test inside
self.assertEqual(interpol.normalize(2, 1, 4), 0.5)
self.assertEqual(interpol.denormalize(0.5, 1, 4), 2)
# test left
self.assertAlmostEqual(interpol.normalize(0.5, 1, 4), -0.5, 10)
self.assertAlmostEqual(interpol.denormalize(-0.5, 1, 4), 0.5, 10)
# test right
self.assertAlmostEqual(interpol.normalize(8, 1, 4), 1.5, 10)
self.assertAlmostEqual(interpol.denormalize(1.5, 1, 4), 8, 10)
def test_arrays(self):
"""Tests whether interpolator works correctly with arrays."""
interpol = pero.LogInterpol()
data = [0.1, 10, 100, 1000]
model = [-0.5, 0.5, 1, 1.5]
numpy.testing.assert_almost_equal(list(interpol.normalize(numpy.array(data), 1, 100)), model, 10)
numpy.testing.assert_almost_equal(list(interpol.denormalize(numpy.array(model), 1, 100)), data, 10)
# run test case
if __name__ == "__main__":
unittest.main(verbosity=2)
| [
"unittest.main",
"pero.LogInterpol",
"numpy.array"
] | [((2004, 2030), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (2017, 2030), False, 'import unittest\n'), ((321, 339), 'pero.LogInterpol', 'pero.LogInterpol', ([], {}), '()\n', (337, 339), False, 'import pero\n'), ((982, 1000), 'pero.LogInterpol', 'pero.LogInterpol', ([], {}), '()\n', (998, 1000), False, 'import pero\n'), ((1632, 1650), 'pero.LogInterpol', 'pero.LogInterpol', ([], {}), '()\n', (1648, 1650), False, 'import pero\n'), ((1807, 1824), 'numpy.array', 'numpy.array', (['data'], {}), '(data)\n', (1818, 1824), False, 'import numpy\n'), ((1915, 1933), 'numpy.array', 'numpy.array', (['model'], {}), '(model)\n', (1926, 1933), False, 'import numpy\n')] |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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 random
import grpc
import numpy as np
import ms_service_pb2
import ms_service_pb2_grpc
import mindspore.dataset as de
from mindspore import Tensor, context
from mindspore import log as logger
from tests.st.networks.models.bert.src.bert_model import BertModel
from .generate_model import AddNet, bert_net_cfg
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
random.seed(1)
np.random.seed(1)
de.config.set_seed(1)
def test_add():
channel = grpc.insecure_channel('localhost:5500')
stub = ms_service_pb2_grpc.MSServiceStub(channel)
request = ms_service_pb2.PredictRequest()
x = request.data.add()
x.tensor_shape.dims.extend([4])
x.tensor_type = ms_service_pb2.MS_FLOAT32
x.data = (np.ones([4]).astype(np.float32)).tobytes()
y = request.data.add()
y.tensor_shape.dims.extend([4])
y.tensor_type = ms_service_pb2.MS_FLOAT32
y.data = (np.ones([4]).astype(np.float32)).tobytes()
result = stub.Predict(request)
result_np = np.frombuffer(result.result[0].data, dtype=np.float32).reshape(result.result[0].tensor_shape.dims)
print("ms client received: ")
print(result_np)
net = AddNet()
net_out = net(Tensor(np.ones([4]).astype(np.float32)), Tensor(np.ones([4]).astype(np.float32)))
print("add net out: ")
print(net_out)
assert np.allclose(net_out.asnumpy(), result_np, 0.001, 0.001, equal_nan=True)
def test_bert():
MAX_MESSAGE_LENGTH = 0x7fffffff
input_ids = np.random.randint(0, 1000, size=(2, 32), dtype=np.int32)
segment_ids = np.zeros((2, 32), dtype=np.int32)
input_mask = np.zeros((2, 32), dtype=np.int32)
channel = grpc.insecure_channel('localhost:5500', options=[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH),
('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)])
stub = ms_service_pb2_grpc.MSServiceStub(channel)
request = ms_service_pb2.PredictRequest()
x = request.data.add()
x.tensor_shape.dims.extend([2, 32])
x.tensor_type = ms_service_pb2.MS_INT32
x.data = input_ids.tobytes()
y = request.data.add()
y.tensor_shape.dims.extend([2, 32])
y.tensor_type = ms_service_pb2.MS_INT32
y.data = segment_ids.tobytes()
z = request.data.add()
z.tensor_shape.dims.extend([2, 32])
z.tensor_type = ms_service_pb2.MS_INT32
z.data = input_mask.tobytes()
result = stub.Predict(request)
result_np = np.frombuffer(result.result[0].data, dtype=np.float32).reshape(result.result[0].tensor_shape.dims)
print("ms client received: ")
print(result_np)
net = BertModel(bert_net_cfg, False)
bert_out = net(Tensor(input_ids), Tensor(segment_ids), Tensor(input_mask))
print("bert out: ")
print(bert_out[0])
bert_out_size = len(bert_out)
for i in range(bert_out_size):
result_np = np.frombuffer(result.result[i].data, dtype=np.float32).reshape(result.result[i].tensor_shape.dims)
logger.info("i:{}, result_np:{}, bert_out:{}".
format(i, result.result[i].tensor_shape.dims, bert_out[i].asnumpy().shape))
assert np.allclose(bert_out[i].asnumpy(), result_np, 0.001, 0.001, equal_nan=True)
| [
"mindspore.context.set_context",
"numpy.random.seed",
"numpy.frombuffer",
"grpc.insecure_channel",
"numpy.zeros",
"ms_service_pb2.PredictRequest",
"tests.st.networks.models.bert.src.bert_model.BertModel",
"mindspore.Tensor",
"numpy.ones",
"numpy.random.randint",
"random.seed",
"mindspore.datas... | [((984, 1052), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'device_target': '"""Ascend"""'}), "(mode=context.GRAPH_MODE, device_target='Ascend')\n", (1003, 1052), False, 'from mindspore import Tensor, context\n'), ((1054, 1068), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (1065, 1068), False, 'import random\n'), ((1069, 1086), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1083, 1086), True, 'import numpy as np\n'), ((1087, 1108), 'mindspore.dataset.config.set_seed', 'de.config.set_seed', (['(1)'], {}), '(1)\n', (1105, 1108), True, 'import mindspore.dataset as de\n'), ((1140, 1179), 'grpc.insecure_channel', 'grpc.insecure_channel', (['"""localhost:5500"""'], {}), "('localhost:5500')\n", (1161, 1179), False, 'import grpc\n'), ((1191, 1233), 'ms_service_pb2_grpc.MSServiceStub', 'ms_service_pb2_grpc.MSServiceStub', (['channel'], {}), '(channel)\n', (1224, 1233), False, 'import ms_service_pb2_grpc\n'), ((1248, 1279), 'ms_service_pb2.PredictRequest', 'ms_service_pb2.PredictRequest', ([], {}), '()\n', (1277, 1279), False, 'import ms_service_pb2\n'), ((2139, 2195), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000)'], {'size': '(2, 32)', 'dtype': 'np.int32'}), '(0, 1000, size=(2, 32), dtype=np.int32)\n', (2156, 2195), True, 'import numpy as np\n'), ((2214, 2247), 'numpy.zeros', 'np.zeros', (['(2, 32)'], {'dtype': 'np.int32'}), '((2, 32), dtype=np.int32)\n', (2222, 2247), True, 'import numpy as np\n'), ((2265, 2298), 'numpy.zeros', 'np.zeros', (['(2, 32)'], {'dtype': 'np.int32'}), '((2, 32), dtype=np.int32)\n', (2273, 2298), True, 'import numpy as np\n'), ((2313, 2483), 'grpc.insecure_channel', 'grpc.insecure_channel', (['"""localhost:5500"""'], {'options': "[('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), (\n 'grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)]"}), "('localhost:5500', options=[(\n 'grpc.max_send_message_length', MAX_MESSAGE_LENGTH), (\n 'grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)])\n", (2334, 2483), False, 'import grpc\n'), ((2548, 2590), 'ms_service_pb2_grpc.MSServiceStub', 'ms_service_pb2_grpc.MSServiceStub', (['channel'], {}), '(channel)\n', (2581, 2590), False, 'import ms_service_pb2_grpc\n'), ((2605, 2636), 'ms_service_pb2.PredictRequest', 'ms_service_pb2.PredictRequest', ([], {}), '()\n', (2634, 2636), False, 'import ms_service_pb2\n'), ((3292, 3322), 'tests.st.networks.models.bert.src.bert_model.BertModel', 'BertModel', (['bert_net_cfg', '(False)'], {}), '(bert_net_cfg, False)\n', (3301, 3322), False, 'from tests.st.networks.models.bert.src.bert_model import BertModel\n'), ((3342, 3359), 'mindspore.Tensor', 'Tensor', (['input_ids'], {}), '(input_ids)\n', (3348, 3359), False, 'from mindspore import Tensor, context\n'), ((3361, 3380), 'mindspore.Tensor', 'Tensor', (['segment_ids'], {}), '(segment_ids)\n', (3367, 3380), False, 'from mindspore import Tensor, context\n'), ((3382, 3400), 'mindspore.Tensor', 'Tensor', (['input_mask'], {}), '(input_mask)\n', (3388, 3400), False, 'from mindspore import Tensor, context\n'), ((1666, 1720), 'numpy.frombuffer', 'np.frombuffer', (['result.result[0].data'], {'dtype': 'np.float32'}), '(result.result[0].data, dtype=np.float32)\n', (1679, 1720), True, 'import numpy as np\n'), ((3127, 3181), 'numpy.frombuffer', 'np.frombuffer', (['result.result[0].data'], {'dtype': 'np.float32'}), '(result.result[0].data, dtype=np.float32)\n', (3140, 3181), True, 'import numpy as np\n'), ((3538, 3592), 'numpy.frombuffer', 'np.frombuffer', (['result.result[i].data'], {'dtype': 'np.float32'}), '(result.result[i].data, dtype=np.float32)\n', (3551, 3592), True, 'import numpy as np\n'), ((1404, 1416), 'numpy.ones', 'np.ones', (['[4]'], {}), '([4])\n', (1411, 1416), True, 'import numpy as np\n'), ((1571, 1583), 'numpy.ones', 'np.ones', (['[4]'], {}), '([4])\n', (1578, 1583), True, 'import numpy as np\n'), ((1865, 1877), 'numpy.ones', 'np.ones', (['[4]'], {}), '([4])\n', (1872, 1877), True, 'import numpy as np\n'), ((1906, 1918), 'numpy.ones', 'np.ones', (['[4]'], {}), '([4])\n', (1913, 1918), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@File :kine_UAV.py
@Description :
@Date :2021/09/29 14:08:39
@Author :<NAME>
'''
import numpy as np
from .rotation_matrix import RotationMatrix
rm = RotationMatrix()
class KineUAV():
"""
UAV kinematics, yaw is fixed
"""
def __init__(self) -> None:
self.tau_phi = 0.5
self.tau_theta = 0.5
self.K_phi = 1
self.K_theta = 1
self.Ax = 0.1
self.Ay = 0.1
self.Az = 0.2
self.g = 9.81
self.T_trim = self.g
def kine_nl(self, state, control):
"""
nonlinear system
Kinnmatics built based on https://doi.org/10.1109/LRA.2020.3010730
Yaw is fixed
"""
p = state[0:3]
v = state[3:6]
phi = state[6]
theta = state[7]
T = control[0]
phi_ref = control[1]
theta_ref = control[2]
R = rm.b2e_0psi(phi, theta)
d_p = v
d_v = np.matmul(R,np.array([0,0,T])) + np.array([0,0,-self.g]) - np.matmul(np.diag([self.Ax, self.Ay, self.Az]),v)
d_phi = 1/self.tau_phi*(self.K_phi*phi_ref-phi)
d_theta = 1/self.tau_theta*(self.K_theta*theta_ref - theta)
d_state = np.array([d_p,d_v])
d_state = np.append(d_state, d_phi)
d_state = np.append(d_state, d_theta)
return d_state
def sys_nl_ss(self, phi, theta):
"""
Matrices for the state-space form of nonlinear system
states = [p,v,phi,theta]
"""
A = np.array([
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,-self.Ax,0,0,0,0],
[0,0,0,0,-self.Ay,0,0,0],
[0,0,0,0,0,-self.Az,0,0],
[0,0,0,0,0,0,-1/self.tau_phi,0],
[0,0,0,0,0,0,0,-1/self.tau_theta]
])
B = np.array([
[0,0,0],
[0,0,0],
[0,0,0],
[np.sin(theta),0,0],
[-np.sin(phi)*np.cos(theta),0,0],
[np.cos(phi)*np.cos(theta),0,0],
[0,self.K_phi/self.tau_phi,0],
[0,0,self.K_theta/self.tau_theta]
])
dist_grav = np.array([0,0,0,0,0,-self.g,0,0])
return A, B, dist_grav
def kine_nl_ss(self, state, control):
"""
Kinnmatics built based on https://doi.org/10.1109/LRA.2020.3010730
Yaw is fixed
"""
A, B, dist_grav = self.sys_nl_ss(state[6], state[7])
d_state = np.matmul(A,state) + np.matmul(B,control) + dist_grav
return d_state
def sys_linear_ss(self):
"""
linearized system
states = [p,v,phi,theta]
trimed condition
"""
A = np.array([
[0,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,0],
[0,0,0,0,0,1,0,0],
[0,0,0,-self.Ax,0,0,0,self.T_trim],
[0,0,0,0,-self.Ay,0,-self.T_trim,0],
[0,0,0,0,0,-self.Az,0,0],
[0,0,0,0,0,0,-1/self.tau_phi,0],
[0,0,0,0,0,0,0,-1/self.tau_theta]
])
B = np.array([
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0],
[1,0,0],
[0,self.K_phi/self.tau_phi,0],
[0,0,self.K_theta/self.tau_theta]
])
return A, B
def augsys_linear_ss(self):
A, B = self.sys_linear_ss()
C = np.array([
[1,0,0,0,0,0,0,0],
[0,1,0,0,0,0,0,0],
[0,0,1,0,0,0,0,0]
])
a_temp = np.concatenate((A,np.zeros((8,3))), axis = 1)
b_temp = np.concatenate((C,np.zeros((3,3))), axis = 1)
A_aug = np.concatenate((a_temp,b_temp), axis = 0)
B_aug = np.concatenate((B,np.zeros((3,3))), axis = 0)
return A_aug, B_aug
class RefPos():
def __init__(self) -> None:
self.t_tkf = 5 # time for takeoff
def circle(self, time):
"""
A circle refernce path
"""
if time < self.t_tkf:
x_r = 0
y_r = 0
z_r = 0.1*time
else:
x_r = 0.5 - 0.5*np.cos(np.pi*(time-self.t_tkf)/10)
y_r = 0.5*np.sin(np.pi*(time-self.t_tkf)/10)
z_r = 1 - 0.5*np.cos(np.pi*(time-self.t_tkf)/10)
return np.array([x_r,y_r,z_r])
def eight(self, time):
"""
A eight-form refernce path
"""
if time < self.t_tkf:
x_r = 0
y_r = 0
z_r = 0.1*time
else:
x_r = 0.5 - 0.5*np.cos(np.pi*(time-self.t_tkf)/10)
y_r = 0.5*np.sin(np.pi*(time-self.t_tkf)/5)
z_r = 1 - 0.5*np.cos(np.pi*(time-self.t_tkf)/10)
return np.array([x_r,y_r,z_r])
def hover(self, time):
"""
Hover at a certain height
"""
if time < self.t_tkf:
x_r = 0
y_r = 0
z_r = 0.1*time
else:
x_r = 0
y_r = 0
z_r = 0.5
return np.array([x_r,y_r,z_r])
| [
"numpy.zeros",
"numpy.append",
"numpy.sin",
"numpy.array",
"numpy.matmul",
"numpy.cos",
"numpy.diag",
"numpy.concatenate"
] | [((1239, 1259), 'numpy.array', 'np.array', (['[d_p, d_v]'], {}), '([d_p, d_v])\n', (1247, 1259), True, 'import numpy as np\n'), ((1277, 1302), 'numpy.append', 'np.append', (['d_state', 'd_phi'], {}), '(d_state, d_phi)\n', (1286, 1302), True, 'import numpy as np\n'), ((1321, 1348), 'numpy.append', 'np.append', (['d_state', 'd_theta'], {}), '(d_state, d_theta)\n', (1330, 1348), True, 'import numpy as np\n'), ((1542, 1829), 'numpy.array', 'np.array', (['[[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, \n 0], [0, 0, 0, -self.Ax, 0, 0, 0, 0], [0, 0, 0, 0, -self.Ay, 0, 0, 0], [\n 0, 0, 0, 0, 0, -self.Az, 0, 0], [0, 0, 0, 0, 0, 0, -1 / self.tau_phi, 0\n ], [0, 0, 0, 0, 0, 0, 0, -1 / self.tau_theta]]'], {}), '([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, \n 0, 1, 0, 0], [0, 0, 0, -self.Ax, 0, 0, 0, 0], [0, 0, 0, 0, -self.Ay, 0,\n 0, 0], [0, 0, 0, 0, 0, -self.Az, 0, 0], [0, 0, 0, 0, 0, 0, -1 / self.\n tau_phi, 0], [0, 0, 0, 0, 0, 0, 0, -1 / self.tau_theta]])\n', (1550, 1829), True, 'import numpy as np\n'), ((2199, 2239), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, -self.g, 0, 0]'], {}), '([0, 0, 0, 0, 0, -self.g, 0, 0])\n', (2207, 2239), True, 'import numpy as np\n'), ((2736, 3049), 'numpy.array', 'np.array', (['[[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, \n 0], [0, 0, 0, -self.Ax, 0, 0, 0, self.T_trim], [0, 0, 0, 0, -self.Ay, 0,\n -self.T_trim, 0], [0, 0, 0, 0, 0, -self.Az, 0, 0], [0, 0, 0, 0, 0, 0, -\n 1 / self.tau_phi, 0], [0, 0, 0, 0, 0, 0, 0, -1 / self.tau_theta]]'], {}), '([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, \n 0, 1, 0, 0], [0, 0, 0, -self.Ax, 0, 0, 0, self.T_trim], [0, 0, 0, 0, -\n self.Ay, 0, -self.T_trim, 0], [0, 0, 0, 0, 0, -self.Az, 0, 0], [0, 0, 0,\n 0, 0, 0, -1 / self.tau_phi, 0], [0, 0, 0, 0, 0, 0, 0, -1 / self.tau_theta]]\n )\n', (2744, 3049), True, 'import numpy as np\n'), ((3089, 3243), 'numpy.array', 'np.array', (['[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0], [0, self\n .K_phi / self.tau_phi, 0], [0, 0, self.K_theta / self.tau_theta]]'], {}), '([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0],\n [0, self.K_phi / self.tau_phi, 0], [0, 0, self.K_theta / self.tau_theta]])\n', (3097, 3243), True, 'import numpy as np\n'), ((3428, 3521), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]]'], {}), '([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, \n 0, 0, 0, 0]])\n', (3436, 3521), True, 'import numpy as np\n'), ((3687, 3727), 'numpy.concatenate', 'np.concatenate', (['(a_temp, b_temp)'], {'axis': '(0)'}), '((a_temp, b_temp), axis=0)\n', (3701, 3727), True, 'import numpy as np\n'), ((4315, 4340), 'numpy.array', 'np.array', (['[x_r, y_r, z_r]'], {}), '([x_r, y_r, z_r])\n', (4323, 4340), True, 'import numpy as np\n'), ((4741, 4766), 'numpy.array', 'np.array', (['[x_r, y_r, z_r]'], {}), '([x_r, y_r, z_r])\n', (4749, 4766), True, 'import numpy as np\n'), ((5040, 5065), 'numpy.array', 'np.array', (['[x_r, y_r, z_r]'], {}), '([x_r, y_r, z_r])\n', (5048, 5065), True, 'import numpy as np\n'), ((1020, 1045), 'numpy.array', 'np.array', (['[0, 0, -self.g]'], {}), '([0, 0, -self.g])\n', (1028, 1045), True, 'import numpy as np\n'), ((1056, 1092), 'numpy.diag', 'np.diag', (['[self.Ax, self.Ay, self.Az]'], {}), '([self.Ax, self.Ay, self.Az])\n', (1063, 1092), True, 'import numpy as np\n'), ((2507, 2526), 'numpy.matmul', 'np.matmul', (['A', 'state'], {}), '(A, state)\n', (2516, 2526), True, 'import numpy as np\n'), ((2528, 2549), 'numpy.matmul', 'np.matmul', (['B', 'control'], {}), '(B, control)\n', (2537, 2549), True, 'import numpy as np\n'), ((3580, 3596), 'numpy.zeros', 'np.zeros', (['(8, 3)'], {}), '((8, 3))\n', (3588, 3596), True, 'import numpy as np\n'), ((3643, 3659), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (3651, 3659), True, 'import numpy as np\n'), ((3763, 3779), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (3771, 3779), True, 'import numpy as np\n'), ((4204, 4244), 'numpy.sin', 'np.sin', (['(np.pi * (time - self.t_tkf) / 10)'], {}), '(np.pi * (time - self.t_tkf) / 10)\n', (4210, 4244), True, 'import numpy as np\n'), ((4631, 4670), 'numpy.sin', 'np.sin', (['(np.pi * (time - self.t_tkf) / 5)'], {}), '(np.pi * (time - self.t_tkf) / 5)\n', (4637, 4670), True, 'import numpy as np\n'), ((999, 1018), 'numpy.array', 'np.array', (['[0, 0, T]'], {}), '([0, 0, T])\n', (1007, 1018), True, 'import numpy as np\n'), ((1961, 1974), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (1967, 1974), True, 'import numpy as np\n'), ((4147, 4187), 'numpy.cos', 'np.cos', (['(np.pi * (time - self.t_tkf) / 10)'], {}), '(np.pi * (time - self.t_tkf) / 10)\n', (4153, 4187), True, 'import numpy as np\n'), ((4265, 4305), 'numpy.cos', 'np.cos', (['(np.pi * (time - self.t_tkf) / 10)'], {}), '(np.pi * (time - self.t_tkf) / 10)\n', (4271, 4305), True, 'import numpy as np\n'), ((4574, 4614), 'numpy.cos', 'np.cos', (['(np.pi * (time - self.t_tkf) / 10)'], {}), '(np.pi * (time - self.t_tkf) / 10)\n', (4580, 4614), True, 'import numpy as np\n'), ((4691, 4731), 'numpy.cos', 'np.cos', (['(np.pi * (time - self.t_tkf) / 10)'], {}), '(np.pi * (time - self.t_tkf) / 10)\n', (4697, 4731), True, 'import numpy as np\n'), ((2007, 2020), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (2013, 2020), True, 'import numpy as np\n'), ((2040, 2051), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (2046, 2051), True, 'import numpy as np\n'), ((2052, 2065), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (2058, 2065), True, 'import numpy as np\n'), ((1995, 2006), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (2001, 2006), True, 'import numpy as np\n')] |
import numpy as np
from citysim3d.spaces import Space
class ConcatenationSpace(Space):
def __init__(self, spaces):
self.spaces = spaces
sizes = []
for space in self.spaces:
size, = space.shape
sizes.append(size)
cumsum = np.cumsum(sizes)
self.slices = [slice(start, stop) for start, stop in zip((0,) + tuple(cumsum[:-1]), cumsum)]
def sample(self):
return np.concatenate([space.sample() for space in self.spaces])
def contains(self, x):
assert x.shape == self.shape
return all(space.contains(x[s]) for space, s in zip(self.spaces, self.slices))
def clip(self, x, out=None):
assert x.shape == self.shape
if out is not None:
assert out.shape == self.shape
return np.concatenate([space.clip(x[s], out=(out[s] if out is not None else None))
for space, s in zip(self.spaces, self.slices)])
@property
def shape(self):
return (self.slices[-1].stop,)
| [
"numpy.cumsum"
] | [((283, 299), 'numpy.cumsum', 'np.cumsum', (['sizes'], {}), '(sizes)\n', (292, 299), True, 'import numpy as np\n')] |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import inspect, re
import numpy as np
import os
import collections
import subprocess as sp
import gc
from skimage.draw import disk, line_aa, polygon, polygon2mask, rectangle
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def tensor2im(image_tensor, imtype=np.uint8, index=0):
image_numpy = image_tensor[index].cpu().float().numpy()
if image_numpy.shape[0] == 1:
image_numpy = np.tile(image_numpy, (3, 1, 1))
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
return image_numpy.astype(imtype)
# draw pose img
LIMB_SEQ = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9],
[9, 10], [1, 11], [11, 12], [12, 13], [1, 0], [0, 14], [14, 16],
[0, 15], [15, 17], [2, 16], [5, 17]]
COLORS = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0],
[0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],
[170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
LABELS = ['nose', 'neck', 'Rsho', 'Relb', 'Rwri', 'Lsho', 'Lelb', 'Lwri',
'Rhip', 'Rkne', 'Rank', 'Lhip', 'Lkne', 'Lank', 'Leye', 'Reye', 'Lear', 'Rear']
MISSING_VALUE = -1
def map_to_cord(pose_map, threshold=0.1):
all_peaks = [[] for i in range(18)]
pose_map = pose_map[..., :18]
y, x, z = np.where(np.logical_and(pose_map == pose_map.max(axis=(0, 1)),
pose_map > threshold))
for x_i, y_i, z_i in zip(x, y, z):
all_peaks[z_i].append([x_i, y_i])
x_values = []
y_values = []
for i in range(18):
if len(all_peaks[i]) != 0:
x_values.append(all_peaks[i][0][0])
y_values.append(all_peaks[i][0][1])
else:
x_values.append(MISSING_VALUE)
y_values.append(MISSING_VALUE)
return np.concatenate([np.expand_dims(y_values, -1), np.expand_dims(x_values, -1)], axis=1)
def draw_pose_from_map(pose_map, threshold=0.1, index=0, **kwargs):
# CHW -> HCW -> HWC
pose_map = pose_map[index].cpu().transpose(1, 0).transpose(2, 1).numpy()
cords = map_to_cord(pose_map, threshold=threshold)
return draw_pose_from_cords(cords, pose_map.shape[:2], **kwargs)
def draw_pose_from_map_wider(pose_map, threshold=0.1, ratio=0.225, **kwargs):
# CHW -> HCW -> HWC
pose_map = pose_map[0].cpu().transpose(1, 0).transpose(2, 1).numpy()
cords = map_to_cord(pose_map, threshold=threshold)
for i in range(len(cords)):
tmp = cords[i][0] * ratio
if tmp < 0:
tmp = -1
cords[i][0] = round(tmp)
tmp = cords[i][1] * ratio
if tmp < 0:
tmp = -1
cords[i][1] = round(tmp)
return draw_pose_from_cords(cords, (round(pose_map.shape[0] * ratio), round(pose_map.shape[1] * ratio)), **kwargs)
# draw pose from map
def draw_pose_from_cords(pose_joints, img_size, radius=2, draw_joints=True):
colors = np.zeros(shape=img_size + (3,), dtype=np.uint8)
mask = np.zeros(shape=img_size, dtype=bool)
if draw_joints:
for f, t in LIMB_SEQ:
from_missing = pose_joints[f][0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE
to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[t][1] == MISSING_VALUE
if from_missing or to_missing:
continue
yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1])
colors[yy, xx] = np.expand_dims(val, 1) * 255
mask[yy, xx] = True
for i, joint in enumerate(pose_joints):
if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][1] == MISSING_VALUE:
continue
yy, xx = disk((joint[0], joint[1]), radius=radius, shape=img_size)
colors[yy, xx] = COLORS[i]
mask[yy, xx] = True
return colors, mask
def diagnose_network(net, name='network'):
mean = 0.0
count = 0
for param in net.parameters():
if param.grad is not None:
mean += torch.mean(torch.abs(param.grad.data))
count += 1
if count > 0:
mean = mean / count
print(name)
print(mean)
def save_image(image_numpy, image_path):
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path)
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [e for e in dir(object) if isinstance(getattr(object, e), collections.Callable)]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print("\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList]))
def varname(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
return m.group(1)
def print_numpy(x, val=True, shp=False):
x = x.astype(np.float64)
if shp:
print('shape,', x.shape)
if val:
x = x.flatten()
print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (
np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def avg_dic(old_dic, new_dic, n_iter):
if n_iter < 1:
return new_dic
for k, v in enumerate(old_dic):
if k in new_dic:
new_dic[k] = (v * (n_iter - 1) + new_dic[k]) / n_iter
return new_dic
def get_gpu_memory():
command = "nvidia-smi --query-gpu=memory.free --format=csv"
memory_free_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:]
memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)]
return memory_free_values
def debug_gpu_memory(model):
print("Free memory: ", get_gpu_memory())
attribs = {k: v.nelement() * v.element_size() for k, v in model.__dict__.items() if
isinstance(v, torch.Tensor)}
with open('garbage.log', 'a') as f:
for obj in gc.get_objects():
try:
if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)):
f.write(f'{type(obj)}: {obj.size()}\n')
except:
pass
f.write('%' * 20)
for n, t in model.named_parameters():
f.write(f'{n}: {t.shape}\n')
f.write('%' * 20)
for m in [model, model.netG]:
for n, t in m.__dict__.items():
if torch.is_tensor(t):
f.write(f'{n}: {t.shape}\n')
def get_kps(bp, thresh=0.1, w=None):
if w is None:
w = bp.shape[-1]
v, kps = bp.view(*bp.shape[:-2], -1).max(dim=-1)
kps = torch.stack((kps.div(w, rounding_mode='trunc'), kps % w), -1)
v = v > thresh
return kps, v
def box_from_pose(pose):
B, C, H, W = pose.shape
kps, v = get_kps(pose, thresh=0.5)
masks = torch.zeros((B, H, W), dtype=torch.bool, device=pose.device)
for b, kp in enumerate(kps):
h_min, w_min = kp[v[b]].min(axis=0).values.tolist()
h_max, w_max = kp[v[b]].max(axis=0).values.tolist()
h_min = max(0, h_min - 0.1 * H)
w_min = max(0, w_min - 0.1 * W)
h_max = min(H - 1, h_max + 0.1 * H)
w_max = min(W - 1, w_max + 0.1 * W)
mask = polygon2mask((H, W), [
(h_min, w_min),
(h_min, w_max),
(h_max, w_max),
(h_max, w_min)
])
masks[b] = torch.tensor(mask, device=pose.device)
return masks.unsqueeze(1)
def mask_from_pose(pose):
masks = pose.sum(dim=1, keepdims=True) > 0.7
rad = (pose > .5).sum(dim=-1).max().item()
img_size = pose.shape[-2:]
kps, v = get_kps(pose, thresh=0.5)
for b, kp in enumerate(kps):
points = [kp[i].tolist() for i in [0, 14, 16, 2, 3, 4, 8, 9, 10, 13, 12, 11, 7, 6, 5, 17, 15] if v[b, i]]
poly = polygon2mask(list(img_size), points)
for p in range(len(points)):
pt1 = points[p]
pt2 = points[(p + 1) % len(points)]
if pt1 == pt2:
continue
y, x, _ = weighted_line(*pt1, *pt2, rad)
in_bound = (x >= 0) * (x < img_size[1]) * (y >= 0) * (y < img_size[0])
x = x[in_bound]
y = y[in_bound]
poly[y, x] = True
masks[b] += torch.tensor(poly, device=pose.device)
return masks
def trapezium(y, y0, w):
return np.clip(np.minimum(y + 1 + w / 2 - y0, -y + 1 + w / 2 + y0), 0, 1)
def weighted_line(r0, c0, r1, c1, w, r_min=0, r_max=np.inf):
# The algorithm below works fine if c1 >= c0 and c1-c0 >= abs(r1-r0).
# If either of these cases are violated, do some switches.
if abs(c1 - c0) < abs(r1 - r0):
# Switch x and y, and switch again when returning.
xx, yy, val = weighted_line(c0, r0, c1, r1, w, r_min=r_min, r_max=r_max)
return yy, xx, val
# At this point we know that the distance in columns (x) is greater
# than that in rows (y). Possibly one more switch if c0 > c1.
if c0 > c1:
return weighted_line(r1, c1, r0, c0, w, r_min=r_min, r_max=r_max)
# The following is now always < 1 in abs
slope = (r1 - r0) / (c1 - c0)
# Adjust weight by the slope
w *= np.sqrt(1 + np.abs(slope)) / 2
# We write y as a function of x, because the slope is always <= 1
# (in absolute value)
x = np.arange(c0, c1 + 1, dtype=float)
y = x * slope + (c1 * r0 - c0 * r1) / (c1 - c0)
# Now instead of 2 values for y, we have 2*np.ceil(w/2).
# All values are 1 except the upmost and bottommost.
thickness = np.ceil(w / 2)
yy = (np.floor(y).reshape(-1, 1) + np.arange(-thickness - 1, thickness + 2).reshape(1, -1))
xx = np.repeat(x, yy.shape[1])
vals = trapezium(yy, y.reshape(-1, 1), w).flatten()
yy = yy.flatten()
# Exclude useless parts and those outside of the interval
# to avoid parts outside the picture
mask = np.logical_and.reduce((yy >= r_min, yy < r_max, vals > 0))
return yy[mask].astype(int), xx[mask].astype(int), vals[mask]
| [
"numpy.abs",
"numpy.floor",
"numpy.mean",
"numpy.arange",
"numpy.tile",
"numpy.std",
"os.path.exists",
"numpy.logical_and.reduce",
"numpy.transpose",
"numpy.max",
"torch.zeros",
"torch.is_tensor",
"re.search",
"numpy.repeat",
"numpy.minimum",
"numpy.ceil",
"skimage.draw.line_aa",
"... | [((3113, 3160), 'numpy.zeros', 'np.zeros', ([], {'shape': '(img_size + (3,))', 'dtype': 'np.uint8'}), '(shape=img_size + (3,), dtype=np.uint8)\n', (3121, 3160), True, 'import numpy as np\n'), ((3172, 3208), 'numpy.zeros', 'np.zeros', ([], {'shape': 'img_size', 'dtype': 'bool'}), '(shape=img_size, dtype=bool)\n', (3180, 3208), True, 'import numpy as np\n'), ((4403, 4431), 'PIL.Image.fromarray', 'Image.fromarray', (['image_numpy'], {}), '(image_numpy)\n', (4418, 4431), False, 'from PIL import Image\n'), ((7435, 7495), 'torch.zeros', 'torch.zeros', (['(B, H, W)'], {'dtype': 'torch.bool', 'device': 'pose.device'}), '((B, H, W), dtype=torch.bool, device=pose.device)\n', (7446, 7495), False, 'import torch\n'), ((9924, 9958), 'numpy.arange', 'np.arange', (['c0', '(c1 + 1)'], {'dtype': 'float'}), '(c0, c1 + 1, dtype=float)\n', (9933, 9958), True, 'import numpy as np\n'), ((10146, 10160), 'numpy.ceil', 'np.ceil', (['(w / 2)'], {}), '(w / 2)\n', (10153, 10160), True, 'import numpy as np\n'), ((10266, 10291), 'numpy.repeat', 'np.repeat', (['x', 'yy.shape[1]'], {}), '(x, yy.shape[1])\n', (10275, 10291), True, 'import numpy as np\n'), ((10485, 10543), 'numpy.logical_and.reduce', 'np.logical_and.reduce', (['(yy >= r_min, yy < r_max, vals > 0)'], {}), '((yy >= r_min, yy < r_max, vals > 0))\n', (10506, 10543), True, 'import numpy as np\n'), ((537, 568), 'numpy.tile', 'np.tile', (['image_numpy', '(3, 1, 1)'], {}), '(image_numpy, (3, 1, 1))\n', (544, 568), True, 'import numpy as np\n'), ((3894, 3951), 'skimage.draw.disk', 'disk', (['(joint[0], joint[1])'], {'radius': 'radius', 'shape': 'img_size'}), '((joint[0], joint[1]), radius=radius, shape=img_size)\n', (3898, 3951), False, 'from skimage.draw import disk, line_aa, polygon, polygon2mask, rectangle\n'), ((5080, 5151), 're.search', 're.search', (['"""\\\\bvarname\\\\s*\\\\(\\\\s*([A-Za-z_][A-Za-z0-9_]*)\\\\s*\\\\)"""', 'line'], {}), "('\\\\bvarname\\\\s*\\\\(\\\\s*([A-Za-z_][A-Za-z0-9_]*)\\\\s*\\\\)', line)\n", (5089, 5151), False, 'import inspect, re\n'), ((5698, 5718), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (5712, 5718), False, 'import os\n'), ((5728, 5745), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (5739, 5745), False, 'import os\n'), ((6540, 6556), 'gc.get_objects', 'gc.get_objects', ([], {}), '()\n', (6554, 6556), False, 'import gc\n'), ((7834, 7925), 'skimage.draw.polygon2mask', 'polygon2mask', (['(H, W)', '[(h_min, w_min), (h_min, w_max), (h_max, w_max), (h_max, w_min)]'], {}), '((H, W), [(h_min, w_min), (h_min, w_max), (h_max, w_max), (\n h_max, w_min)])\n', (7846, 7925), False, 'from skimage.draw import disk, line_aa, polygon, polygon2mask, rectangle\n'), ((7999, 8037), 'torch.tensor', 'torch.tensor', (['mask'], {'device': 'pose.device'}), '(mask, device=pose.device)\n', (8011, 8037), False, 'import torch\n'), ((8871, 8909), 'torch.tensor', 'torch.tensor', (['poly'], {'device': 'pose.device'}), '(poly, device=pose.device)\n', (8883, 8909), False, 'import torch\n'), ((8974, 9025), 'numpy.minimum', 'np.minimum', (['(y + 1 + w / 2 - y0)', '(-y + 1 + w / 2 + y0)'], {}), '(y + 1 + w / 2 - y0, -y + 1 + w / 2 + y0)\n', (8984, 9025), True, 'import numpy as np\n'), ((2035, 2063), 'numpy.expand_dims', 'np.expand_dims', (['y_values', '(-1)'], {}), '(y_values, -1)\n', (2049, 2063), True, 'import numpy as np\n'), ((2065, 2093), 'numpy.expand_dims', 'np.expand_dims', (['x_values', '(-1)'], {}), '(x_values, -1)\n', (2079, 2093), True, 'import numpy as np\n'), ((3552, 3639), 'skimage.draw.line_aa', 'line_aa', (['pose_joints[f][0]', 'pose_joints[f][1]', 'pose_joints[t][0]', 'pose_joints[t][1]'], {}), '(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0],\n pose_joints[t][1])\n', (3559, 3639), False, 'from skimage.draw import disk, line_aa, polygon, polygon2mask, rectangle\n'), ((588, 624), 'numpy.transpose', 'np.transpose', (['image_numpy', '(1, 2, 0)'], {}), '(image_numpy, (1, 2, 0))\n', (600, 624), True, 'import numpy as np\n'), ((3665, 3687), 'numpy.expand_dims', 'np.expand_dims', (['val', '(1)'], {}), '(val, 1)\n', (3679, 3687), True, 'import numpy as np\n'), ((4215, 4241), 'torch.abs', 'torch.abs', (['param.grad.data'], {}), '(param.grad.data)\n', (4224, 4241), False, 'import torch\n'), ((5033, 5055), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (5053, 5055), False, 'import inspect, re\n'), ((7015, 7033), 'torch.is_tensor', 'torch.is_tensor', (['t'], {}), '(t)\n', (7030, 7033), False, 'import torch\n'), ((9800, 9813), 'numpy.abs', 'np.abs', (['slope'], {}), '(slope)\n', (9806, 9813), True, 'import numpy as np\n'), ((10171, 10182), 'numpy.floor', 'np.floor', (['y'], {}), '(y)\n', (10179, 10182), True, 'import numpy as np\n'), ((10200, 10240), 'numpy.arange', 'np.arange', (['(-thickness - 1)', '(thickness + 2)'], {}), '(-thickness - 1, thickness + 2)\n', (10209, 10240), True, 'import numpy as np\n'), ((5442, 5452), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (5449, 5452), True, 'import numpy as np\n'), ((5454, 5463), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (5460, 5463), True, 'import numpy as np\n'), ((5465, 5474), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (5471, 5474), True, 'import numpy as np\n'), ((5476, 5488), 'numpy.median', 'np.median', (['x'], {}), '(x)\n', (5485, 5488), True, 'import numpy as np\n'), ((5490, 5499), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (5496, 5499), True, 'import numpy as np\n'), ((6594, 6614), 'torch.is_tensor', 'torch.is_tensor', (['obj'], {}), '(obj)\n', (6609, 6614), False, 'import torch\n'), ((6644, 6669), 'torch.is_tensor', 'torch.is_tensor', (['obj.data'], {}), '(obj.data)\n', (6659, 6669), False, 'import torch\n')] |
import time
import numpy as np
class Simplex:
"""Primal simplex method that solves a linear program expressed in standard form.
It starts with a feasible basic solution, and moves from one feasible basic solution to
another to decrease objective function, until reaching the minimum.
"""
def __init__(self, arg_tab, names=None):
"""Initiates a Simplex object."""
self.iterations = 0
self.solvetime = None
# code -1: solving, 0: solved, 1: unbounded, 2: infeasible
self.code = -1
self.constrs = arg_tab[:-1, :]
self.objective = arg_tab[-1, :]
self.tab = np.vstack((self.constrs, self.objective))
self.n_constrs = self.constrs.shape[0]
self.n_vars = self.constrs.shape[1] - 1
self.n_arts = 0
if names is None:
self.names = ['x' + str(i + 1) for i in range(self.n_vars)]
else:
self.names = names
def print_tab(self, width=8):
"""Prints current tab."""
print(''.join(name.rjust(width) for name in self.names))
for i in range(self.tab.shape[0]):
print(''.join('{0:0.3f}'.format(self.tab[i][j]).rjust(width) for j in range(self.tab.shape[1])))
def indices(self):
"""Returns indices of basic vars in tab."""
candidates = np.where(self.tab[:self.n_constrs, :-1] == 1)
indices = []
for n in range(len(candidates[0])):
if len(np.where(self.tab[:self.n_constrs, candidates[1][n]] == 0)[0]) == self.n_constrs-1:
indices.append((candidates[0][n], candidates[1][n]))
return indices
def is_canonical(self, verbose=False):
"""Returns whether tab is in canonical form or not."""
# condition 3: RHS non-negative
if not all(self.tab[:, -1] >= 0):
if verbose:
print('not in canonical form for violating condition 3: RHS non-negative')
return False
# condition 4: isolated var
if len(self.indices()) < self.n_constrs:
if verbose:
print('not in canonical form for violating condition 4: isolated var')
return False
# is canonical
if verbose:
print('in canonical form')
return True
def put_canonical(self, verbose=False):
"""Puts tab in canonical form."""
# indices of basic variables
indices = self.indices()
i_indices = [idx[0] for idx in indices]
# number of artificial vars needed
self.n_arts = self.n_constrs - len(indices)
self.names = self.names + ['a' + str(i+1) for i in range(self.n_arts)]
# artificial constr
art_constr = np.copy(self.constrs[:, :-1])
art_i_indices = []
aux = np.zeros((self.n_constrs, self.n_arts))
art_j = 0
for i in range(self.n_constrs):
if i not in i_indices:
aux[i][art_j] = 1
art_i_indices.append(i)
art_j += 1
art_constr = np.hstack((art_constr, aux, np.expand_dims(self.constrs[:, -1], axis=-1)))
# artificial objective
art_objective = np.zeros((1, art_constr.shape[1]))
for i in art_i_indices:
art_objective -= art_constr[i, :]
art_objective[0, self.n_vars:-1] = 0
# new tab
objective = np.hstack((self.objective[:-1], np.zeros(self.n_arts), self.objective[-1]))
self.tab = np.vstack((art_constr, objective, art_objective))
if verbose:
print('\noriginal problem with artificial vars:')
self.print_tab()
# try to put in canonical form
while self.should_continue():
self.pivot(verbose=verbose)
# remove redundancy
indices = self.indices()
for idx in indices:
# if artificial variable in basic variables set
if idx[1] >= self.n_vars:
if verbose:
print('artificial variable a{} in basic variables set'.format(idx[1]-self.n_vars+1))
leaves = idx[0]
# remove redundant constraint
if all(self.tab[leaves, :self.n_vars] == 0):
if verbose:
print('constraint {} is redundant'.format(idx[0]+1))
else:
enters = np.where(self.tab[leaves, :self.n_vars] != 0)[0][0]
self.pivot(enters=enters, leaves=leaves, verbose=verbose)
# original problem is feasible
if abs(self.tab[-1][-1]) <= 0.00001:
# remove artificial objective and artificial variables
# reset self.n_vars to the correct number
self.names = self.names[:-self.n_arts]
self.tab = np.hstack((self.tab[:-1, :self.n_vars], np.expand_dims(self.tab[:-1, -1], axis=-1)))
self.code = -1
if verbose:
print('\noriginal problem has feasible soln and is now in canonical form:')
self.print_tab()
return True
# original problem is infeasible
else:
self.code = 2
return False
def pivot(self, enters=None, leaves=None, verbose=False):
"""Pivots the tab."""
self.iterations += 1
if enters is None:
# find pivot point
enters = np.argmin(self.tab[-1, :self.n_vars])
ratios = []
for i in range(self.n_constrs):
if self.tab[i, enters] > 0:
ratios.append(self.tab[i, -1] / self.tab[i, enters])
else:
ratios.append(float('inf'))
leaves = np.argmin(ratios)
# row of pivot point
self.tab[leaves] = self.tab[leaves] / self.tab[leaves, enters]
# the remaining rows
for i in range(self.tab.shape[0]):
if i != leaves:
self.tab[i] = self.tab[i] - self.tab[i, enters] * self.tab[leaves]
if verbose:
print('pivoting at:', leaves + 1, enters + 1)
self.print_tab()
def should_continue(self):
"""Returns whether should continue pivoting or not."""
# theorem O: reached optimality when all c_k > 0
if all(c >= 0 for c in self.tab[-1, :self.n_vars]):
if all(self.tab[:self.n_constrs, -1] >= 0):
self.code = 0
else:
self.code = 2
return False
# theorem U: unbounded if all a_ik <= 0, c_k < 0
else:
for k in range(self.n_vars):
if self.tab[-1, k] < 0:
if all(a <= 0 for a in self.tab[:-1, k]):
self.code = 1
return False
return True
def solve(self, verbose=False):
"""Solves linear program."""
# start solving
if verbose:
print('original problem:')
self.print_tab()
start = time.time()
# stage 1
if not self.is_canonical(verbose=verbose):
self.put_canonical(verbose=verbose)
# stage 2
if self.code == -1:
while self.should_continue():
self.pivot(verbose=verbose)
self.solvetime = time.time() - start
# report
if verbose:
if self.code == 0:
soln = np.zeros(self.n_vars)
for i in range(self.n_vars):
if len(np.where(self.tab[:-1, i] > 0)[0]) == 1:
arr = np.where(self.tab[:, i] == 1)[0]
if len(arr) == 1:
soln[i] = self.tab[:, -1][arr[0]]
print('solution:')
print('(' + ', '.join('{0:0.3f}'.format(x) for x in soln) + ')')
print('objective function:')
print('{0:0.3f}'.format(-self.tab[-1, -1]))
elif self.code == 1:
print('problem is unbounded')
elif self.code == 2:
print('original problem has no feasible soln')
if __name__ == '__main__':
# in canonical form
tab1 = np.array([[1, 0, 0, 2, -1, 10],
[0, 1, 0, -1, -5, 20],
[0, 0, 1, 6, -12, 18],
[0, 0, 0, -2, 3, 60]], dtype=float)
tab2 = np.array([[3, 2, 0, 1, 0, 0, 60],
[-1, 1, 4, 0, 1, 0, 10],
[2, -2, 5, 0, 0, 1, 50],
[-2, -3, -3, 0, 0, 0, 0]], dtype=float)
# in standard form
std1 = np.array([[1, -2, -3, -2, 3],
[1, -1, 2, 1, 11],
[2, -3, 1, 1, 0]], dtype=float)
# infeasible
std2 = np.array([[1, 2, 1, 1, 0, 1],
[-1, 0, 2, 0, -1, 4],
[1, -1, 2, 0, 0, 4],
[1, 1, 1, 0, 0, 0]], dtype=float)
# https://www.youtube.com/watch?v=CiLG14fsPdc&list=PLbxFfU5GKZz1Tm_9RR5M_uvdOXpJJ8LC3&index=9 at 36:58
std3 = np.array([[1, -1, 0, 1],
[2, 1, -1, 3],
[0, 0, 0, 0]], dtype=float)
# https://www.youtube.com/watch?v=CiLG14fsPdc&list=PLbxFfU5GKZz1Tm_9RR5M_uvdOXpJJ8LC3&index=9 at 47:57
std4 = np.array([[1, -2, -3, -2, 3],
[1, -1, 2, 1, 11],
[2, -3, 1, 1, 0]], dtype=float)
# https://www.youtube.com/watch?v=_uhTN6KvCC8 at 52:42
# redundant
red1 = np.array([[1, -2, 3, 1, 6],
[-1, 1, 2, 2/3, 4],
[2, -1, 1, -1, 0]], dtype=float)
# https://www.youtube.com/watch?v=_uhTN6KvCC8 at 1:04:46
# redundant
red2 = np.array([[1, 2, 0, 1, 20],
[2, 1, 1, 0, 10],
[-1, 4, -2, 3, 40],
[1, 4, 3, 2, 0]], dtype=float)
# s = Simplex(tab1)
# s = Simplex(tab2)
# s = Simplex(std1)
# s = Simplex(std2)
# s = Simplex(std3)
# s = Simplex(std4)
# s = Simplex(red1)
s = Simplex(red2)
s.solve(verbose=True)
| [
"numpy.copy",
"numpy.zeros",
"numpy.expand_dims",
"numpy.argmin",
"time.time",
"numpy.where",
"numpy.array",
"numpy.vstack"
] | [((8361, 8479), 'numpy.array', 'np.array', (['[[1, 0, 0, 2, -1, 10], [0, 1, 0, -1, -5, 20], [0, 0, 1, 6, -12, 18], [0, 0,\n 0, -2, 3, 60]]'], {'dtype': 'float'}), '([[1, 0, 0, 2, -1, 10], [0, 1, 0, -1, -5, 20], [0, 0, 1, 6, -12, 18\n ], [0, 0, 0, -2, 3, 60]], dtype=float)\n', (8369, 8479), True, 'import numpy as np\n'), ((8555, 8682), 'numpy.array', 'np.array', (['[[3, 2, 0, 1, 0, 0, 60], [-1, 1, 4, 0, 1, 0, 10], [2, -2, 5, 0, 0, 1, 50],\n [-2, -3, -3, 0, 0, 0, 0]]'], {'dtype': 'float'}), '([[3, 2, 0, 1, 0, 0, 60], [-1, 1, 4, 0, 1, 0, 10], [2, -2, 5, 0, 0,\n 1, 50], [-2, -3, -3, 0, 0, 0, 0]], dtype=float)\n', (8563, 8682), True, 'import numpy as np\n'), ((8783, 8868), 'numpy.array', 'np.array', (['[[1, -2, -3, -2, 3], [1, -1, 2, 1, 11], [2, -3, 1, 1, 0]]'], {'dtype': 'float'}), '([[1, -2, -3, -2, 3], [1, -1, 2, 1, 11], [2, -3, 1, 1, 0]], dtype=float\n )\n', (8791, 8868), True, 'import numpy as np\n'), ((8940, 9050), 'numpy.array', 'np.array', (['[[1, 2, 1, 1, 0, 1], [-1, 0, 2, 0, -1, 4], [1, -1, 2, 0, 0, 4], [1, 1, 1, 0,\n 0, 0]]'], {'dtype': 'float'}), '([[1, 2, 1, 1, 0, 1], [-1, 0, 2, 0, -1, 4], [1, -1, 2, 0, 0, 4], [1,\n 1, 1, 0, 0, 0]], dtype=float)\n', (8948, 9050), True, 'import numpy as np\n'), ((9235, 9302), 'numpy.array', 'np.array', (['[[1, -1, 0, 1], [2, 1, -1, 3], [0, 0, 0, 0]]'], {'dtype': 'float'}), '([[1, -1, 0, 1], [2, 1, -1, 3], [0, 0, 0, 0]], dtype=float)\n', (9243, 9302), True, 'import numpy as np\n'), ((9469, 9554), 'numpy.array', 'np.array', (['[[1, -2, -3, -2, 3], [1, -1, 2, 1, 11], [2, -3, 1, 1, 0]]'], {'dtype': 'float'}), '([[1, -2, -3, -2, 3], [1, -1, 2, 1, 11], [2, -3, 1, 1, 0]], dtype=float\n )\n', (9477, 9554), True, 'import numpy as np\n'), ((9685, 9772), 'numpy.array', 'np.array', (['[[1, -2, 3, 1, 6], [-1, 1, 2, 2 / 3, 4], [2, -1, 1, -1, 0]]'], {'dtype': 'float'}), '([[1, -2, 3, 1, 6], [-1, 1, 2, 2 / 3, 4], [2, -1, 1, -1, 0]], dtype\n =float)\n', (9693, 9772), True, 'import numpy as np\n'), ((9903, 10003), 'numpy.array', 'np.array', (['[[1, 2, 0, 1, 20], [2, 1, 1, 0, 10], [-1, 4, -2, 3, 40], [1, 4, 3, 2, 0]]'], {'dtype': 'float'}), '([[1, 2, 0, 1, 20], [2, 1, 1, 0, 10], [-1, 4, -2, 3, 40], [1, 4, 3,\n 2, 0]], dtype=float)\n', (9911, 10003), True, 'import numpy as np\n'), ((662, 703), 'numpy.vstack', 'np.vstack', (['(self.constrs, self.objective)'], {}), '((self.constrs, self.objective))\n', (671, 703), True, 'import numpy as np\n'), ((1366, 1411), 'numpy.where', 'np.where', (['(self.tab[:self.n_constrs, :-1] == 1)'], {}), '(self.tab[:self.n_constrs, :-1] == 1)\n', (1374, 1411), True, 'import numpy as np\n'), ((2793, 2822), 'numpy.copy', 'np.copy', (['self.constrs[:, :-1]'], {}), '(self.constrs[:, :-1])\n', (2800, 2822), True, 'import numpy as np\n'), ((2866, 2905), 'numpy.zeros', 'np.zeros', (['(self.n_constrs, self.n_arts)'], {}), '((self.n_constrs, self.n_arts))\n', (2874, 2905), True, 'import numpy as np\n'), ((3262, 3296), 'numpy.zeros', 'np.zeros', (['(1, art_constr.shape[1])'], {}), '((1, art_constr.shape[1]))\n', (3270, 3296), True, 'import numpy as np\n'), ((3561, 3610), 'numpy.vstack', 'np.vstack', (['(art_constr, objective, art_objective)'], {}), '((art_constr, objective, art_objective))\n', (3570, 3610), True, 'import numpy as np\n'), ((7164, 7175), 'time.time', 'time.time', ([], {}), '()\n', (7173, 7175), False, 'import time\n'), ((5510, 5547), 'numpy.argmin', 'np.argmin', (['self.tab[-1, :self.n_vars]'], {}), '(self.tab[-1, :self.n_vars])\n', (5519, 5547), True, 'import numpy as np\n'), ((5831, 5848), 'numpy.argmin', 'np.argmin', (['ratios'], {}), '(ratios)\n', (5840, 5848), True, 'import numpy as np\n'), ((7464, 7475), 'time.time', 'time.time', ([], {}), '()\n', (7473, 7475), False, 'import time\n'), ((3156, 3200), 'numpy.expand_dims', 'np.expand_dims', (['self.constrs[:, -1]'], {'axis': '(-1)'}), '(self.constrs[:, -1], axis=-1)\n', (3170, 3200), True, 'import numpy as np\n'), ((3497, 3518), 'numpy.zeros', 'np.zeros', (['self.n_arts'], {}), '(self.n_arts)\n', (3505, 3518), True, 'import numpy as np\n'), ((7581, 7602), 'numpy.zeros', 'np.zeros', (['self.n_vars'], {}), '(self.n_vars)\n', (7589, 7602), True, 'import numpy as np\n'), ((4942, 4984), 'numpy.expand_dims', 'np.expand_dims', (['self.tab[:-1, -1]'], {'axis': '(-1)'}), '(self.tab[:-1, -1], axis=-1)\n', (4956, 4984), True, 'import numpy as np\n'), ((1499, 1557), 'numpy.where', 'np.where', (['(self.tab[:self.n_constrs, candidates[1][n]] == 0)'], {}), '(self.tab[:self.n_constrs, candidates[1][n]] == 0)\n', (1507, 1557), True, 'import numpy as np\n'), ((4484, 4529), 'numpy.where', 'np.where', (['(self.tab[leaves, :self.n_vars] != 0)'], {}), '(self.tab[leaves, :self.n_vars] != 0)\n', (4492, 4529), True, 'import numpy as np\n'), ((7749, 7778), 'numpy.where', 'np.where', (['(self.tab[:, i] == 1)'], {}), '(self.tab[:, i] == 1)\n', (7757, 7778), True, 'import numpy as np\n'), ((7677, 7707), 'numpy.where', 'np.where', (['(self.tab[:-1, i] > 0)'], {}), '(self.tab[:-1, i] > 0)\n', (7685, 7707), True, 'import numpy as np\n')] |
"""
Integrator module
=================
Module with the classes of integrators to multi-thread the integration of
an ordinary differential equations
.. math:: \dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})
of the model and its linearized version.
Module classes
--------------
* :class:`RungeKuttaIntegrator`
* :class:`RungeKuttaTglsIntegrator`
"""
import multiprocessing
import numpy as np
from numba import njit
from integrators.integrate import _integrate_runge_kutta_jit, _integrate_runge_kutta_tgls_jit, _zeros_func
from functions.util import reverse
class RungeKuttaIntegrator(object):
"""Class to integrate the ordinary differential equations (ODEs)
.. math:: \dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})
with a set of :class:`TrajectoryProcess` and a specified `Runge-Kutta method`_.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
Parameters
----------
num_threads: None or int, optional
Number of :class:`TrajectoryProcess` workers (threads) to use. If `None`, use the number of machine's
cores available. Default to `None`.
b: None or ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
c: None or ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
a: None or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
number_of_dimensions: None or int, optional
Allow to hardcode the dynamical system dimension. If `None`, evaluate the dimension from the
callable :attr:`func`. Default to `None`.
Attributes
----------
num_threads: int
Number of :class:`TrajectoryProcess` workers (threads) to use.
b: ~numpy.ndarray
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: ~numpy.ndarray
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
n_dim: int
Dynamical system dimension.
n_traj: int
The number of trajectories (initial conditions) computed at the last integration
performed by the integrator.
n_records: int
The number of saved states of the last integration performed by the integrator.
ic: ~numpy.ndarray
Store the integrator initial conditions.
time: ~numpy.ndarray
The time at which the state of the system was saved. Array of shape (`n_records`,).
recorded_traj: ~numpy.ndarray
Saved states of the ODEs. 3D array of shape (`n_traj`, `n_dim`, `n_records`).
func: callable
Last function :math:`\\boldsymbol{f}` used by the integrator to integrate.
"""
def __init__(self, num_threads=None, b=None, c=None, a=None, number_of_dimensions=None):
if num_threads is None:
self.num_threads = multiprocessing.cpu_count()
else:
self.num_threads = num_threads
# Default is RK4
if a is None and b is None and c is None:
self.c = np.array([0., 0.5, 0.5, 1.])
self.b = np.array([1./6, 1./3, 1./3, 1./6])
self.a = np.zeros((len(self.c), len(self.b)))
self.a[1, 0] = 0.5
self.a[2, 1] = 0.5
self.a[3, 2] = 1.
else:
self.a = a
self.b = b
self.c = c
self.ic = None
self.time = None
self.recorded_traj = None
self.n_traj = 0
self.n_dim = number_of_dimensions
self.n_records = 0
self._write_steps = 0
self._time_direction = 1
self.func = None
self._ics_queue = None
self._traj_queue = None
self._processes_list = list()
def terminate(self):
"""Stop the workers (threads) and release the resources of the integrator."""
for process in self._processes_list:
process.terminate()
process.join()
def start(self):
"""Start or restart the workers (threads) of the integrator.
Warnings
--------
If the integrator was not previously terminated, it will be terminated first in the case
of a restart.
"""
self.terminate()
self._processes_list = list()
self._ics_queue = multiprocessing.JoinableQueue()
self._traj_queue = multiprocessing.Queue()
for i in range(self.num_threads):
self._processes_list.append(TrajectoryProcess(i, self.func, self.b, self.c, self.a,
self._ics_queue, self._traj_queue))
for process in self._processes_list:
process.daemon = True
process.start()
def set_func(self, f, ic_init=True):
"""Set the `Numba`_-jitted function :math:`\\boldsymbol{f}` to integrate.
.. _Numba: https://numba.pydata.org/
Parameters
----------
f: callable
The `Numba`_-jitted function :math:`\\boldsymbol{f}`.
Should have the signature ``f(t, x)`` where ``x`` is the state value and ``t`` is the time.
ic_init: bool, optional
Re-initialize or not the initial conditions of the integrator. Default to `True`.
Warnings
--------
This function restarts the integrator!
"""
self.func = f
if ic_init:
self.ic = None
self.start()
def set_bca(self, b=None, c=None, a=None, ic_init=True):
"""Set the coefficients of the `Runge-Kutta method`_ and restart the integrator. s
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
Parameters
----------
b: None or ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
c: None or ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
a: None or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
ic_init: bool, optional
Re-initialize or not the initial conditions of the integrator. Default to `True`.
"""
if a is not None:
self.a = a
if b is not None:
self.b = b
if c is not None:
self.c = c
if ic_init:
self.ic = None
self.start()
def initialize(self, convergence_time, dt, pert_size=0.01, reconvergence_time=None, forward=True,
number_of_trajectories=1, ic=None, reconverge=False):
"""Initialize the integration on an attractor by running it for a transient time,
For an ensemble of initial conditions, can do the same transient time for each, or the
`convergence_time` for the first one, and a smaller `reconvergence_time` for the subsequent ones.
This results into initial conditions on the attractor, stored in :attr:`ic`.
Parameters
----------
convergence_time: float
Transient time needed to converge to the attractor.
dt: float
Timestep of the transient integration.
pert_size:float, optional
If the reconvergence is activated, size of the perturbation to add to the previous ic to find
the next one. Default to 0.01 .
reconvergence_time: None or float, optional
Transient time for the subsequent trajectories after the first long `transient_time`.
forward: bool, optional
Whether to integrate the ODEs forward or backward in time. In case of backward integration, the
initial condition `ic` becomes a final condition. Default to forward integration.
number_of_trajectories: int
Number of initial conditions to find. Default to 1. Inactive if `ic` is provided.
ic: None or ~numpy.ndarray(float), optional
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
If `None`, use `number_trajectories` random initial conditions. Default to `None`.
reconverge: bool
Use or not the smaller transient time reconvergence with a perturbation
after the first initial conditions have been computed. If activated, only use the :attr:`num_threads`
first initial conditions of the `ic` arguments. Default to `False`.
"""
if reconverge is None:
reconverge = False
if ic is None:
if self.n_dim is not None:
i = self.n_dim
else:
i = 1
while True:
self.ic = np.zeros(i)
try:
x = self.func(0., self.ic)
except:
i += 1
else:
break
i = len(self.func(0., self.ic))
if number_of_trajectories > self.num_threads:
reconverge = True
tmp_ic = np.zeros((number_of_trajectories, i))
tmp_ic[:self.num_threads] = np.random.randn(self.num_threads, i)
else:
tmp_ic = np.random.randn(number_of_trajectories, i)
else:
tmp_ic = ic.copy()
if len(tmp_ic.shape) > 1:
number_of_trajectories = tmp_ic.shape[0]
if reconverge and reconvergence_time is not None:
self.integrate(0., convergence_time, dt, ic=tmp_ic[:self.num_threads], write_steps=0, forward=forward)
t, x = self.get_trajectories()
tmp_ic[:self.num_threads] = x
if number_of_trajectories - self.num_threads > self.num_threads:
next_len = self.num_threads
else:
next_len = number_of_trajectories - self.num_threads
index = self.num_threads
while True:
perturbation = pert_size * np.random.randn(next_len, x.shape[1])
self.integrate(0., reconvergence_time, dt, ic=x[:next_len]+perturbation, write_steps=0, forward=forward)
t, x = self.get_trajectories()
tmp_ic[index:index+next_len] = x
index += next_len
if number_of_trajectories - index > self.num_threads:
next_len = self.num_threads
else:
next_len = number_of_trajectories - index
if next_len <= 0:
break
self.ic = tmp_ic
else:
self.integrate(0., convergence_time, dt, ic=tmp_ic, write_steps=0, forward=forward)
t, x = self.get_trajectories()
self.ic = x
def integrate(self, t0, t, dt, ic=None, forward=True, write_steps=1):
"""Integrate the ordinary differential equations (ODEs)
.. math:: \dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})
with a specified `Runge-Kutta method`_ and workers. The function :math:`\\boldsymbol{f}` is the `Numba`_ jitted
function stored in :attr:`func`. The result of the integration can be obtained afterward by calling
:meth:`get_trajectories`.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
.. _Numba: https://numba.pydata.org/
Parameters
----------
t0: float
Initial time of the time integration. Corresponds to the initial condition's `ic` time.
Important if the ODEs are non-autonomous.
t: float
Final time of the time integration. Corresponds to the final condition.
Important if the ODEs are non-autonomous.
dt: float
Timestep of the integration.
ic: None or ~numpy.ndarray(float), optional
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
If `None`, use the initial conditions stored in :attr:`ic`.
If then :attr:`ic` is `None`, use a zero initial condition.
Default to `None`.
forward: bool, optional
Whether to integrate the ODEs forward or backward in time. In case of backward integration, the
initial condition `ic` becomes a final condition. Default to forward integration.
write_steps: int, optional
Save the state of the integration in memory every `write_steps` steps. The other intermediary
steps are lost. It determine the size of the returned objects. Default is 1.
Set to 0 to return only the final state.
"""
if self.func is None:
print('No function to integrate defined!')
return 0
if ic is None:
if self.ic is None:
if self.n_dim is not None:
i = self.n_dim
else:
i = 1
while True:
self.ic = np.zeros(i)
try:
x = self.func(0., self.ic)
except:
i += 1
else:
break
i = len(self.func(0., self.ic))
self.ic = np.zeros(i)
else:
self.ic = ic
if len(self.ic.shape) == 1:
self.ic = self.ic.reshape((1, -1))
self.n_traj = self.ic.shape[0]
self.n_dim = self.ic.shape[1]
self.time = np.concatenate((np.arange(t0, t, dt), np.full((1,), t)))
self._write_steps = write_steps
if forward:
self._time_direction = 1
else:
self._time_direction = -1
if write_steps == 0:
self.n_records = 1
else:
tot = self.time[::self._write_steps]
self.n_records = len(tot)
if tot[-1] != self.time[-1]:
self.n_records += 1
self.recorded_traj = np.zeros((self.n_traj, self.n_dim, self.n_records))
for i in range(self.n_traj):
self._ics_queue.put((i, self.time, self.ic[i], self._time_direction, self._write_steps))
self._ics_queue.join()
for i in range(self.n_traj):
args = self._traj_queue.get()
self.recorded_traj[args[0]] = args[1]
def get_trajectories(self):
"""Returns the result of the previous integrator integration.
Returns
-------
time, traj: ~numpy.ndarray
The result of the integration:
* `time` is the time at which the state of the system was saved. Array of shape (:attr:`n_records`,).
* `traj` are the saved states. 3D array of shape (:attr:`n_traj`, :attr:`n_dim`, :attr:`n_records`).
If :attr:`n_traj` = 1, a 2D array of shape (:attr:`n_dim`, :attr:`n_steps`) is returned instead.
"""
if self._write_steps > 0:
if self._time_direction == 1:
if self.time[::self._write_steps][-1] == self.time[-1]:
return self.time[::self._write_steps], np.squeeze(self.recorded_traj)
else:
return np.concatenate((self.time[::self._write_steps], np.full((1,), self.time[-1]))), \
np.squeeze(self.recorded_traj)
else:
rtime = reverse(self.time[::-self._write_steps])
if rtime[0] == self.time[0]:
return rtime, np.squeeze(self.recorded_traj)
else:
return np.concatenate((np.full((1,), self.time[0]), rtime)), np.squeeze(self.recorded_traj)
else:
return self.time[-1], np.squeeze(self.recorded_traj)
def get_ic(self):
"""Returns the initial conditions stored in the integrator.
Returns
-------
~numpy.ndarray
The initial conditions.
"""
return self.ic
def set_ic(self, ic):
"""Direct setter for the integrator's initial conditions
Parameters
----------
ic: ~numpy.ndarray(float)
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
"""
self.ic = ic
class TrajectoryProcess(multiprocessing.Process):
""":class:`RungeKuttaIntegrator`'s workers class. Allows to multi-thread time integration.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
.. _Numba: https://numba.pydata.org/
Parameters
----------
processID: int
Number identifying the worker.
func: callable
`Numba`_-jitted function to integrate assigned to the worker.
b: ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
ics_queue: multiprocessing.JoinableQueue
Queue to which the worker ask for initial conditions input.
traj_queue: multiprocessing.Queue
Queue to which the worker returns the integration results.
Attributes
----------
processID: int
Number identifying the worker.
func: callable
`Numba`_-jitted function to integrate assigned to the worker.
b: ~numpy.ndarray
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: ~numpy.ndarray
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
ics_queue: multiprocessing.JoinableQueue
Queue to which the worker ask for initial conditions input.
traj_queue: multiprocessing.Queue
Queue to which the worker returns the integration results.
"""
def __init__(self, processID, func, b, c, a, ics_queue, traj_queue):
super().__init__()
self.processID = processID
self.ics_queue = ics_queue
self.traj_queue = traj_queue
self.func = func
self.a = a
self.b = b
self.c = c
def run(self):
"""Main worker computing routine. Perform the time integration with the fetched initial conditons."""
while True:
args = self.ics_queue.get()
recorded_traj = _integrate_runge_kutta_jit(self.func, args[1], args[2][np.newaxis, :], args[3], args[4],
self.b, self.c, self.a)
self.traj_queue.put((args[0], recorded_traj))
self.ics_queue.task_done()
class RungeKuttaTglsIntegrator(object):
"""Class to integrate simultaneously the ordinary differential equations (ODEs)
.. math:: \dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})
and its tangent linear model, i.e. the linearized ODEs
.. math :: \dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}
where :math:`\\boldsymbol{\mathrm{J}} = \\frac{\partial \\boldsymbol{f}}{\partial \\boldsymbol{x}}` is the
Jacobian matrix of :math:`\\boldsymbol{f}`, with a specified `Runge-Kutta method`_.
To solve this equation, one has to integrate simultaneously both ODEs. This class does so with a set
of :class:`TglsTrajectoryProcess` workers.
The function :math:`\\boldsymbol{f}` and :math:`\\boldsymbol{J}` should
be `Numba`_ jitted functions. These functions must have a signature ``f(t, x)`` and ``J(t, x)`` where ``x`` is
the state value and ``t`` is the time.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
.. _Numba: https://numba.pydata.org/
.. _fundamental matrix of solutions: https://en.wikipedia.org/wiki/Fundamental_matrix_(linear_differential_equation)
Parameters
----------
num_threads: None or int, optional
Number of :class:`TrajectoryProcess` workers (threads) to use. If `None`, use the number of machine's
cores available. Default to `None`.
b: None or ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
c: None or ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
a: None or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
If `None`, use the classic RK4 method coefficients. Default to `None`.
number_of_dimensions: None or int, optional
Allow to hardcode the dynamical system dimension. If `None`, evaluate the dimension from the
callable :attr:`func`. Default to `None`.
Attributes
----------
num_threads: int
Number of :class:`TrajectoryProcess` workers (threads) to use.
b: ~numpy.ndarray
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: ~numpy.ndarray
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
n_dim: int
Dynamical system dimension.
n_traj: int
The number of trajectories (initial conditions) of the non-linear ODEs computed at the last integration
performed by the integrator.
n_tgtraj: int
The number of trajectories (initial conditions) the linear ODEs computed at the last integration
performed by the integrator.
n_records: int
The number of saved states of the last integration performed by the integrator.
ic: ~numpy.ndarray
Store the integrator non-linear ODEs initial conditions.
tg_ic: ~numpy.ndarray
Store the integrator linear ODEs initial conditions.
time: ~numpy.ndarray
The time at which the state of the system was saved. Array of shape (`n_records`,).
recorded_traj: ~numpy.ndarray
Saved states of the ODEs. 3D array of shape (:attr:`n_traj`, :attr:`n_dim`, :attr:`n_records`).
recorded_fmatrix: ~numpy.ndarray
Saved states of the linear ODEs. 4D array of shape (:attr:`n_traj`, :attr:`n_tg_traj`, :attr:`n_dim`, :attr:`n_records`).
func: callable
Last function :math:`\\boldsymbol{f}` used by the integrator to integrate.
func_jac: callable
Last Jacobian matrix function :math:`\\boldsymbol{J}` used by the integrator to integrate.
"""
def __init__(self, num_threads=None, b=None, c=None, a=None, number_of_dimensions=None):
if num_threads is None:
self.num_threads = multiprocessing.cpu_count()
else:
self.num_threads = num_threads
# Default is RK4
if a is None and b is None and c is None:
self.c = np.array([0., 0.5, 0.5, 1.])
self.b = np.array([1./6, 1./3, 1./3, 1./6])
self.a = np.zeros((len(self.c), len(self.b)))
self.a[1, 0] = 0.5
self.a[2, 1] = 0.5
self.a[3, 2] = 1.
else:
self.a = a
self.b = b
self.c = c
self.ic = None
self.tg_ic = None
self.time = None
self.recorded_traj = None
self.recorded_fmatrix = None
self.n_traj = 0
self.n_tgtraj = 0
self.n_dim = number_of_dimensions
self.n_records = 0
self._write_steps = 0
self._time_direction = 1
self._adjoint = False
self._boundary = None
self._inverse = 1.
self.func = None
self.func_jac = None
self._ics_queue = None
self._traj_queue = None
self._processes_list = list()
def terminate(self):
"""Stop the workers (threads) and release the resources of the integrator."""
for process in self._processes_list:
process.terminate()
process.join()
def start(self):
"""Start or restart the workers (threads) of the integrator.
Warnings
--------
If the integrator was not previously terminated, it will be terminated first in the case
of a restart.
"""
self.terminate()
self._processes_list = list()
self._ics_queue = multiprocessing.JoinableQueue()
self._traj_queue = multiprocessing.Queue()
for i in range(self.num_threads):
self._processes_list.append(TglsTrajectoryProcess(i, self.func, self.func_jac, self.b, self.c, self.a,
self._ics_queue, self._traj_queue))
for process in self._processes_list:
process.daemon = True
process.start()
def set_func(self, f, fjac, ic_init=True):
"""Set the `Numba`_-jitted function :math:`\\boldsymbol{f}` and Jacobian matrix function
:math:`\\boldsymbol{\mathrm{J}}` to integrate.
.. _Numba: https://numba.pydata.org/
Parameters
----------
f: callable
The `Numba`_-jitted function :math:`\\boldsymbol{f}`.
Should have the signature ``f(t, x)`` where ``x`` is the state value and ``t`` is the time.
fjac: callable
The `Numba`_-jitted Jacobian matrix function :math:`\\boldsymbol{J}`.
Should have the signature ``J(t, x)`` where ``x`` is the state value and ``t`` is the time.
ic_init: bool, optional
Re-initialize or not the initial conditions of the integrator. Default to `True`.
Warnings
--------
This function restarts the integrator!
"""
self.func = f
self.func_jac = fjac
if ic_init:
self.ic = None
self.start()
def set_bca(self, b=None, c=None, a=None, ic_init=True):
"""Set the coefficients of the `Runge-Kutta method`_ and restart the integrator. s
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
Parameters
----------
b: None or ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
c: None or ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
a: None or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
If `None`, does not reinitialize these coefficients.
ic_init: bool, optional
Re-initialize or not the initial conditions of the integrator. Default to `True`.
"""
if a is not None:
self.a = a
if b is not None:
self.b = b
if c is not None:
self.c = c
if ic_init:
self.ic = None
self.start()
def initialize(self, convergence_time, dt, pert_size=0.01, reconvergence_time=None, forward=True,
number_of_trajectories=1, ic=None, reconverge=None):
"""Initialize the integration on an attractor by running it for a transient time,
For an ensemble of initial conditions, can do the same transient time for each, or the
`convergence_time` for the first one, and a smaller `reconvergence_time` for the subsequent ones.
This results into initial conditions on the attractor, stored in :attr:`ic`.
Parameters
----------
convergence_time: float
Transient time needed to converge to the attractor.
dt: float
Timestep of the transient integration.
pert_size:float, optional
If the reconvergence is activated, size of the perturbation to add to the previous ic to find
the next one. Default to 0.01 .
reconvergence_time: None or float, optional
Transient time for the subsequent trajectories after the first long `transient_time`.
forward: bool, optional
If true, integrate the ODEs forward in time, else, integrate backward in time. In case of backward integration, the
initial condition `ic` becomes a final condition. Default to forward integration.
number_of_trajectories: int
Number of initial conditions to find. Default to 1. Inactive if `ic` is provided.
ic: None or ~numpy.ndarray(float), optional
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
If `None`, use `number_trajectories` random initial conditions. Default to `None`.
reconverge: bool
Use or not the smaller transient time reconvergence with a perturbation
after the first initial conditions have been computed. If activated, only use the :attr:`num_threads`
first initial conditions of the `ic` arguments. Default to `False`.
"""
if reconverge is None:
reconverge = False
if ic is None:
if self.n_dim is not None:
i = self.n_dim
else:
i = 1
while True:
self.ic = np.zeros(i)
try:
x = self.func(0., self.ic)
except:
i += 1
else:
break
i = len(self.func(0., self.ic))
if number_of_trajectories > self.num_threads:
reconverge = True
tmp_ic = np.zeros((number_of_trajectories, i))
tmp_ic[:self.num_threads] = np.random.randn(self.num_threads, i)
else:
tmp_ic = np.random.randn(number_of_trajectories, i)
else:
tmp_ic = ic.copy()
if len(tmp_ic.shape) > 1:
number_of_trajectories = tmp_ic.shape[0]
if reconverge and reconvergence_time is not None:
self.integrate(0., convergence_time, dt, ic=tmp_ic[:self.num_threads], write_steps=0, forward=forward)
t, x, fm = self.get_trajectories()
tmp_ic[:self.num_threads] = x
if number_of_trajectories - self.num_threads > self.num_threads:
next_len = self.num_threads
else:
next_len = number_of_trajectories - self.num_threads
index = self.num_threads
while True:
perturbation = pert_size * np.random.randn(next_len, x.shape[1])
self.integrate(0., reconvergence_time, dt, ic=x[:next_len]+perturbation, write_steps=0, forward=forward)
t, x, fm = self.get_trajectories()
tmp_ic[index:index+next_len] = x
index += next_len
if number_of_trajectories - index > self.num_threads:
next_len = self.num_threads
else:
next_len = number_of_trajectories - index
if next_len <= 0:
break
self.ic = tmp_ic
else:
self.integrate(0., convergence_time, dt, ic=tmp_ic, write_steps=0, forward=forward)
t, x, fm = self.get_trajectories()
self.ic = x
def integrate(self, t0, t, dt, ic=None, tg_ic=None, forward=True, adjoint=False, inverse=False, boundary=None,
write_steps=1):
"""Integrate simultaneously the non-linear and linearized ordinary differential equations (ODEs)
.. math:: \dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})
and
.. math :: \dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}
with a specified `Runge-Kutta method`_ and workers.
The function :math:`\\boldsymbol{f}` is the `Numba`_ jitted function stored in :attr:`func`.
The function :math:`\\boldsymbol{J}` is the `Numba`_ jitted function stored in :attr:`func_jac`.
The result of the integration can be obtained afterward by calling :meth:`get_trajectories`.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
.. _Numba: https://numba.pydata.org/
.. _fundamental matrix of solutions: https://en.wikipedia.org/wiki/Fundamental_matrix_(linear_differential_equation)
Parameters
----------
t0: float
Initial time of the time integration. Corresponds to the initial condition's `ic` time.
Important if the ODEs are non-autonomous.
t: float
Final time of the time integration. Corresponds to the final condition.
Important if the ODEs are non-autonomous.
dt: float
Timestep of the integration.
ic: None or ~numpy.ndarray(float), optional
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
If `None`, use the initial conditions stored in :attr:`ic`.
If then :attr:`ic` is `None`, use a zero initial condition.
Default to `None`.
tg_ic: None or ~numpy.ndarray(float), optional
Initial condition of the linear ODEs
:math:`\dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}`. \n
Can be a 1D, a 2D or a 3D array:
* 1D: Provide a single initial condition. This initial condition of the linear ODEs will be the same used for each
initial condition `ic` of the ODEs :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Two sub-cases:
+ If `tg_ic.shape[0]`=`ic.shape[0]`, assumes that each initial condition `ic[i]` of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`,
correspond to a different initial condition `tg_ic[i]`.
+ Else, assumes and integrate an ensemble of `n_tg_traj` initial condition of the linear ODEs for each
initial condition of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`.
* 3D: An array of shape (`n_traj`, `n_tg_traj`, `n_dim`) which provide an ensemble of `n_tg_ic` initial conditions
specific to each of the `n_traj` initial conditions of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`.
If `None`, use the identity matrix as initial condition, returning the `fundamental matrix of solutions`_ of the
linear ODEs.
Default to `None`.
forward: bool, optional
If true, integrate the ODEs forward in time, else, integrate backward in time. In case of backward integration, the
initial condition `ic` becomes a final condition. Default to forward integration.
adjoint: bool, optional
If true, integrate the tangent :math:`\dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}` ,
else, integrate the adjoint linear model :math:`\dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}^T(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}`.
Integrate the tangent model by default.
inverse: bool, optional
Wheter or not to invert the Jacobian matrix
:math:`\\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \\rightarrow \\boldsymbol{\mathrm{J}}^{-1}(t, \\boldsymbol{x})`.
`False` by default.
boundary: None or callable, optional
Allow to add a inhomogeneous term to linear ODEs:
:math:`\dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x} + \Psi(t, \\boldsymbol{x})`.
The boundary :math:`\Psi` should have the same signature as :math:`\\boldsymbol{\mathrm{J}}`, i.e. ``func(t, x)``.
If `None`, don't add anything (homogeneous case). `None` by default.
write_steps: int, optional
Save the state of the integration in memory every `write_steps` steps. The other intermediary
steps are lost. It determine the size of the returned objects. Default is 1.
Set to 0 to return only the final state.
"""
if self.func is None or self.func_jac is None:
print('No function to integrate defined!')
return 0
if ic is None:
if self.ic is None:
if self.n_dim is not None:
i = self.n_dim
else:
i = 1
while True:
self.ic = np.zeros(i)
try:
x = self.func(0., self.ic)
except:
i += 1
else:
break
i = len(self.func(0., self.ic))
self.ic = np.zeros(i)
else:
self.ic = ic
if len(self.ic.shape) == 1:
self.ic = self.ic.reshape((1, -1))
self.n_traj = self.ic.shape[0]
self.n_dim = self.ic.shape[1]
self.time = np.concatenate((np.arange(t0, t, dt), np.full((1,), t)))
self._write_steps = write_steps
if tg_ic is None:
tg_ic = np.eye(self.ic.shape[1])
tg_ic_sav = tg_ic.copy()
if len(tg_ic.shape) == 1:
tg_ic = tg_ic.reshape((1, -1, 1))
ict = tg_ic.copy()
for i in range(self.n_traj-1):
ict = np.concatenate((ict, tg_ic))
self.tg_ic = ict
elif len(tg_ic.shape) == 2:
if tg_ic.shape[0] == self.n_traj:
self.tg_ic = tg_ic[..., np.newaxis]
else:
tg_ic = tg_ic[np.newaxis, ...]
tg_ic = np.swapaxes(tg_ic, 1, 2)
ict = tg_ic.copy()
for i in range(self.n_traj-1):
ict = np.concatenate((ict, tg_ic))
self.tg_ic = ict
elif len(tg_ic.shape) == 3:
if tg_ic.shape[1] != self.n_dim:
self.tg_ic = np.swapaxes(tg_ic, 1, 2)
if forward:
self._time_direction = 1
else:
self._time_direction = -1
self._adjoint = adjoint
if boundary is None:
self._boundary = _zeros_func
else:
self._boundary = boundary
self._inverse = 1.
if inverse:
self._inverse *= -1.
if write_steps == 0:
self.n_records = 1
else:
tot = self.time[::self._write_steps]
self.n_records = len(tot)
if tot[-1] != self.time[-1]:
self.n_records += 1
self.recorded_traj = np.zeros((self.n_traj, self.n_dim, self.n_records))
self.recorded_fmatrix = np.zeros((self.n_traj, self.tg_ic.shape[1], self.tg_ic.shape[2], self.n_records))
for i in range(self.n_traj):
self._ics_queue.put((i, self.time, self.ic[i], self.tg_ic[i], self._time_direction, self._write_steps,
self._adjoint, self._inverse, self._boundary))
self._ics_queue.join()
for i in range(self.n_traj):
args = self._traj_queue.get()
self.recorded_traj[args[0]] = args[1]
self.recorded_fmatrix[args[0]] = args[2]
if len(tg_ic_sav.shape) == 2:
if self.recorded_fmatrix.shape[1:3] != tg_ic_sav.shape:
self.recorded_fmatrix = np.swapaxes(self.recorded_fmatrix, 1, 2)
elif len(tg_ic_sav.shape) == 3:
if tg_ic_sav.shape[1] != self.n_dim:
if self.recorded_fmatrix.shape[:3] != tg_ic_sav.shape:
self.recorded_fmatrix = np.swapaxes(self.recorded_fmatrix, 1, 2)
def get_trajectories(self):
"""Returns the result of the previous integrator integration.
Returns
-------
time, traj, tg_traj: ~numpy.ndarray
The result of the integration:
* `time` is the time at which the state of the system was saved. Array of shape (:attr:`n_records`,).
* `traj` are the saved states. 3D array of shape (:attr:`n_traj`, :attr:`n_dim`, :attr:`n_records`).
If :attr:`n_traj` = 1, a 2D array of shape (:attr:`n_dim`, :attr:`n_steps`) is returned instead.
* `tg_traj` are the saved states of the linear ODEs.
Depending on the input initial conditions of both ODEs,
it is at maximum a 4D array of shape
(:attr:`n_traj`, :attr:`n_tg_traj`, :attr:`n_dim`, :attr:`n_records`).
If one of the dimension is 1, it is squeezed.
"""
if self._write_steps > 0:
if self._time_direction == 1:
if self.time[::self._write_steps][-1] == self.time[-1]:
return self.time[::self._write_steps], np.squeeze(self.recorded_traj), \
np.squeeze(self.recorded_fmatrix)
else:
return np.concatenate((self.time[::self._write_steps], np.full((1,), self.time[-1]))), \
np.squeeze(self.recorded_traj), np.squeeze(self.recorded_fmatrix)
else:
rtime = reverse(self.time[::-self._write_steps])
if rtime[0] == self.time[0]:
return rtime, np.squeeze(self.recorded_traj), np.squeeze(self.recorded_fmatrix)
else:
return np.concatenate((np.full((1,), self.time[0]), rtime)), np.squeeze(self.recorded_traj),\
np.squeeze(self.recorded_fmatrix)
else:
return self.time[-1], np.squeeze(self.recorded_traj), np.squeeze(self.recorded_fmatrix)
def get_ic(self):
"""Returns the initial conditions of the non-linear ODEs stored in the integrator.
Returns
-------
~numpy.ndarray
The initial conditions.
"""
return self.ic
def set_ic(self, ic):
"""Direct setter for the integrator's non-linear ODEs initial conditions
Parameters
----------
ic: ~numpy.ndarray(float)
Initial condition of the system. Can be a 1D or a 2D array:
* 1D: Provide a single initial condition.
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Provide an ensemble of initial condition.
Should be of shape (`n_traj`, `n_dim`) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`,
and where `n_traj` is the number of initial conditions.
"""
self.ic = ic
def get_tg_ic(self):
"""Returns the initial conditions of the linear ODEs stored in the integrator.
Returns
-------
~numpy.ndarray
The initial conditions.
"""
return self.tg_ic
def set_tg_ic(self, tg_ic):
"""Direct setter for the integrator's linear ODEs initial conditions
Parameters
----------
tg_ic: ~numpy.ndarray(float)
Initial condition of the linear ODEs
:math:`\dot{\\boldsymbol{\delta x}} = \\boldsymbol{\mathrm{J}}(t, \\boldsymbol{x}) \cdot \\boldsymbol{\delta x}`. \n
Can be a 1D, a 2D or a 3D array:
* 1D: Provide a single initial condition. This initial condition of the linear ODEs will be the same used for each
initial condition `ic` of the ODEs :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`
Should be of shape (`n_dim`,) where `n_dim` = :math:`\mathrm{dim}(\\boldsymbol{x})`.
* 2D: Two sub-cases:
+ If `tg_ic.shape[0]`=`ic.shape[0]`, assumes that each initial condition `ic[i]` of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`,
correspond to a different initial condition `tg_ic[i]`.
+ Else, assumes and integrate an ensemble of `n_tg_traj` initial condition of the linear ODEs for each
initial condition of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`.
* 3D: An array of shape (`n_traj`, `n_tg_traj`, `n_dim`) which provide an ensemble of `n_tg_ic` initial conditions
specific to each of the `n_traj` initial conditions of :math:`\dot{\\boldsymbol{x}} = \\boldsymbol{f}(t, \\boldsymbol{x})`.
"""
self.tg_ic = tg_ic
class TglsTrajectoryProcess(multiprocessing.Process):
""":class:`RungeKuttaTglsIntegrator`'s workers class. Allows to multi-thread time integration.
.. _Runge-Kutta method: https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
.. _Numba: https://numba.pydata.org/
Parameters
----------
processID: int
Number identifying the worker.
func: callable
`Numba`_-jitted function to integrate assigned to the worker.
b: ~numpy.ndarray, optional
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray, optional
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: or ~numpy.ndarray, optional
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
ics_queue: multiprocessing.JoinableQueue
Queue to which the worker ask for initial conditions input.
traj_queue: multiprocessing.Queue
Queue to which the worker returns the integration results.
Attributes
----------
processID: int
Number identifying the worker.
func: callable
`Numba`_-jitted function to integrate assigned to the worker.
func_jac: callable
`Numba`_-jitted Jacobian matrix function to integrate assigned to the worker.
b: ~numpy.ndarray
Vector of coefficients :math:`b_i` of the `Runge-Kutta method`_ .
c: ~numpy.ndarray
Matrix of coefficients :math:`c_{i,j}` of the `Runge-Kutta method`_ .
a: ~numpy.ndarray
Vector of coefficients :math:`a_i` of the `Runge-Kutta method`_ .
ics_queue: multiprocessing.JoinableQueue
Queue to which the worker ask for initial conditions input.
traj_queue: multiprocessing.Queue
Queue to which the worker returns the integration results.
"""
def __init__(self, processID, func, func_jac, b, c, a, ics_queue, traj_queue):
super().__init__()
self.processID = processID
self.ics_queue = ics_queue
self.traj_queue = traj_queue
self.func = func
self.func_jac = func_jac
self.a = a
self.b = b
self.c = c
def run(self):
"""Main worker computing routine. Perform the time integration with the fetched initial conditons."""
while True:
args = self.ics_queue.get()
recorded_traj, recorded_fmatrix = _integrate_runge_kutta_tgls_jit(self.func, self.func_jac, args[1], args[2][np.newaxis, ...],
args[3][np.newaxis, ...], args[4], args[5],
self.b, self.c, self.a,
args[6], args[7], args[8])
self.traj_queue.put((args[0], recorded_traj, recorded_fmatrix))
self.ics_queue.task_done()
if __name__ == "__main__":
import matplotlib.pyplot as plt
from scipy.integrate import odeint
@njit
def f(t, x):
return - np.array([1., 2., 3.]) * x
def fr(x, t):
return f(t, x)
ic = np.random.randn(6).reshape(2, 3)
integrator = RungeKuttaIntegrator()
integrator.set_func(f)
integrator.integrate(0., 10., 0.01, ic=ic, write_steps=1)
time, r = integrator.get_trajectories()
t = np.arange(0., 10., 0.1)
t = np.concatenate((t[::3], np.full((1,), 10.)))
rl = list()
for i in range(ic.shape[0]):
rl.append(odeint(fr, ic[i], t).T)
plt.figure()
for i in range(ic.shape[0]):
p, = plt.plot(time, r[i, 0])
c = p.get_color()
plt.plot(t, rl[i][0], color=c, ls='--')
for j in range(1, ic.shape[1]):
p, = plt.plot(time, r[i, j], color=c)
plt.plot(t, rl[i][j], color=c, ls='--')
plt.title('Forward')
integrator.integrate(0., 10., 0.01, ic=ic, forward=False, write_steps=1)
timet, rt = integrator.get_trajectories()
rlt = list()
for i in range(ic.shape[0]):
rlt.append(odeint(fr, ic[i], reverse(t)).T)
plt.figure()
for i in range(ic.shape[0]):
p, = plt.plot(timet, rt[i, 0])
c = p.get_color()
plt.plot(t, reverse(rlt[i][0]), color=c, ls='--')
for j in range(1, ic.shape[1]):
p, = plt.plot(timet, rt[i, j], color=c)
plt.plot(t, reverse(rlt[i][j]), color=c, ls='--')
plt.title('Backward')
integrator.integrate(0., 10., 0.01, ic=ic, write_steps=0)
tt, re = integrator.get_trajectories()
print(tt)
print(r[0, :, -1], re[0])
plt.show(block=False)
a = 0.25
F = 16.
G = 3.
b = 6.
@njit
def fL84(t, x):
xx = -x[1] ** 2 - x[2] ** 2 - a * x[0] + a * F
yy = x[0] * x[1] - b * x[0] * x[2] - x[1] + G
zz = b * x[0] * x[1] + x[0] * x[2] - x[2]
return np.array([xx, yy, zz])
@njit
def DfL84(t, x):
return np.array([[ -a , -2. * x[1], -2. * x[2]],
[x[1] - b * x[2], -1. + x[0], -b * x[0]],
[b * x[1] + x[2], b * x[0], -1. + x[0]]])
integrator.set_func(fL84)
integrator.integrate(0., 10000., 0.01, write_steps=0)
tt, traj = integrator.get_trajectories()
integrator.integrate(0.,20.,0.01,ic=traj, write_steps=10)
tt, traj = integrator.get_trajectories()
integrator.integrate(0.,20.,0.01,ic=traj[:,-1],write_steps=10, forward=False)
ttb, trajb = integrator.get_trajectories()
plt.figure()
plt.plot(tt, traj[0])
plt.plot(ttb, trajb[0])
plt.show(block=False)
plt.title('Lorenz 63 - Forward then backward')
integrator.integrate(0., 10000., 0.01, write_steps=0)
tt, traj = integrator.get_trajectories()
integrator.integrate(0.,20.,0.01,ic=traj,write_steps=10, forward=False)
tt, trajb = integrator.get_trajectories()
integrator.integrate(0.,20.,0.01,ic=trajb[:,0],write_steps=10)
ttb, traj = integrator.get_trajectories()
plt.figure()
plt.plot(tt, traj[0])
plt.plot(ttb, trajb[0])
plt.show(block=False)
plt.title('Lorenz 63 - Backward then forward')
integrator.terminate()
tgls_integrator = RungeKuttaTglsIntegrator()
tgls_integrator.set_func(fL84, DfL84)
@njit
def tboundary(t, x):
return np.array([0.,x[1],0.])
ic = np.random.randn(4, 3)
tgls_integrator.initialize(10., 0.01, ic=ic)
tgls_integrator.integrate(0., 20., 0.01, write_steps=10, tg_ic=np.zeros(3), boundary=tboundary)
# x, fm = _integrate_runge_kutta_tgls_jit(fL84, DfL84, tgls_integrator.time, tgls_integrator.ic[0][np .newaxis,...], np.zeros((1,3,1)), 1, 1, tgls_integrator.b, tgls_integrator.c, tgls_integrator.a, False, 1., tboundary)
t, x, fm = tgls_integrator.get_trajectories()
tgls_integrator.terminate()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"numpy.arange",
"multiprocessing.Queue",
"integrators.integrate._integrate_runge_kutta_jit",
"multiprocessing.cpu_count",
"numpy.full",
"functions.util.reverse",
"numpy.random.randn",
"scipy.integrate.odeint",
"numpy.swapaxes",
"multiproce... | [((50697, 50722), 'numpy.arange', 'np.arange', (['(0.0)', '(10.0)', '(0.1)'], {}), '(0.0, 10.0, 0.1)\n', (50706, 50722), True, 'import numpy as np\n'), ((50870, 50882), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (50880, 50882), True, 'import matplotlib.pyplot as plt\n'), ((51173, 51193), 'matplotlib.pyplot.title', 'plt.title', (['"""Forward"""'], {}), "('Forward')\n", (51182, 51193), True, 'import matplotlib.pyplot as plt\n'), ((51425, 51437), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (51435, 51437), True, 'import matplotlib.pyplot as plt\n'), ((51752, 51773), 'matplotlib.pyplot.title', 'plt.title', (['"""Backward"""'], {}), "('Backward')\n", (51761, 51773), True, 'import matplotlib.pyplot as plt\n'), ((51928, 51949), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (51936, 51949), True, 'import matplotlib.pyplot as plt\n'), ((52839, 52851), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (52849, 52851), True, 'import matplotlib.pyplot as plt\n'), ((52856, 52877), 'matplotlib.pyplot.plot', 'plt.plot', (['tt', 'traj[0]'], {}), '(tt, traj[0])\n', (52864, 52877), True, 'import matplotlib.pyplot as plt\n'), ((52882, 52905), 'matplotlib.pyplot.plot', 'plt.plot', (['ttb', 'trajb[0]'], {}), '(ttb, trajb[0])\n', (52890, 52905), True, 'import matplotlib.pyplot as plt\n'), ((52910, 52931), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (52918, 52931), True, 'import matplotlib.pyplot as plt\n'), ((52937, 52983), 'matplotlib.pyplot.title', 'plt.title', (['"""Lorenz 63 - Forward then backward"""'], {}), "('Lorenz 63 - Forward then backward')\n", (52946, 52983), True, 'import matplotlib.pyplot as plt\n'), ((53328, 53340), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (53338, 53340), True, 'import matplotlib.pyplot as plt\n'), ((53345, 53366), 'matplotlib.pyplot.plot', 'plt.plot', (['tt', 'traj[0]'], {}), '(tt, traj[0])\n', (53353, 53366), True, 'import matplotlib.pyplot as plt\n'), ((53371, 53394), 'matplotlib.pyplot.plot', 'plt.plot', (['ttb', 'trajb[0]'], {}), '(ttb, trajb[0])\n', (53379, 53394), True, 'import matplotlib.pyplot as plt\n'), ((53399, 53420), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (53407, 53420), True, 'import matplotlib.pyplot as plt\n'), ((53426, 53472), 'matplotlib.pyplot.title', 'plt.title', (['"""Lorenz 63 - Backward then forward"""'], {}), "('Lorenz 63 - Backward then forward')\n", (53435, 53472), True, 'import matplotlib.pyplot as plt\n'), ((53676, 53697), 'numpy.random.randn', 'np.random.randn', (['(4)', '(3)'], {}), '(4, 3)\n', (53691, 53697), True, 'import numpy as np\n'), ((4702, 4733), 'multiprocessing.JoinableQueue', 'multiprocessing.JoinableQueue', ([], {}), '()\n', (4731, 4733), False, 'import multiprocessing\n'), ((4761, 4784), 'multiprocessing.Queue', 'multiprocessing.Queue', ([], {}), '()\n', (4782, 4784), False, 'import multiprocessing\n'), ((15355, 15406), 'numpy.zeros', 'np.zeros', (['(self.n_traj, self.n_dim, self.n_records)'], {}), '((self.n_traj, self.n_dim, self.n_records))\n', (15363, 15406), True, 'import numpy as np\n'), ((26205, 26236), 'multiprocessing.JoinableQueue', 'multiprocessing.JoinableQueue', ([], {}), '()\n', (26234, 26236), False, 'import multiprocessing\n'), ((26264, 26287), 'multiprocessing.Queue', 'multiprocessing.Queue', ([], {}), '()\n', (26285, 26287), False, 'import multiprocessing\n'), ((41589, 41640), 'numpy.zeros', 'np.zeros', (['(self.n_traj, self.n_dim, self.n_records)'], {}), '((self.n_traj, self.n_dim, self.n_records))\n', (41597, 41640), True, 'import numpy as np\n'), ((41673, 41759), 'numpy.zeros', 'np.zeros', (['(self.n_traj, self.tg_ic.shape[1], self.tg_ic.shape[2], self.n_records)'], {}), '((self.n_traj, self.tg_ic.shape[1], self.tg_ic.shape[2], self.\n n_records))\n', (41681, 41759), True, 'import numpy as np\n'), ((50929, 50952), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'r[i, 0]'], {}), '(time, r[i, 0])\n', (50937, 50952), True, 'import matplotlib.pyplot as plt\n'), ((50987, 51026), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'rl[i][0]'], {'color': 'c', 'ls': '"""--"""'}), "(t, rl[i][0], color=c, ls='--')\n", (50995, 51026), True, 'import matplotlib.pyplot as plt\n'), ((51484, 51509), 'matplotlib.pyplot.plot', 'plt.plot', (['timet', 'rt[i, 0]'], {}), '(timet, rt[i, 0])\n', (51492, 51509), True, 'import matplotlib.pyplot as plt\n'), ((52204, 52226), 'numpy.array', 'np.array', (['[xx, yy, zz]'], {}), '([xx, yy, zz])\n', (52212, 52226), True, 'import numpy as np\n'), ((52275, 52406), 'numpy.array', 'np.array', (['[[-a, -2.0 * x[1], -2.0 * x[2]], [x[1] - b * x[2], -1.0 + x[0], -b * x[0]],\n [b * x[1] + x[2], b * x[0], -1.0 + x[0]]]'], {}), '([[-a, -2.0 * x[1], -2.0 * x[2]], [x[1] - b * x[2], -1.0 + x[0], -b *\n x[0]], [b * x[1] + x[2], b * x[0], -1.0 + x[0]]])\n', (52283, 52406), True, 'import numpy as np\n'), ((53643, 53669), 'numpy.array', 'np.array', (['[0.0, x[1], 0.0]'], {}), '([0.0, x[1], 0.0])\n', (53651, 53669), True, 'import numpy as np\n'), ((3268, 3295), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (3293, 3295), False, 'import multiprocessing\n'), ((3450, 3480), 'numpy.array', 'np.array', (['[0.0, 0.5, 0.5, 1.0]'], {}), '([0.0, 0.5, 0.5, 1.0])\n', (3458, 3480), True, 'import numpy as np\n'), ((3500, 3546), 'numpy.array', 'np.array', (['[1.0 / 6, 1.0 / 3, 1.0 / 3, 1.0 / 6]'], {}), '([1.0 / 6, 1.0 / 3, 1.0 / 3, 1.0 / 6])\n', (3508, 3546), True, 'import numpy as np\n'), ((20190, 20307), 'integrators.integrate._integrate_runge_kutta_jit', '_integrate_runge_kutta_jit', (['self.func', 'args[1]', 'args[2][np.newaxis, :]', 'args[3]', 'args[4]', 'self.b', 'self.c', 'self.a'], {}), '(self.func, args[1], args[2][np.newaxis, :], args\n [3], args[4], self.b, self.c, self.a)\n', (20216, 20307), False, 'from integrators.integrate import _integrate_runge_kutta_jit, _integrate_runge_kutta_tgls_jit, _zeros_func\n'), ((24565, 24592), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (24590, 24592), False, 'import multiprocessing\n'), ((24747, 24777), 'numpy.array', 'np.array', (['[0.0, 0.5, 0.5, 1.0]'], {}), '([0.0, 0.5, 0.5, 1.0])\n', (24755, 24777), True, 'import numpy as np\n'), ((24797, 24843), 'numpy.array', 'np.array', (['[1.0 / 6, 1.0 / 3, 1.0 / 3, 1.0 / 6]'], {}), '([1.0 / 6, 1.0 / 3, 1.0 / 3, 1.0 / 6])\n', (24805, 24843), True, 'import numpy as np\n'), ((40126, 40150), 'numpy.eye', 'np.eye', (['self.ic.shape[1]'], {}), '(self.ic.shape[1])\n', (40132, 40150), True, 'import numpy as np\n'), ((49711, 49907), 'integrators.integrate._integrate_runge_kutta_tgls_jit', '_integrate_runge_kutta_tgls_jit', (['self.func', 'self.func_jac', 'args[1]', 'args[2][np.newaxis, ...]', 'args[3][np.newaxis, ...]', 'args[4]', 'args[5]', 'self.b', 'self.c', 'self.a', 'args[6]', 'args[7]', 'args[8]'], {}), '(self.func, self.func_jac, args[1], args[2][\n np.newaxis, ...], args[3][np.newaxis, ...], args[4], args[5], self.b,\n self.c, self.a, args[6], args[7], args[8])\n', (49742, 49907), False, 'from integrators.integrate import _integrate_runge_kutta_jit, _integrate_runge_kutta_tgls_jit, _zeros_func\n'), ((50479, 50497), 'numpy.random.randn', 'np.random.randn', (['(6)'], {}), '(6)\n', (50494, 50497), True, 'import numpy as np\n'), ((50753, 50772), 'numpy.full', 'np.full', (['(1,)', '(10.0)'], {}), '((1,), 10.0)\n', (50760, 50772), True, 'import numpy as np\n'), ((51084, 51116), 'matplotlib.pyplot.plot', 'plt.plot', (['time', 'r[i, j]'], {'color': 'c'}), '(time, r[i, j], color=c)\n', (51092, 51116), True, 'import matplotlib.pyplot as plt\n'), ((51129, 51168), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'rl[i][j]'], {'color': 'c', 'ls': '"""--"""'}), "(t, rl[i][j], color=c, ls='--')\n", (51137, 51168), True, 'import matplotlib.pyplot as plt\n'), ((51556, 51574), 'functions.util.reverse', 'reverse', (['rlt[i][0]'], {}), '(rlt[i][0])\n', (51563, 51574), False, 'from functions.util import reverse\n'), ((51651, 51685), 'matplotlib.pyplot.plot', 'plt.plot', (['timet', 'rt[i, j]'], {'color': 'c'}), '(timet, rt[i, j], color=c)\n', (51659, 51685), True, 'import matplotlib.pyplot as plt\n'), ((53814, 53825), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (53822, 53825), True, 'import numpy as np\n'), ((10046, 10083), 'numpy.zeros', 'np.zeros', (['(number_of_trajectories, i)'], {}), '((number_of_trajectories, i))\n', (10054, 10083), True, 'import numpy as np\n'), ((10128, 10164), 'numpy.random.randn', 'np.random.randn', (['self.num_threads', 'i'], {}), '(self.num_threads, i)\n', (10143, 10164), True, 'import numpy as np\n'), ((10208, 10250), 'numpy.random.randn', 'np.random.randn', (['number_of_trajectories', 'i'], {}), '(number_of_trajectories, i)\n', (10223, 10250), True, 'import numpy as np\n'), ((14646, 14657), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (14654, 14657), True, 'import numpy as np\n'), ((14895, 14915), 'numpy.arange', 'np.arange', (['t0', 't', 'dt'], {}), '(t0, t, dt)\n', (14904, 14915), True, 'import numpy as np\n'), ((14917, 14933), 'numpy.full', 'np.full', (['(1,)', 't'], {}), '((1,), t)\n', (14924, 14933), True, 'import numpy as np\n'), ((16742, 16782), 'functions.util.reverse', 'reverse', (['self.time[::-self._write_steps]'], {}), '(self.time[::-self._write_steps])\n', (16749, 16782), False, 'from functions.util import reverse\n'), ((17076, 17106), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (17086, 17106), True, 'import numpy as np\n'), ((31905, 31942), 'numpy.zeros', 'np.zeros', (['(number_of_trajectories, i)'], {}), '((number_of_trajectories, i))\n', (31913, 31942), True, 'import numpy as np\n'), ((31987, 32023), 'numpy.random.randn', 'np.random.randn', (['self.num_threads', 'i'], {}), '(self.num_threads, i)\n', (32002, 32023), True, 'import numpy as np\n'), ((32067, 32109), 'numpy.random.randn', 'np.random.randn', (['number_of_trajectories', 'i'], {}), '(number_of_trajectories, i)\n', (32082, 32109), True, 'import numpy as np\n'), ((39749, 39760), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (39757, 39760), True, 'import numpy as np\n'), ((39998, 40018), 'numpy.arange', 'np.arange', (['t0', 't', 'dt'], {}), '(t0, t, dt)\n', (40007, 40018), True, 'import numpy as np\n'), ((40020, 40036), 'numpy.full', 'np.full', (['(1,)', 't'], {}), '((1,), t)\n', (40027, 40036), True, 'import numpy as np\n'), ((40362, 40390), 'numpy.concatenate', 'np.concatenate', (['(ict, tg_ic)'], {}), '((ict, tg_ic))\n', (40376, 40390), True, 'import numpy as np\n'), ((42350, 42390), 'numpy.swapaxes', 'np.swapaxes', (['self.recorded_fmatrix', '(1)', '(2)'], {}), '(self.recorded_fmatrix, 1, 2)\n', (42361, 42390), True, 'import numpy as np\n'), ((44110, 44150), 'functions.util.reverse', 'reverse', (['self.time[::-self._write_steps]'], {}), '(self.time[::-self._write_steps])\n', (44117, 44150), False, 'from functions.util import reverse\n'), ((44541, 44571), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (44551, 44571), True, 'import numpy as np\n'), ((44573, 44606), 'numpy.squeeze', 'np.squeeze', (['self.recorded_fmatrix'], {}), '(self.recorded_fmatrix)\n', (44583, 44606), True, 'import numpy as np\n'), ((50400, 50425), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (50408, 50425), True, 'import numpy as np\n'), ((50841, 50861), 'scipy.integrate.odeint', 'odeint', (['fr', 'ic[i]', 't'], {}), '(fr, ic[i], t)\n', (50847, 50861), False, 'from scipy.integrate import odeint\n'), ((51710, 51728), 'functions.util.reverse', 'reverse', (['rlt[i][j]'], {}), '(rlt[i][j])\n', (51717, 51728), False, 'from functions.util import reverse\n'), ((9676, 9687), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (9684, 9687), True, 'import numpy as np\n'), ((10964, 11001), 'numpy.random.randn', 'np.random.randn', (['next_len', 'x.shape[1]'], {}), '(next_len, x.shape[1])\n', (10979, 11001), True, 'import numpy as np\n'), ((31535, 31546), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (31543, 31546), True, 'import numpy as np\n'), ((32827, 32864), 'numpy.random.randn', 'np.random.randn', (['next_len', 'x.shape[1]'], {}), '(next_len, x.shape[1])\n', (32842, 32864), True, 'import numpy as np\n'), ((40643, 40667), 'numpy.swapaxes', 'np.swapaxes', (['tg_ic', '(1)', '(2)'], {}), '(tg_ic, 1, 2)\n', (40654, 40667), True, 'import numpy as np\n'), ((51405, 51415), 'functions.util.reverse', 'reverse', (['t'], {}), '(t)\n', (51412, 51415), False, 'from functions.util import reverse\n'), ((14339, 14350), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (14347, 14350), True, 'import numpy as np\n'), ((16480, 16510), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (16490, 16510), True, 'import numpy as np\n'), ((16669, 16699), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (16679, 16699), True, 'import numpy as np\n'), ((16862, 16892), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (16872, 16892), True, 'import numpy as np\n'), ((16996, 17026), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (17006, 17026), True, 'import numpy as np\n'), ((39442, 39453), 'numpy.zeros', 'np.zeros', (['i'], {}), '(i)\n', (39450, 39453), True, 'import numpy as np\n'), ((40776, 40804), 'numpy.concatenate', 'np.concatenate', (['(ict, tg_ic)'], {}), '((ict, tg_ic))\n', (40790, 40804), True, 'import numpy as np\n'), ((40948, 40972), 'numpy.swapaxes', 'np.swapaxes', (['tg_ic', '(1)', '(2)'], {}), '(tg_ic, 1, 2)\n', (40959, 40972), True, 'import numpy as np\n'), ((42596, 42636), 'numpy.swapaxes', 'np.swapaxes', (['self.recorded_fmatrix', '(1)', '(2)'], {}), '(self.recorded_fmatrix, 1, 2)\n', (42607, 42636), True, 'import numpy as np\n'), ((43749, 43779), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (43759, 43779), True, 'import numpy as np\n'), ((43810, 43843), 'numpy.squeeze', 'np.squeeze', (['self.recorded_fmatrix'], {}), '(self.recorded_fmatrix)\n', (43820, 43843), True, 'import numpy as np\n'), ((44002, 44032), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (44012, 44032), True, 'import numpy as np\n'), ((44034, 44067), 'numpy.squeeze', 'np.squeeze', (['self.recorded_fmatrix'], {}), '(self.recorded_fmatrix)\n', (44044, 44067), True, 'import numpy as np\n'), ((44230, 44260), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (44240, 44260), True, 'import numpy as np\n'), ((44262, 44295), 'numpy.squeeze', 'np.squeeze', (['self.recorded_fmatrix'], {}), '(self.recorded_fmatrix)\n', (44272, 44295), True, 'import numpy as np\n'), ((44399, 44429), 'numpy.squeeze', 'np.squeeze', (['self.recorded_traj'], {}), '(self.recorded_traj)\n', (44409, 44429), True, 'import numpy as np\n'), ((44459, 44492), 'numpy.squeeze', 'np.squeeze', (['self.recorded_fmatrix'], {}), '(self.recorded_fmatrix)\n', (44469, 44492), True, 'import numpy as np\n'), ((16608, 16636), 'numpy.full', 'np.full', (['(1,)', 'self.time[-1]'], {}), '((1,), self.time[-1])\n', (16615, 16636), True, 'import numpy as np\n'), ((16958, 16985), 'numpy.full', 'np.full', (['(1,)', 'self.time[0]'], {}), '((1,), self.time[0])\n', (16965, 16985), True, 'import numpy as np\n'), ((43941, 43969), 'numpy.full', 'np.full', (['(1,)', 'self.time[-1]'], {}), '((1,), self.time[-1])\n', (43948, 43969), True, 'import numpy as np\n'), ((44361, 44388), 'numpy.full', 'np.full', (['(1,)', 'self.time[0]'], {}), '((1,), self.time[0])\n', (44368, 44388), True, 'import numpy as np\n')] |
import numpy as np
from .. import Geometry, Line, LineSegmentMaterial
from ..utils import Color
DTYPE = "f4"
class GridHelper(Line):
"""An object indicating the z=0 plane."""
def __init__(
self,
size=10.0,
divisions=10,
color1=(0.35, 0.35, 0.35, 1),
color2=(0.1, 0.1, 0.1, 1),
thickness=1,
):
assert isinstance(divisions, int)
assert size > 0.0
half_size = size / 2
n_lines = divisions + 1
x = np.linspace(-half_size, half_size, num=n_lines, dtype=DTYPE)
# the grid is made up of 2 * n_lines line segments
# where each line has two endpoints (2, 3)
positions = np.zeros((2, n_lines, 2, 3), dtype=DTYPE)
positions[0, ..., 0] = x[:, None]
positions[0, ..., 2] = [[-half_size, half_size]]
positions[1, ..., 0] = [[-half_size, half_size]]
positions[1, ..., 2] = x[:, None]
# color1 for the center lines, color2 for the rest
colors = np.empty((2, n_lines, 2, 4), dtype=DTYPE)
colors[..., :] = Color(color2)
colors[:, n_lines // 2, :, :] = Color(color1)
geometry = Geometry(
positions=positions.reshape((-1, 3)), colors=colors.reshape((-1, 4))
)
material = LineSegmentMaterial(vertex_colors=True, thickness=thickness, aa=True)
super().__init__(geometry, material)
| [
"numpy.empty",
"numpy.zeros",
"numpy.linspace"
] | [((500, 560), 'numpy.linspace', 'np.linspace', (['(-half_size)', 'half_size'], {'num': 'n_lines', 'dtype': 'DTYPE'}), '(-half_size, half_size, num=n_lines, dtype=DTYPE)\n', (511, 560), True, 'import numpy as np\n'), ((692, 733), 'numpy.zeros', 'np.zeros', (['(2, n_lines, 2, 3)'], {'dtype': 'DTYPE'}), '((2, n_lines, 2, 3), dtype=DTYPE)\n', (700, 733), True, 'import numpy as np\n'), ((1009, 1050), 'numpy.empty', 'np.empty', (['(2, n_lines, 2, 4)'], {'dtype': 'DTYPE'}), '((2, n_lines, 2, 4), dtype=DTYPE)\n', (1017, 1050), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.io.luts.common` module.
"""
from __future__ import division, unicode_literals
import numpy as np
import unittest
from colour.constants import DEFAULT_INT_DTYPE
from colour.io.luts.common import parse_array, path_to_title
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = '<EMAIL>'
__status__ = 'Production'
__all__ = ['TestParseArray', 'TestPathToTitle']
class TestParseArray(unittest.TestCase):
"""
Defines :func:`colour.io.luts.common.parse_array` definition unit tests
methods.
"""
def test_parse_array(self):
"""
Tests :func:`colour.io.luts.common.parse_array` definition.
"""
np.testing.assert_equal(
parse_array('-0.25 0.5 0.75'),
np.array([-0.25, 0.5, 0.75]),
)
np.testing.assert_equal(
parse_array(['-0.25', '0.5', '0.75']),
np.array([-0.25, 0.5, 0.75]),
)
a = np.linspace(0, 1, 10)
np.testing.assert_almost_equal(
parse_array(
str(a.tolist()).replace(
'[',
'',
).replace(
']',
'',
).replace(
' ',
'',
),
separator=','),
a,
decimal=7)
self.assertEqual(
parse_array(['1', '2', '3'], dtype=DEFAULT_INT_DTYPE).dtype,
DEFAULT_INT_DTYPE)
class TestPathToTitle(unittest.TestCase):
"""
Defines :func:`colour.io.luts.common.path_to_title` definition unit tests
methods.
"""
def test_path_to_title(self):
"""
Tests :func:`colour.io.luts.common.path_to_title` definition.
"""
self.assertEqual(
path_to_title(
'colour/io/luts/tests/resources/cinespace/RGB_1_0.5_0.25.csp'),
'RGB 1 0 5 0 25')
if __name__ == '__main__':
unittest.main()
| [
"unittest.main",
"colour.io.luts.common.parse_array",
"numpy.array",
"numpy.linspace",
"colour.io.luts.common.path_to_title"
] | [((2175, 2190), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2188, 2190), False, 'import unittest\n'), ((1149, 1170), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(10)'], {}), '(0, 1, 10)\n', (1160, 1170), True, 'import numpy as np\n'), ((916, 945), 'colour.io.luts.common.parse_array', 'parse_array', (['"""-0.25 0.5 0.75"""'], {}), "('-0.25 0.5 0.75')\n", (927, 945), False, 'from colour.io.luts.common import parse_array, path_to_title\n'), ((959, 987), 'numpy.array', 'np.array', (['[-0.25, 0.5, 0.75]'], {}), '([-0.25, 0.5, 0.75])\n', (967, 987), True, 'import numpy as np\n'), ((1045, 1082), 'colour.io.luts.common.parse_array', 'parse_array', (["['-0.25', '0.5', '0.75']"], {}), "(['-0.25', '0.5', '0.75'])\n", (1056, 1082), False, 'from colour.io.luts.common import parse_array, path_to_title\n'), ((1096, 1124), 'numpy.array', 'np.array', (['[-0.25, 0.5, 0.75]'], {}), '([-0.25, 0.5, 0.75])\n', (1104, 1124), True, 'import numpy as np\n'), ((2017, 2093), 'colour.io.luts.common.path_to_title', 'path_to_title', (['"""colour/io/luts/tests/resources/cinespace/RGB_1_0.5_0.25.csp"""'], {}), "('colour/io/luts/tests/resources/cinespace/RGB_1_0.5_0.25.csp')\n", (2030, 2093), False, 'from colour.io.luts.common import parse_array, path_to_title\n'), ((1606, 1659), 'colour.io.luts.common.parse_array', 'parse_array', (["['1', '2', '3']"], {'dtype': 'DEFAULT_INT_DTYPE'}), "(['1', '2', '3'], dtype=DEFAULT_INT_DTYPE)\n", (1617, 1659), False, 'from colour.io.luts.common import parse_array, path_to_title\n')] |
"""
Copyright (c) 2018-2021 Intel Corporation
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 pytest
pytest.importorskip('accuracy_checker.launcher.onnx_launcher')
import cv2
import numpy as np
from accuracy_checker.launcher.launcher import create_launcher
from accuracy_checker.config import ConfigError
def old_onnxrunitme(models_dir):
import onnxruntime as rt
sess = rt.InferenceSession(str(models_dir / "samplenet.onnx"))
try:
sess.get_providers()
return False
except AttributeError:
return True
def get_onnx_test_model(models_dir, device=None, ep=None):
config = {
"framework": "onnx_runtime",
"model": str(models_dir / "samplenet.onnx"),
"adapter": "classification",
}
if device is not None:
config['device'] = device
if ep is not None:
config['execution_providers'] = ep
return create_launcher(config)
class TestONNXRuntimeLauncher:
def test_launcher_creates(self, models_dir):
launcher = get_onnx_test_model(models_dir)
assert launcher.inputs['data'] == [1, 3, 32, 32]
assert launcher.output_blob == 'fc3'
def test_infer(self, data_dir, models_dir):
onnx_test_model = get_onnx_test_model(models_dir)
_, _, h, w = onnx_test_model.inputs['data']
img_raw = cv2.imread(str(data_dir / '1.jpg'))
img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
img_resized = cv2.resize(img_rgb, (w, h))
input_blob = np.transpose([img_resized], (0, 3, 1, 2))
res = onnx_test_model.predict([{'data': input_blob.astype(np.float32)}], [{}])
assert np.argmax(res[0]['fc3']) == 7
def test_infer_with_execution_provider(self, data_dir, models_dir):
if old_onnxrunitme(models_dir):
pytest.skip(reason="onnxruntime does not support EP")
onnx_test_model = get_onnx_test_model(models_dir, ep=['CPUExecutionProvider'])
_, _, h, w = onnx_test_model.inputs['data']
img_raw = cv2.imread(str(data_dir / '1.jpg'))
img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
img_resized = cv2.resize(img_rgb, (w, h))
input_blob = np.transpose([img_resized], (0, 3, 1, 2))
res = onnx_test_model.predict([{'data': input_blob.astype(np.float32)}], [{}])
assert np.argmax(res[0]['fc3']) == 7
def test_auto_model_search(self, models_dir):
config = {
"framework": "onnx_runtime",
"model": models_dir,
}
launcher = create_launcher(config, 'samplenet')
assert launcher.model == models_dir / "samplenet.onnx"
@pytest.mark.usefixtures('mock_path_exists')
class TestONNXRuntimeLauncherConfig:
def test_missed_model_in_create_onnx_launcher_raises_config_error_exception(self):
config = {'framework': 'onnx_runtime'}
with pytest.raises(ConfigError):
create_launcher(config)
def test_unsupported_device_in_create_onnx_launcher_raises_config_error_exception(self):
config = {'framework': 'onnx_runtime', 'model': 'model.onnx', 'device': 'UNSUPPORTED'}
with pytest.raises(ConfigError):
create_launcher(config)
| [
"cv2.resize",
"pytest.importorskip",
"numpy.argmax",
"cv2.cvtColor",
"numpy.transpose",
"pytest.skip",
"pytest.raises",
"accuracy_checker.launcher.launcher.create_launcher",
"pytest.mark.usefixtures"
] | [((592, 654), 'pytest.importorskip', 'pytest.importorskip', (['"""accuracy_checker.launcher.onnx_launcher"""'], {}), "('accuracy_checker.launcher.onnx_launcher')\n", (611, 654), False, 'import pytest\n'), ((3112, 3155), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""mock_path_exists"""'], {}), "('mock_path_exists')\n", (3135, 3155), False, 'import pytest\n'), ((1382, 1405), 'accuracy_checker.launcher.launcher.create_launcher', 'create_launcher', (['config'], {}), '(config)\n', (1397, 1405), False, 'from accuracy_checker.launcher.launcher import create_launcher\n'), ((1872, 1912), 'cv2.cvtColor', 'cv2.cvtColor', (['img_raw', 'cv2.COLOR_BGR2RGB'], {}), '(img_raw, cv2.COLOR_BGR2RGB)\n', (1884, 1912), False, 'import cv2\n'), ((1935, 1962), 'cv2.resize', 'cv2.resize', (['img_rgb', '(w, h)'], {}), '(img_rgb, (w, h))\n', (1945, 1962), False, 'import cv2\n'), ((1984, 2025), 'numpy.transpose', 'np.transpose', (['[img_resized]', '(0, 3, 1, 2)'], {}), '([img_resized], (0, 3, 1, 2))\n', (1996, 2025), True, 'import numpy as np\n'), ((2549, 2589), 'cv2.cvtColor', 'cv2.cvtColor', (['img_raw', 'cv2.COLOR_BGR2RGB'], {}), '(img_raw, cv2.COLOR_BGR2RGB)\n', (2561, 2589), False, 'import cv2\n'), ((2612, 2639), 'cv2.resize', 'cv2.resize', (['img_rgb', '(w, h)'], {}), '(img_rgb, (w, h))\n', (2622, 2639), False, 'import cv2\n'), ((2661, 2702), 'numpy.transpose', 'np.transpose', (['[img_resized]', '(0, 3, 1, 2)'], {}), '([img_resized], (0, 3, 1, 2))\n', (2673, 2702), True, 'import numpy as np\n'), ((3009, 3045), 'accuracy_checker.launcher.launcher.create_launcher', 'create_launcher', (['config', '"""samplenet"""'], {}), "(config, 'samplenet')\n", (3024, 3045), False, 'from accuracy_checker.launcher.launcher import create_launcher\n'), ((2129, 2153), 'numpy.argmax', 'np.argmax', (["res[0]['fc3']"], {}), "(res[0]['fc3'])\n", (2138, 2153), True, 'import numpy as np\n'), ((2284, 2337), 'pytest.skip', 'pytest.skip', ([], {'reason': '"""onnxruntime does not support EP"""'}), "(reason='onnxruntime does not support EP')\n", (2295, 2337), False, 'import pytest\n'), ((2806, 2830), 'numpy.argmax', 'np.argmax', (["res[0]['fc3']"], {}), "(res[0]['fc3'])\n", (2815, 2830), True, 'import numpy as np\n'), ((3341, 3367), 'pytest.raises', 'pytest.raises', (['ConfigError'], {}), '(ConfigError)\n', (3354, 3367), False, 'import pytest\n'), ((3381, 3404), 'accuracy_checker.launcher.launcher.create_launcher', 'create_launcher', (['config'], {}), '(config)\n', (3396, 3404), False, 'from accuracy_checker.launcher.launcher import create_launcher\n'), ((3608, 3634), 'pytest.raises', 'pytest.raises', (['ConfigError'], {}), '(ConfigError)\n', (3621, 3634), False, 'import pytest\n'), ((3648, 3671), 'accuracy_checker.launcher.launcher.create_launcher', 'create_launcher', (['config'], {}), '(config)\n', (3663, 3671), False, 'from accuracy_checker.launcher.launcher import create_launcher\n')] |
import numpy as np
##################################################################################
# Two class or binary SVM #
##################################################################################
def binary_svm_loss(theta, X, y, C):
"""
SVM hinge loss function for two class problem
Inputs:
- theta: A numpy vector of size d containing coefficients.
- X: A numpy array of shape mxd
- y: A numpy array of shape (m,) containing training labels; +1, -1
- C: (float) penalty factor
Returns a tuple of:
- loss as single float
- gradient with respect to theta; an array of same shape as theta
"""
m, d = X.shape
grad = np.zeros(theta.shape)
J = 0
############################################################################
# TODO #
# Implement the binary SVM hinge loss function here #
# 4 - 5 lines of vectorized code expected #
############################################################################
h = X@theta
J = 1.0 / 2.0 * np.sum(np.square(theta)) / m + C / m * np.sum(np.max([np.zeros(m), 1 - y * h], axis=0))
grad = 1.0 / m * theta + C / m * X.T@(-y * (y * h < 1))
#############################################################################
# END OF YOUR CODE #
#############################################################################
return J, grad
##################################################################################
# Multiclass SVM #
##################################################################################
# SVM multiclass
def svm_loss_naive(theta, X, y, C):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension d, there are K classes, and we operate on minibatches
of m examples.
Inputs:
- theta: A numpy array of shape d X K containing parameters.
- X: A numpy array of shape m X d containing a minibatch of data.
- y: A numpy array of shape (m,) containing training labels; y[i] = k means
that X[i] has label k, where 0 <= k < K.
- C: (float) penalty factor
Returns a tuple of:
- loss J as single float
- gradient with respect to weights theta; an array of same shape as theta
"""
K = theta.shape[1] # number of classes
m = X.shape[0] # number of examples
J = 0.0
dtheta = np.zeros(theta.shape) # initialize the gradient as zero
delta = 1.0
#############################################################################
# TODO: #
# Compute the loss function and store it in J. #
# Do not forget the regularization term! #
# code above to compute the gradient. #
# 8-10 lines of code expected #
#############################################################################
for i in range(m):
h = X[i, :]@theta
hy = h[y[i]]
for j in range(K):
if j == y[i]:
continue
cur = h[j] - hy + delta
if cur > 0:
J += cur
dtheta[:, j] += X[i, :]
dtheta[:, y[i]] -= X[i, :]
J = np.sum(np.square(theta)) / 2 / m + C * J / m
dtheta = theta / m + C * dtheta / m
# For jupyter notebook
# J = C * np.sum(np.square(theta)) / 2 / m + J / m
# dtheta = C * theta / m + dtheta / m
#############################################################################
# TODO: #
# Compute the gradient of the loss function and store it dtheta. #
# Rather that first computing the loss and then computing the derivative, #
# it may be simpler to compute the derivative at the same time that the #
# loss is being computed. As a result you may need to modify some of the #
# code above to compute the gradient. #
#############################################################################
return J, dtheta
def svm_loss_vectorized(theta, X, y, C):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
J = 0.0
dtheta = np.zeros(theta.shape) # initialize the gradient as zero
delta = 1.0
m = X.shape[0]
K = theta.shape[1]
d = theta.shape[0]
#############################################################################
# TODO: #
# Implement a vectorized version of the structured SVM loss, storing the #
# result in variable J. #
# 8-10 lines of code #
#############################################################################
h = X@theta
hy = h - h[range(len(y)), y].reshape((-1, 1))
hy[hy != 0] += delta
cur = np.maximum(0.0, hy)
J = np.sum(np.square(theta)) / 2 / m + C * np.sum(cur) / m
# For jupyter notebook
# J = C * np.sum(np.square(theta)) / 2 / m + np.sum(cur) / m
#############################################################################
# END OF YOUR CODE #
#############################################################################
#############################################################################
# TODO: #
# Implement a vectorized version of the gradient for the structured SVM #
# loss, storing the result in dtheta. #
# #
# Hint: Instead of computing the gradient from scratch, it may be easier #
# to reuse some of the intermediate values that you used to compute the #
# loss. #
#############################################################################
cc = (hy > 0) * 1
cc[range(len(y)), y] = -np.sum(cc, axis=1)
dtheta = theta / m + C * X.T@cc / m
# For jupyter notebook
# dtheta = C * theta / m + X.T @ cc / m
#############################################################################
# END OF YOUR CODE #
#############################################################################
return J, dtheta
| [
"numpy.sum",
"numpy.zeros",
"numpy.maximum",
"numpy.square"
] | [((741, 762), 'numpy.zeros', 'np.zeros', (['theta.shape'], {}), '(theta.shape)\n', (749, 762), True, 'import numpy as np\n'), ((2671, 2692), 'numpy.zeros', 'np.zeros', (['theta.shape'], {}), '(theta.shape)\n', (2679, 2692), True, 'import numpy as np\n'), ((4731, 4752), 'numpy.zeros', 'np.zeros', (['theta.shape'], {}), '(theta.shape)\n', (4739, 4752), True, 'import numpy as np\n'), ((5463, 5482), 'numpy.maximum', 'np.maximum', (['(0.0)', 'hy'], {}), '(0.0, hy)\n', (5473, 5482), True, 'import numpy as np\n'), ((6673, 6691), 'numpy.sum', 'np.sum', (['cc'], {'axis': '(1)'}), '(cc, axis=1)\n', (6679, 6691), True, 'import numpy as np\n'), ((5530, 5541), 'numpy.sum', 'np.sum', (['cur'], {}), '(cur)\n', (5536, 5541), True, 'import numpy as np\n'), ((1222, 1238), 'numpy.square', 'np.square', (['theta'], {}), '(theta)\n', (1231, 1238), True, 'import numpy as np\n'), ((3650, 3666), 'numpy.square', 'np.square', (['theta'], {}), '(theta)\n', (3659, 3666), True, 'import numpy as np\n'), ((5498, 5514), 'numpy.square', 'np.square', (['theta'], {}), '(theta)\n', (5507, 5514), True, 'import numpy as np\n'), ((1269, 1280), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (1277, 1280), True, 'import numpy as np\n')] |
import warnings
import os
from ..base import PSGbase
import numpy as np
import pandas as pd
from .utils import _read_event, _read_technician_note, _read_sleep_stage, \
_read_data_segments,_read_header,_read_montage, _read_epoch_data,\
read_dat_data, read_d16_data, read_dat_discrete_data
import scipy.signal
import mne
import time
import scipy.signal
def read_psg_compumedics(folder,include = 'all',mne_output = True,
resample = True, sf = 128
):
"""
Read compumedics raw files. This function was only tested for files
recorded with Grael. Furthermore, data types may be different for older
file. If an error occurs, consider exporting your data to .edf using
profusion and use our :py:
Parameters
----------
folder : str
path to the folder containing compumedics files
include : list or 'all'
The list of channel to be loaded
mne_output : bool
If True (default), will output raw data as a :py:class:`mne.io.BaseRaw`
object. If False, will return a dict.
resample : bool
If True, all channels will be resampled to "sf" frequency.
sf : int
Sampling frequency to resample channels to (default 128).
Returns
-------
raw : :py:class:`mne.io.BaseRaw` or 'dict
An MNE Raw instance if mne_output is True, else a dict containing
informations about each channels + the data
hypnogram : pd.DataFrame
A dataframe with sleep staging (label, duration and onset) informations.
events : pd.DataFrame
A dataframe containing events (e.g. apneas, arousals) informations.
Each line corresponds to a different events. Dataframe keys are
"EVT_LABEL", "EVT_TIME" and "EVT_LENGTH" and represents label,
onset and duration of the onsets.
"""
for file in ['STUDYCFG.xml', 'DATASEGMENTS.xml']:
if not os.path.exists(os.path.join(folder, 'STUDYCFG.xml')):
raise IOError('{} folder does not contain the {} file'.format(
folder, file))
pg = PSGcompumedics(folder)
dtcdata = pg.raw_data(include=include)
hypnogram = pg.hypnogram()
events = pg.events()
if mne_output:
ch_name = []
ch_data = []
ch_list = list(dtcdata.keys())
for ch in ch_list:
temp = dtcdata[ch]
if len(temp['data']) != 0:
if 'DiscreteData' not in list(temp.keys()):
ch_name.append(ch)
data = temp['data']
datafs = int(temp['Rate'])
if temp['Type'] == '4': datafs = datafs/2 #it seems
# sampling frequency is wrong for these channels
if resample:
resampled_data = scipy.signal.resample_poly(\
data, sf, datafs) * -1
ch_data.append(resampled_data)
else:
if datafs == 512:
sf=512
ch_data.append(data)
info = mne.create_info(ch_name, sfreq=sf)
info['meas_date'] = pg.start_date()
raw = mne.io.RawArray(np.vstack(ch_data), info, verbose='error')
else:
raw = dtcdata
return raw,hypnogram,events
def cpm_what_channels(folder):
"""Helper functions to print available channels given a folder with
polysomnography files"""
pg = PSGcompumedics(folder)
return pg.available_channel
class PSGcompumedics(PSGbase):
"""
Class to read compumedics files
"""
def __init__(self,folder, lights_on_off = None):
super().__init__(folder)
self.multiple_data_segment = False
self._folder = folder
# POLYSOMNOGRAPHY INFO
self.montage = _read_montage(folder)
self.available_channel = list(self.montage.keys())
self.header = _read_header(folder)
self.data_segments = _read_data_segments(folder)
self._tech_notes = _read_technician_note(folder)
self._epoch_data = _read_epoch_data(folder)
self._epoch_length = int(self.header['EpochLength'])
self._stages = _read_sleep_stage(folder)
if lights_on_off is None:
self.lights_off, self.lights_on = self._find_lights()
def raw_data(self, include = 'all', detrend = True):
"""
Reads PSG raw data and returns a dict.
Parameters
----------
include : list or 'all'
The list of channel to be loaded
detrend : bool
If true, linear trend (offset values) will be removed using
:py:`scipy.signal.detrends`
Returns
-------
raw : dict
Data. Keys and values will depend on the channels (discrete vs
continuous)
"""
montage = self.montage
if include is 'all': include = list(montage.keys())
for ch_name in list(montage.keys()):
if ch_name in include:
ch = montage[ch_name]
ch_file = os.path.join(self._folder, ch['Filename'])
ch_fs = int(ch['Rate'])
ext = os.path.splitext(ch_file)[1]
if ext =='.D16':
data = read_d16_data(ch_file, ch_fs)
elif ext=='.DAT':
if 'DiscreteData' in list(ch.keys()):
t, data= read_dat_discrete_data(ch_file, ch_fs)
else:
data = read_dat_data(ch_file)
else:
raise ValueError('Weird channel format: ' + ext)
if int(ch['Type']) == 1:
data = scipy.signal.detrend(data)
data = mne.filter.filter_data(np.asarray(data,
dtype='float'),
ch_fs,l_freq=0.05,
h_freq=None, verbose='error')
if 'DiscreteData' not in list(ch.keys()):
if len(self.data_segments)>1:
if int(ch['Type']) == 4: ch_fs = ch_fs/2
starts = np.asarray([int(seg['Start']) for seg in \
self.data_segments])
durs = np.asarray([int(seg['Duration']) for seg in \
self.data_segments])
total_duration = starts[-1] + durs[-1]
array = np.zeros((int(ch_fs*(total_duration)),1)).squeeze()
prev = 0
for (start,stop,du) in zip(starts,starts+durs,
durs):
end_data = prev + int(du*ch_fs)
array[int(start*ch_fs):int(stop*ch_fs)] = data[
prev:end_data]
prev = prev + int(du*ch_fs)
data = array
montage[ch_name]['data'] = data
else:
montage[ch_name]['data'] = (t, data)
else:
montage[ch_name]['data'] = []
return montage
def posture(self):
"""
Reads posture information from compumedics files.
Returns
-------
posture : pd.Dataframe
Dataframe containing posture informations for each epochs.
"""
posture = self._epoch_data[['Posture']]
posture['onset'] = np.cumsum(np.ones_like(posture['Posture'].values)*30)
posture['duration'] = np.ones_like(posture['onset'].values) * 30
return posture
def hypnogram(self, trim = False):
"""
Reads sleep staging informations.
Returns
-------
hypnogram : pd.DataFrame
A dataframe with sleep staging (label, duration and onset)
informations.
"""
hypno = np.asarray(self._stages, dtype='int')
onsets = np.cumsum(np.ones_like(hypno)*self._epoch_length) - 30
if trim:
index_hypn_in_loff_lon = np.bitwise_and(onsets>self.lights_off,
onsets<self.lights_on)
onsets = onsets[index_hypn_in_loff_lon]
hypno = hypno[index_hypn_in_loff_lon]
stage_duration = np.ones_like(hypno) * 30
Stages = pd.DataFrame(data={'label': hypno,
'duration': stage_duration,
'onset': onsets,
})
return Stages
def events(self):
"""
Reads manual scoring of events (e.g. apneas and arousals).
Returns
-------
events : pd.DataFrame
A dataframe containing events (e.g. apneas, arousals) informations.
Each line corresponds to a different events. Dataframe keys are
"EVT_LABEL", "EVT_TIME" and "EVT_LENGTH" and represents label,
onset and duration of the onsets.
"""
_events = _read_event(self._folder)
return _events
def _find_lights(self):
from ..utils import lights_is_wrong
lights_off, lights_on = self._find_lights_from_tech_notes()
if lights_is_wrong(lights_off, lights_on):
if len(self._stages) > 0:
lights_on = len(self._stages) * int(self._epoch_length)
lights_off = 0
return (lights_off, lights_on)
def _find_lights_from_tech_notes(self):
lights_off, lights_on = (None,None)
if self._tech_notes:
labels = self._tech_notes['event']
if all(['LIGHTS OFF' in labels, 'LIGHTS ON' in labels]):
for event in ['LIGHTS OFF','LIGHTS ON']:
index_lo = [idx for idx, s in enumerate(labels) if s == event]
if len(index_lo) > 1:
warnings.warn("Found {} " + event +" tech notes, setting "
"lights "
"on/off to the last".format(len(index_lo)))
index_lo = index_lo[-1]
if index_lo:
if event=='LIGHTS OFF':
lights_off = int(index_lo[0])
else:
lights_on = int(index_lo[0])
else:
warnings.warn('Tech notes does not contain LIGHTS OFF and '
'LIGHTS ON.')
else:
warnings.warn('No tech form to infer lights on/off from.')
return (lights_off, lights_on)
def start_date(self):
import datetime
date = self.header['StartDate'] + ' ' + self.header['StartTime']
datetime_object = datetime.datetime.strptime(date,
'%d/%m/%Y %H:%M:%S')
datetime_object = datetime_object.replace(tzinfo=datetime.timezone.utc)
return datetime_object
def info(self):
print('-----------Compumedics Polysomnography ------------')
print('- Date : {} '
'Time: {}'.format(self.header['StartDate'],self.header['StartTime']))
print('- Lights on time : {} '
'Lights off time: {}'.format(self.lights_on,self.lights_off)) | [
"pandas.DataFrame",
"numpy.ones_like",
"numpy.asarray",
"mne.create_info",
"datetime.datetime.strptime",
"numpy.bitwise_and",
"os.path.splitext",
"warnings.warn",
"os.path.join",
"numpy.vstack"
] | [((3117, 3151), 'mne.create_info', 'mne.create_info', (['ch_name'], {'sfreq': 'sf'}), '(ch_name, sfreq=sf)\n', (3132, 3151), False, 'import mne\n'), ((8043, 8080), 'numpy.asarray', 'np.asarray', (['self._stages'], {'dtype': '"""int"""'}), "(self._stages, dtype='int')\n", (8053, 8080), True, 'import numpy as np\n'), ((8490, 8575), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'label': hypno, 'duration': stage_duration, 'onset': onsets}"}), "(data={'label': hypno, 'duration': stage_duration, 'onset': onsets}\n )\n", (8502, 8575), True, 'import pandas as pd\n'), ((10932, 10985), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['date', '"""%d/%m/%Y %H:%M:%S"""'], {}), "(date, '%d/%m/%Y %H:%M:%S')\n", (10958, 10985), False, 'import datetime\n'), ((3226, 3244), 'numpy.vstack', 'np.vstack', (['ch_data'], {}), '(ch_data)\n', (3235, 3244), True, 'import numpy as np\n'), ((7692, 7729), 'numpy.ones_like', 'np.ones_like', (["posture['onset'].values"], {}), "(posture['onset'].values)\n", (7704, 7729), True, 'import numpy as np\n'), ((8207, 8272), 'numpy.bitwise_and', 'np.bitwise_and', (['(onsets > self.lights_off)', '(onsets < self.lights_on)'], {}), '(onsets > self.lights_off, onsets < self.lights_on)\n', (8221, 8272), True, 'import numpy as np\n'), ((8448, 8467), 'numpy.ones_like', 'np.ones_like', (['hypno'], {}), '(hypno)\n', (8460, 8467), True, 'import numpy as np\n'), ((10684, 10742), 'warnings.warn', 'warnings.warn', (['"""No tech form to infer lights on/off from."""'], {}), "('No tech form to infer lights on/off from.')\n", (10697, 10742), False, 'import warnings\n'), ((1940, 1976), 'os.path.join', 'os.path.join', (['folder', '"""STUDYCFG.xml"""'], {}), "(folder, 'STUDYCFG.xml')\n", (1952, 1976), False, 'import os\n'), ((5097, 5139), 'os.path.join', 'os.path.join', (['self._folder', "ch['Filename']"], {}), "(self._folder, ch['Filename'])\n", (5109, 5139), False, 'import os\n'), ((7618, 7657), 'numpy.ones_like', 'np.ones_like', (["posture['Posture'].values"], {}), "(posture['Posture'].values)\n", (7630, 7657), True, 'import numpy as np\n'), ((10554, 10624), 'warnings.warn', 'warnings.warn', (['"""Tech notes does not contain LIGHTS OFF and LIGHTS ON."""'], {}), "('Tech notes does not contain LIGHTS OFF and LIGHTS ON.')\n", (10567, 10624), False, 'import warnings\n'), ((5203, 5228), 'os.path.splitext', 'os.path.splitext', (['ch_file'], {}), '(ch_file)\n', (5219, 5228), False, 'import os\n'), ((8108, 8127), 'numpy.ones_like', 'np.ones_like', (['hypno'], {}), '(hypno)\n', (8120, 8127), True, 'import numpy as np\n'), ((5803, 5834), 'numpy.asarray', 'np.asarray', (['data'], {'dtype': '"""float"""'}), "(data, dtype='float')\n", (5813, 5834), True, 'import numpy as np\n')] |
import pathlib
import tempfile
import numpy as np
import qpimage
from drymass.cli import config, dialog
def setup_test_data(radius_px=30, size=200, pxsize=1e-6, medium_index=1.335,
wavelength=550e-9, method="edge", model="projection",
refraction_increment=.18, num=1, write_config=True):
x = np.arange(size).reshape(-1, 1)
y = np.arange(size).reshape(1, -1)
cx = 80
cy = 120
r = np.sqrt((x - cx)**2 + (y - cy)**2)
pha = (r < radius_px) * 1.3
amp = .5 + np.roll(pha, 10) / pha.max()
qpi = qpimage.QPImage(data=(pha, amp), which_data="phase,amplitude")
path_in = tempfile.mktemp(suffix=".h5", prefix="drymass_test_cli_dialog")
path_in = pathlib.Path(path_in)
with qpimage.QPSeries(h5file=path_in, h5mode="w", identifier="tes") as qps:
for ii in range(num):
qps.add_qpimage(qpi, identifier="test_{}".format(ii))
path_out = path_in.with_name(path_in.name + dialog.OUTPUT_SUFFIX)
path_out.mkdir()
if write_config:
# add drymass configuration file
cfg = config.ConfigFile(path_out)
cfg.set_value(section="meta", key="pixel size um", value=pxsize*1e6)
cfg.set_value(section="meta", key="wavelength nm",
value=wavelength*1e9)
cfg.set_value(section="meta", key="medium index", value=medium_index)
cfg.set_value(section="sphere", key="method", value=method)
cfg.set_value(section="sphere", key="model", value=model)
cfg.set_value(section="sphere", key="refraction increment",
value=refraction_increment)
return qpi, path_in, path_out
def test_merge_config():
# test data
_, path_in, path_out = setup_test_data(medium_index=1.30,
pxsize=1.12e-6,
method="image",
model="projection",
refraction_increment=1.1)
# profile
_, path_profile = tempfile.mkstemp(
prefix="drymass_test_config_", suffix=".cfg")
cfg = config.ConfigFile(path=path_profile)
cfg.path.write_text("[meta]\n"
+ "medium index = 1.31\n"
+ "pixel size um = None\n"
+ "[sphere]\n"
+ "method = image\n"
+ "model = rytov\n")
cfg2 = config.ConfigFile(path=path_out)
assert cfg2["sphere"]["refraction increment"] == 1.1, "for test case"
assert cfg2["meta"]["pixel size um"] == 1.12, "for test case"
# apply profile (merge with original configuration)
dialog.main(path=path_in, profile=path_profile)
# Sanity checks in case DryMass defaults changed
assert cfg["sphere"]["refraction increment"] != 1.1, "for test case"
assert cfg["meta"]["pixel size um"] != 1.12, "for test case"
# The following three are all valid by just copying cfg to path_out
assert cfg2["meta"]["medium index"] == 1.31
assert cfg2["sphere"]["method"] == "image"
assert cfg2["sphere"]["model"] == "rytov"
# This one is only valid when the configs are merged
assert cfg2["sphere"]["refraction increment"] == 1.1
# This one is only valid when Nones in profile do not override path_out
assert cfg2["meta"]["pixel size um"] == 1.12
if __name__ == "__main__":
# Run all tests
loc = locals()
for key in list(loc.keys()):
if key.startswith("test_") and hasattr(loc[key], "__call__"):
loc[key]()
| [
"qpimage.QPSeries",
"drymass.cli.config.ConfigFile",
"tempfile.mkstemp",
"numpy.roll",
"pathlib.Path",
"numpy.arange",
"qpimage.QPImage",
"tempfile.mktemp",
"drymass.cli.dialog.main",
"numpy.sqrt"
] | [((443, 481), 'numpy.sqrt', 'np.sqrt', (['((x - cx) ** 2 + (y - cy) ** 2)'], {}), '((x - cx) ** 2 + (y - cy) ** 2)\n', (450, 481), True, 'import numpy as np\n'), ((564, 626), 'qpimage.QPImage', 'qpimage.QPImage', ([], {'data': '(pha, amp)', 'which_data': '"""phase,amplitude"""'}), "(data=(pha, amp), which_data='phase,amplitude')\n", (579, 626), False, 'import qpimage\n'), ((641, 704), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'suffix': '""".h5"""', 'prefix': '"""drymass_test_cli_dialog"""'}), "(suffix='.h5', prefix='drymass_test_cli_dialog')\n", (656, 704), False, 'import tempfile\n'), ((719, 740), 'pathlib.Path', 'pathlib.Path', (['path_in'], {}), '(path_in)\n', (731, 740), False, 'import pathlib\n'), ((2048, 2110), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'prefix': '"""drymass_test_config_"""', 'suffix': '""".cfg"""'}), "(prefix='drymass_test_config_', suffix='.cfg')\n", (2064, 2110), False, 'import tempfile\n'), ((2130, 2166), 'drymass.cli.config.ConfigFile', 'config.ConfigFile', ([], {'path': 'path_profile'}), '(path=path_profile)\n', (2147, 2166), False, 'from drymass.cli import config, dialog\n'), ((2444, 2476), 'drymass.cli.config.ConfigFile', 'config.ConfigFile', ([], {'path': 'path_out'}), '(path=path_out)\n', (2461, 2476), False, 'from drymass.cli import config, dialog\n'), ((2678, 2725), 'drymass.cli.dialog.main', 'dialog.main', ([], {'path': 'path_in', 'profile': 'path_profile'}), '(path=path_in, profile=path_profile)\n', (2689, 2725), False, 'from drymass.cli import config, dialog\n'), ((750, 812), 'qpimage.QPSeries', 'qpimage.QPSeries', ([], {'h5file': 'path_in', 'h5mode': '"""w"""', 'identifier': '"""tes"""'}), "(h5file=path_in, h5mode='w', identifier='tes')\n", (766, 812), False, 'import qpimage\n'), ((1084, 1111), 'drymass.cli.config.ConfigFile', 'config.ConfigFile', (['path_out'], {}), '(path_out)\n', (1101, 1111), False, 'from drymass.cli import config, dialog\n'), ((340, 355), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (349, 355), True, 'import numpy as np\n'), ((379, 394), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (388, 394), True, 'import numpy as np\n'), ((525, 541), 'numpy.roll', 'np.roll', (['pha', '(10)'], {}), '(pha, 10)\n', (532, 541), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.