code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import typing as T from abc import ABC import numpy as np import torch from .a2c import A2cAgent from .base.models import TrainingProgress, LearningStep, TrainingStep, TrainingParams, ReplayBufferEntry from ..environments import Environment class MonteCarloA2c(A2cAgent, ABC): def learn(self, entries: T.List[ReplayBufferEntry]) -> None: batch = self.form_learning_batch(entries) batch.r = batch.r.unsqueeze(1) action_probabilities, state_values = self.actor_critic(batch.s) advantages: torch.Tensor = (batch.r - state_values.clone().detach()).squeeze(1) chosen_action_log_probabilities: torch.Tensor = torch.stack( [torch.distributions.Categorical(p).log_prob(a) for p, a in zip(action_probabilities, batch.a)]) actor_loss: torch.Tensor = -chosen_action_log_probabilities * advantages * batch.weight critic_loss: torch.Tensor = self.loss_f(state_values, batch.r) * batch.weight loss = (actor_loss + critic_loss).mean() self.actor_critic_optimizer.zero_grad() loss.backward() self.actor_critic_optimizer.step() self.call_learn_callbacks(LearningStep(entries, [v.item() for v in state_values], [v.item() for v in batch.r])) def train(self, env: Environment, tp: TrainingParams = None) -> None: if tp is None: tp = self.default_training_params self.health_check(env) self.accumulate_rewards = False s = env.reset() i = 0 episode = 1 steps_survived = 0 accumulated_reward = 0 steps_record: T.List[ReplayBufferEntry] = [] while True: estimated_rewards = self.act(s) def choosing_f(x): return torch.distributions.Categorical(torch.tensor(x)).sample().item() a = self.ex_choose(list(estimated_rewards), choosing_f) s_, r, final = env.step(a) steps_record.append(ReplayBufferEntry(s, s_, a, r, final)) accumulated_reward += r s = s_ self.call_step_callbacks(TrainingStep(i, episode)) if i % self.agent_params.learn_every == 0 and i != 0 and self.rp_get_length() >= tp.batch_size: batch = self.rp_sample(tp.batch_size) self.learn(batch) if final: discounted_r = 0 reward_array = np.zeros((len(steps_record))) for j, step in enumerate(steps_record[::-1]): discounted_r = step.r + self.agent_params.gamma * discounted_r step.r = discounted_r reward_array[j] = discounted_r mean, std, eps = reward_array.mean(), reward_array.std(), np.finfo(np.float32).eps.item() for step in steps_record: step.r = (step.r - mean) / (std + eps) self.rp_add(step) training_progress = TrainingProgress(i, episode, steps_survived, accumulated_reward) must_exit = self.call_progress_callbacks(training_progress) if episode >= tp.episodes or must_exit: return accumulated_reward = 0 steps_survived = 0 episode += 1 steps_record.clear() s = env.reset() else: steps_survived += 1 env.render() i += 1
[ "numpy.finfo", "torch.tensor", "torch.distributions.Categorical" ]
[((679, 713), 'torch.distributions.Categorical', 'torch.distributions.Categorical', (['p'], {}), '(p)\n', (710, 713), False, 'import torch\n'), ((2717, 2737), 'numpy.finfo', 'np.finfo', (['np.float32'], {}), '(np.float32)\n', (2725, 2737), True, 'import numpy as np\n'), ((1760, 1775), 'torch.tensor', 'torch.tensor', (['x'], {}), '(x)\n', (1772, 1775), False, 'import torch\n')]
# -*- coding: utf-8 -*- # # ConnPlotter.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. # ConnPlotter --- A Tool to Generate Connectivity Pattern Matrices """ ConnPlotter is a tool to create connectivity pattern tables. For background on ConnPlotter, please see <NAME> and <NAME>. Connection Pattern Tables: A new way to visualize connectivity in neuronal network models. Frontiers in Neuroinformatics 3:39 (2010) doi: 10.3389/neuro.11.039.2009 Example: # code creating population and connection lists from ConnPlotter import ConnectionPattern, SynType # Case A: All connections have the same "synapse_model". # # Connections with weight < 0 are classified as excitatory, # weight > 0 are classified as inhibitory. # Each sender must make either excitatory or inhibitory connection, # not both. When computing totals, excit/inhib connections are # weighted with +-1. pattern = ConnectionPattern(layerList, connList) # Case B: All connections have the same "synapse_model", but violate Dale's law # # Connections with weight < 0 are classified as excitatory, # weight > 0 are classified as inhibitory. # A single sender may have excitatory and inhibitory connections. # When computing totals, excit/inhib connections are # weighted with +-1. pattern = ConnectionPattern(layerList, connList, synTypes=(((SynType('exc', 1.0, 'b'), SynType('inh', -1.0, 'r')),))) # Case C: Synapse models are "AMPA", "NMDA", "GABA_A", "GABA_B". # # Connections are plotted by synapse model, with AMPA and NMDA # on the top row, GABA_A and GABA_B in the bottom row when # combining by layer. Senders must either have AMPA and NMDA or # GABA_A and GABA_B synapses, but not both. When computing totals, # AMPA and NMDA connections are weighted with +1, GABA_A and GABA_B # with -1. pattern = ConnectionPattern(layerList, connList) # Case D: Explicit synapse types. # # If your network model uses other synapse types, or you want to use # other weighting factors when computing totals, or you want different # colormaps, you must specify synapse type information explicitly for # ALL synase models in your network. For each synapse model, you create # a # # SynType(name, tweight, cmap) # # object, where "name" is the synapse model name, "tweight" the weight # to be given to the type when computing totals (usually >0 for excit, # <0 for inhib synapses), and "cmap" the "colormap": if may be a # matplotlib.colors.Colormap instance or any valid matplotlib color # specification; in the latter case, as colormap will be generated # ranging from white to the given color. # Synapse types are passed as a tuple of tuples. Synapses in a tuple form # a group. ConnPlotter assumes that a sender may make synapses with all # types in a single group, but never synapses with types from different # groups (If you group by transmitter, this simply reflects Dale's law). # When connections are aggregated by layer, each group is printed on one # row. pattern = ConnectionPattern(layerList, connList, synTypes = \ ((SynType('Asyn', 1.0, 'orange'), SynType('Bsyn', 2.5, 'r'), SynType('Csyn', 0.5, (1.0, 0.5, 0.0))), # end first group (SynType('Dsyn', -1.5, matplotlib.pylab.cm.jet), SynType('Esyn', -3.2, '0.95')))) # See documentation of class ConnectionPattern for more options. # plotting the pattern # show connection kernels for all sender-target pairs and all synapse models pattern.plot() # combine synapses of all types for each sender-target pair # always used red-blue (inhib-excit) color scale pattern.plot(aggrSyns=True) # for each pair of sender-target layer pair, show sums for each synapse type pattern.plot(aggrGroups=True) # As mode layer, but combine synapse types. # always used red-blue (inhib-excit) color scale pattern.plot(aggrSyns=True, aggrGroups=True) # Show only synases of the selected type(s) pattern.plot(mode=('AMPA',)) pattern.plot(mode=('AMPA', 'GABA_A')) # use same color scales for all patches pattern.plot(globalColors=True) # manually specify limits for global color scale pattern.plot(globalColors=True, colorLimits=[0, 2.5]) # save to file(s) # NB: do not write to PDF directly, this seems to cause artifacts pattern.plot(file='net.png') pattern.plot(file=('net.eps','net.png')) # You can adjust some properties of the figure by changing the # default values in plotParams. # Experimentally, you can dump the connection pattern into a LaTeX table pattern.toLaTeX('pattern.tex', standalone=True) # Figure layout can be modified by changing the global variable plotParams. # Please see the documentation for class PlotParams for details. # Changes 30 June 2010: # - Singular layers (extent 0x0) are ignored as target layers. # The reason for this is so that single-generator "layers" can be # displayed as input. # Problems: # - singularity is not made clear visually # - This messes up the diagonal shading # - makes no sense to aggregate any longer """ # ---------------------------------------------------------------------------- from . import colormaps as cm import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import warnings __all__ = ['ConnectionPattern', 'SynType', 'plotParams', 'PlotParams'] # ---------------------------------------------------------------------------- # To do: # - proper testsuite # - layers of different sizes not handled properly # (find biggest layer extent in each direction, then center; # may run into problems with population label placement) # - clean up main # - color bars # - "bad color" should be configurable # - fix hack for colormaps import # - use generators where possible (eg kernels?) # ---------------------------------------------------------------------------- class SynType(object): """ Provide information about how synapse types should be rendered. A singly nested list of SynType objects can be passed to the ConnectionPattern constructor to specify layout and rendering info. """ def __init__(self, name, relweight, cmap): """ Arguments: name Name of synapse type (string, must be unique) relweight Relative weight of synapse type when aggregating across synapse types. Should be negative for inhibitory connections. cmap Either a matplotlib.colors.Colormap instance or a color specification. In the latter case, the colormap will be built from white to the color given. Thus, the color should be fully saturated. Colormaps should have "set_bad(color='white')". """ self.name, self.relweight = name, relweight if isinstance(cmap, mpl.colors.Colormap): self.cmap = cmap else: self.cmap = cm.make_colormap(cmap) # ---------------------------------------------------------------------------- class PlotParams(object): """ Collects parameters governing plotting. Implemented using properties to ensure they are read-only. """ class Margins(object): """Width of outer margins, in mm.""" def __init__(self): """Set default values.""" self._left = 15.0 self._right = 10.0 self._top = 10.0 self._bottom = 10.0 self._colbar = 10.0 @property def left(self): return self._left @left.setter def left(self, l): self._left = float(l) @property def right(self): return self._right @right.setter def right(self, r): self._right = float(r) @property def top(self): return self._top @top.setter def top(self, t): self._top = float(t) @property def bottom(self): return self._bottom @bottom.setter def bottom(self, b): self._bottom = float(b) @property def colbar(self): return self._colbar @colbar.setter def colbar(self, b): self._colbar = float(b) def __init__(self): """Set default values""" self._n_kern = 100 self._patch_size = 20.0 # 20 mm self._layer_bg = {'super': '0.9', 'diag': '0.8', 'sub': '0.9'} self._layer_font = mpl.font_manager.FontProperties(size='large') self._layer_orient = {'sender': 'horizontal', 'target': 'horizontal'} self._pop_font = mpl.font_manager.FontProperties(size='small') self._pop_orient = {'sender': 'horizontal', 'target': 'horizontal'} self._lgd_tick_font = mpl.font_manager.FontProperties(size='x-small') self._lgd_title_font = mpl.font_manager.FontProperties(size='xx-small') self._lgd_ticks = None self._lgd_tick_fmt = None self._lgd_location = None self._cbwidth = None self._cbspace = None self._cbheight = None self._cboffset = None self._z_layer = 25 self._z_pop = 50 self._z_conn = 100 self.margins = self.Margins() def reset(self): """ Reset to default values. """ self.__init__() @property def n_kern(self): """Sample long kernel dimension at N_kernel points.""" return self._n_kern @n_kern.setter def n_kern(self, n): if n <= 0: raise ValueError('n_kern > 0 required') self._n_kern = n @property def patch_size(self): """Length of the longest edge of the largest patch, in mm.""" return self._patch_size @patch_size.setter def patch_size(self, sz): if sz <= 0: raise ValueError('patch_size > 0 required') self._patch_size = sz @property def layer_bg(self): """ Dictionary of colors for layer background. Entries "super", "diag", "sub". Each entry can be set to any valid color specification. If just a color is given, create dict by brightening/dimming. """ return self._layer_bg @layer_bg.setter def layer_bg(self, bg): if isinstance(bg, dict): if set(bg.keys()) != set(('super', 'diag', 'sub')): raise ValueError( 'Background dict must have keys "super", "diag", "sub"') for bgc in bg.values(): if not mpl.colors.is_color_like(bgc): raise ValueError('Entries in background dict must be ' + 'valid color specifications.') self._layer_bg = bg elif not mpl.colors.is_color_like(bg): raise ValueError( 'layer_bg must be dict or valid color specification.') else: # is color like rgb = mpl.colors.colorConverter.to_rgb(bg) self._layer_bg = {'super': [1.1 * c for c in rgb], 'diag': rgb, 'sub': [0.9 * c for c in rgb]} @property def layer_font(self): """ Font to use for layer labels. Can be set to a matplotlib.font_manager.FontProperties instance. """ return self._layer_font @layer_font.setter def layer_font(self, font): if not isinstance(font, mpl.font_manager.FontProperties): raise ValueError('layer_font must be a ' + 'matplotlib.font_manager.FontProperties instance') self._layer_font = font @property def layer_orientation(self): """ Orientation of layer labels. Dictionary with orientation of sender and target labels. Orientation is either 'horizontal', 'vertial', or a value in degrees. When set to a single string or number, this value is used for both sender and target labels. """ return self._layer_orient @layer_orientation.setter def layer_orientation(self, orient): if isinstance(orient, (str, float, int)): tmp = {'sender': orient, 'target': orient} elif isinstance(orient, dict): tmp = self._layer_orient tmp.update(orient) else: raise ValueError( 'Orientation ust be set to dict, string or number.') if len(tmp) > 2: raise ValueError('Orientation dictionary can only contain keys ' + '"sender" and "target".') self._layer_orient = tmp @property def pop_font(self): """ Font to use for population labels. Can be set to a matplotlib.font_manager.FontProperties instance. """ return self._pop_font @pop_font.setter def pop_font(self, font): if not isinstance(font, mpl.font_manager.FontProperties): raise ValueError('pop_font must be a ' + 'matplotlib.font_manager.FontProperties instance') self._pop_font = font @property def pop_orientation(self): """ Orientation of population labels. Dictionary with orientation of sender and target labels. Orientation is either 'horizontal', 'vertial', or a value in degrees. When set to a single string or number, this value is used for both sender and target labels. """ return self._pop_orient @pop_orientation.setter def pop_orientation(self, orient): if isinstance(orient, (str, float, int)): tmp = {'sender': orient, 'target': orient} elif isinstance(orient, dict): tmp = self._pop_orient tmp.update(orient) else: raise ValueError( 'Orientation ust be set to dict, string or number.') if len(tmp) > 2: raise ValueError('Orientation dictionary can only contain keys ' + '"sender" and "target".') self._pop_orient = tmp @property def legend_tick_font(self): """ FontProperties for legend (colorbar) ticks. """ return self._lgd_tick_font @legend_tick_font.setter def legend_tick_font(self, font): if not isinstance(font, mpl.font_manager.FontProperties): raise ValueError('legend_tick_font must be a ' + 'matplotlib.font_manager.FontProperties instance') self._lgd_tick_font = font @property def legend_title_font(self): """ FontProperties for legend (colorbar) titles. """ return self._lgd_title_font @legend_title_font.setter def legend_title_font(self, font): if not isinstance(font, mpl.font_manager.FontProperties): raise ValueError('legend_title_font must be a ' + 'matplotlib.font_manager.FontProperties instance') self._lgd_title_font = font @property def legend_ticks(self): """ Ordered list of values at which legend (colorbar) ticks shall be set. """ return self._lgd_ticks @legend_ticks.setter def legend_ticks(self, ticks): self._lgd_ticks = ticks @property def legend_tick_format(self): """ C-style format string for legend (colorbar) tick marks. """ return self._lgd_tick_fmt @legend_tick_format.setter def legend_tick_format(self, tickfmt): self._lgd_tick_fmt = tickfmt @property def legend_location(self): """ If set to 'top', place legend label above colorbar, if None, to the left. """ return self._lgd_location @legend_location.setter def legend_location(self, loc): self._lgd_location = loc @property def cbwidth(self): """ Width of single colorbar, relative to figure width. """ return self._cbwidth @cbwidth.setter def cbwidth(self, cbw): self._cbwidth = cbw @property def cbheight(self): """ Height of colorbar, relative to margins.colbar """ return self._cbheight @cbheight.setter def cbheight(self, cbh): self._cbheight = cbh @property def cbspace(self): """ Spacing between colorbars, relative to figure width. """ return self._cbspace @cbspace.setter def cbspace(self, cbs): self._cbspace = cbs @property def cboffset(self): """ Left offset of colorbar, relative to figure width. """ return self._cboffset @cboffset.setter def cboffset(self, cbo): self._cboffset = cbo @property def z_layer(self): """Z-value for layer label axes.""" return self._z_layer @property def z_pop(self): """Z-value for population label axes.""" return self._z_pop @property def z_conn(self): """Z-value for connection kernel axes.""" return self._z_conn # ---------------------------------------------------------------------------- # plotting settings, default values plotParams = PlotParams() # ---------------------------------------------------------------------------- class ConnectionPattern(object): """ Connection pattern representation for plotting. When a ConnectionPattern is instantiated, all connection kernels are pre-computed. They can later be plotted in various forms by calling the plot() method. The constructor requires layer and connection lists: ConnectionPattern(layerList, connList, synTypes, **kwargs) The layerList is used to: - determine the size of patches - determine the block structure All other information is taken from the connList. Information about synapses is inferred from the connList. The following keyword arguments can also be given: poporder : Population order. A dictionary mapping population names to numbers; populations will be sorted in diagram in order of increasing numbers. Otherwise, they are sorted alphabetically. intensity: 'wp' - use weight * probability (default) 'p' - use probability alone 'tcd' - use total charge deposited * probability requires mList and Vmem; per v 0.7 only supported for ht_neuron. mList : model list; required for 'tcd' Vmem : membrane potential; required for 'tcd' """ # ------------------------------------------------------------------------ class _LayerProps(object): """ Information about layer. """ def __init__(self, name, extent): """ name : name of layer extent: spatial extent of the layer """ self.name = name self.ext = extent self.singular = extent[0] == 0.0 and extent[1] == 0.0 # ------------------------------------------------------------------------ class _SynProps(object): """ Information on how to plot patches for a synapse type. """ def __init__(self, row, col, tweight, cmap, idx): """ row, col: Position of synapse in grid of synapse patches, from 0,0 tweight : weight used when adding kernels for different synapses cmap : colormap for synapse type (matplotlib.colors.Colormap) idx : linear index, used to order colorbars in figure """ self.r, self.c = row, col self.tw = tweight self.cmap = cmap self.index = idx # -------------------------------------------------------------------- class _PlotKern(object): """ Representing object ready for plotting. """ def __init__(self, sl, sn, tl, tn, syn, kern): """ sl : sender layer sn : sender neuron/population tl : target layer tn : target neuron/population syn : synapse model kern: kernel values (numpy masked array) All arguments but kern are strings. """ self.sl = sl self.sn = sn self.tl = tl self.tn = tn self.syn = syn self.kern = kern # ------------------------------------------------------------------------ class _Connection(object): def __init__(self, conninfo, layers, synapses, intensity, tcd, Vmem): """ Arguments: conninfo: list of connection info entries: (sender,target,conn_dict) layers : list of _LayerProps objects synapses: list of _SynProps objects intensity: 'wp', 'p', 'tcd' tcd : tcd object Vmem : reference membrane potential for tcd calculations """ self._intensity = intensity # get source and target layer self.slayer, self.tlayer = conninfo[:2] lnames = [l.name for l in layers] if self.slayer not in lnames: raise Exception('Unknown source layer "%s".' % self.slayer) if self.tlayer not in lnames: raise Exception('Unknown target layer "%s".' % self.tlayer) # if target layer is singular (extent==(0,0)), # we do not create a full object self.singular = False for l in layers: if l.name == self.tlayer and l.singular: self.singular = True return # see if we connect to/from specific neuron types cdict = conninfo[2] if 'sources' in cdict: if tuple(cdict['sources'].keys()) == ('model',): self.snrn = cdict['sources']['model'] else: raise ValueError( 'Can only handle sources in form {"model": ...}') else: self.snrn = None if 'targets' in cdict: if tuple(cdict['targets'].keys()) == ('model',): self.tnrn = cdict['targets']['model'] else: raise ValueError( 'Can only handle targets in form {"model": ...}') else: self.tnrn = None # now get (mean) weight, we need this if we classify # connections by sign of weight only try: self._mean_wght = _weighteval(cdict['weights']) except: raise ValueError('No or corrupt weight information.') # synapse model if sorted(synapses.keys()) == ['exc', 'inh']: # implicit synapse type, we ignore value of # 'synapse_model', it is for use by NEST only if self._mean_wght >= 0: self.synmodel = 'exc' else: self.synmodel = 'inh' else: try: self.synmodel = cdict['synapse_model'] if self.synmodel not in synapses: raise Exception('Unknown synapse model "%s".' % self.synmodel) except: raise Exception('Explicit synapse model info required.') # store information about connection try: self._mask = cdict['mask'] self._kern = cdict['kernel'] self._wght = cdict['weights'] # next line presumes only one layer name will match self._textent = [tl.ext for tl in layers if tl.name == self.tlayer][0] if intensity == 'tcd': self._tcd = tcd(self.synmodel, self.tnrn, Vmem) else: self._tcd = None except: raise Exception('Corrupt connection dictionary') # prepare for lazy evaluation self._kernel = None # -------------------------------------------------------------------- @property def keyval(self): """ Return key and _Connection as tuple. Useful to create dictionary via list comprehension. """ if self.singular: return (None, self) else: return ((self.slayer, self.snrn, self.tlayer, self.tnrn, self.synmodel), self) # -------------------------------------------------------------------- @property def kernval(self): """Kernel value, as masked array.""" if self._kernel is None: self._kernel = _evalkernel(self._mask, self._kern, self._mean_wght, self._textent, self._intensity, self._tcd) return self._kernel # -------------------------------------------------------------------- @property def mask(self): """Dictionary describing the mask.""" return self._mask # -------------------------------------------------------------------- @property def kernel(self): """Dictionary describing the kernel.""" return self._kern # -------------------------------------------------------------------- @property def weight(self): """Dictionary describing weight distribution.""" return self._wght # -------------------------------------------------------------------- def matches(self, sl=None, sn=None, tl=None, tn=None, syn=None): """ Return True if all non-None arguments match. Arguments: sl : sender layer sn : sender neuron type tl : target layer tn : target neuron type syn: synapse type """ return ((sl is None or sl == self.slayer) and (sn is None or sn == self.snrn) and (tl is None or tl == self.tlayer) and (tn is None or tn == self.tnrn) and (syn is None or syn == self.synmodel)) # ------------------------------------------------------------------------ class _Patch(object): """ Represents a patch, i.e., an axes that will actually contain an imshow graphic of a connection kernel. The patch object contains the physical coordinates of the patch, as well as a reference to the actual Axes object once it is created. Also contains strings to be used as sender/target labels. Everything is based on a coordinate system looking from the top left corner down. """ # -------------------------------------------------------------------- def __init__(self, left, top, row, col, width, height, slabel=None, tlabel=None, parent=None): """ Arguments: left, top : Location of top-left corner row, col : row, column location in parent block width, height : Width and height of patch slabel, tlabel: Values for sender/target label parent : _Block to which _Patch/_Block belongs """ self.l, self.t, self.r, self.c = left, top, row, col self.w, self.h = width, height self.slbl, self.tlbl = slabel, tlabel self.ax = None self._parent = parent # -------------------------------------------------------------------- def _update_size(self, new_lr): """Update patch size by inspecting all children.""" if new_lr[0] < self.l: raise ValueError( "new_lr[0] = %f < l = %f" % (new_lr[0], self.l)) if new_lr[1] < self.t: raise ValueError( "new_lr[1] = %f < t = %f" % (new_lr[1], self.t)) self.w, self.h = new_lr[0] - self.l, new_lr[1] - self.t if self._parent: self._parent._update_size(new_lr) # -------------------------------------------------------------------- @property def tl(self): """Top left corner of the patch.""" return (self.l, self.t) # -------------------------------------------------------------------- @property def lr(self): """Lower right corner of the patch.""" return (self.l + self.w, self.t + self.h) # -------------------------------------------------------------------- @property def l_patches(self): """Left edge of leftmost _Patch in _Block.""" if isinstance(self, ConnectionPattern._Block): return min([e.l_patches for e in _flattened(self.elements)]) else: return self.l # -------------------------------------------------------------------- @property def t_patches(self): """Top edge of topmost _Patch in _Block.""" if isinstance(self, ConnectionPattern._Block): return min([e.t_patches for e in _flattened(self.elements)]) else: return self.t # -------------------------------------------------------------------- @property def r_patches(self): """Right edge of rightmost _Patch in _Block.""" if isinstance(self, ConnectionPattern._Block): return max([e.r_patches for e in _flattened(self.elements)]) else: return self.l + self.w # -------------------------------------------------------------------- @property def b_patches(self): """Bottom edge of lowest _Patch in _Block.""" if isinstance(self, ConnectionPattern._Block): return max([e.b_patches for e in _flattened(self.elements)]) else: return self.t + self.h # -------------------------------------------------------------------- @property def location(self): if self.r < self.c: return 'super' elif self.r == self.c: return 'diag' else: return 'sub' # ------------------------------------------------------------------------ class _Block(_Patch): """ Represents a block of patches. A block is initialized with its top left corner and is then built row-wise downward and column-wise to the right. Rows are added by block.newRow(2.0, 1.5) where 2.0 is the space between rows, 1.5 the space between the first row. Elements are added to a row by el = block.newElement(1.0, 0.6, 's', 't') el = block.newElement(1.0, 0.6, 's', 't', size=[2.0, 3.0]) The first example adds a new _Block to the row. 1.0 is space between blocks, 0.6 space before the first block in a row. 's' and 't' are stored as slbl and tlbl (optional). If size is given, a _Patch with the given size is created. _Patch is atomic. newElement() returns the _Block or _Patch created. """ # -------------------------------------------------------------------- def __init__(self, left, top, row, col, slabel=None, tlabel=None, parent=None): ConnectionPattern._Patch.__init__(self, left, top, row, col, 0, 0, slabel, tlabel, parent) self.elements = [] self._row_top = None # top of current row self._row = 0 self._col = 0 # -------------------------------------------------------------------- def newRow(self, dy=0.0, dynew=0.0): """ Open new row of elements. Arguments: dy : vertical skip before new row dynew: vertical skip if new row is first row """ if self.elements: # top of row is bottom of block so far + dy self._row_top = self.lr[1] + dy else: # place relative to top edge of parent self._row_top = self.tl[1] + dynew self._row += 1 self._col = 0 self.elements.append([]) # -------------------------------------------------------------------- def newElement(self, dx=0.0, dxnew=0.0, slabel=None, tlabel=None, size=None): """ Append new element to last row. Creates _Block instance if size is not given, otherwise _Patch. Arguments: dx : horizontal skip before new element dxnew : horizontal skip if new element is first slabel: sender label (on y-axis) tlabel: target label (on x-axis) size : size of _Patch to create Returns: Created _Block or _Patch. """ assert (self.elements) if self.elements[-1]: # left edge is right edge of block so far + dx col_left = self.lr[0] + dx else: # place relative to left edge of parent col_left = self.tl[0] + dxnew self._col += 1 if size is not None: elem = ConnectionPattern._Patch(col_left, self._row_top, self._row, self._col, size[0], size[1], slabel, tlabel, self) else: elem = ConnectionPattern._Block(col_left, self._row_top, self._row, self._col, slabel, tlabel, self) self.elements[-1].append(elem) self._update_size(elem.lr) return elem # -------------------------------------------------------------------- def addMargin(self, rmarg=0.0, bmarg=0.0): """Extend block by margin to right and bottom.""" if rmarg < 0.0: raise ValueError('rmarg must not be negative!') if bmarg < 0.0: raise ValueError('bmarg must not be negative!') lr = self.lr self._update_size((lr[0] + rmarg, lr[1] + bmarg)) # ------------------------------------------------------------------------ def _prepareAxes(self, mode, showLegend): """ Prepare information for all axes, but do not create the actual axes yet. mode: one of 'detailed', 'by layer', 'totals' """ # parameters for figure, all quantities are in mm patchmax = plotParams.patch_size # length of largest patch dimension # actual parameters scaled from default patchmax = 20mm lmargin = plotParams.margins.left tmargin = plotParams.margins.top rmargin = plotParams.margins.right bmargin = plotParams.margins.bottom cbmargin = plotParams.margins.colbar blksep = 3. / 20. * patchmax # distance between blocks popsep = 2. / 20. * patchmax # distance between populations synsep = 0.5 / 20. * patchmax # distance between synapse types # find maximal extents of individual patches, horizontal and vertical maxext = max(_flattened([l.ext for l in self._layers])) patchscale = patchmax / float(maxext) # determines patch size # obtain number of synaptic patches per population pair # maximum column across all synapse types, same for rows nsyncols = max([s.c for s in self._synAttr.values()]) + 1 nsynrows = max([s.r for s in self._synAttr.values()]) + 1 # dictionary mapping into patch-axes, to they can be found later self._patchTable = {} # set to store all created patches to avoid multiple # creation of patches at same location axset = set() # create entire setup, top-down self._axes = self._Block(lmargin, tmargin, 1, 1) for sl in self._layers: # get sorted list of populations for sender layer spops = sorted([p[1] for p in self._pops if p[0] == sl.name], key=lambda pn: self._poporder[pn]) self._axes.newRow(blksep, 0.0) for tl in self._layers: # ignore singular target layers if tl.singular: continue # get sorted list of populations for target layer tpops = sorted([p[1] for p in self._pops if p[0] == tl.name], key=lambda pn: self._poporder[pn]) # compute size for patches patchsize = patchscale * np.array(tl.ext) block = self._axes.newElement(blksep, 0.0, sl.name, tl.name) if mode == 'totals': # single patch block.newRow(popsep, popsep / 2.) p = block.newElement(popsep, popsep / 2., size=patchsize) self._patchTable[(sl.name, None, tl.name, None, None)] = p elif mode == 'layer': # We loop over all rows and columns in the synapse patch # grid. For each (r,c), we find the pertaining synapse name # by reverse lookup in the _synAttr dictionary. This is # inefficient, but should not be too costly overall. But we # must create the patches in the order they are placed. # NB: We must create also those block.newElement() that are # not registered later, since block would otherwise not # skip over the unused location. for r in range(nsynrows): block.newRow(synsep, popsep / 2.) for c in range(nsyncols): p = block.newElement(synsep, popsep / 2., size=patchsize) smod = [k for k, s in self._synAttr.items() if s.r == r and s.c == c] if smod: assert (len(smod) == 1) self._patchTable[(sl.name, None, tl.name, None, smod[0])] = p elif mode == 'population': # one patch per population pair for sp in spops: block.newRow(popsep, popsep / 2.) for tp in tpops: pblk = block.newElement(popsep, popsep / 2., sp, tp) pblk.newRow(synsep, synsep / 2.) self._patchTable[(sl.name, sp, tl.name, tp, None)] = \ pblk.newElement(synsep, blksep / 2., size=patchsize) else: # detailed presentation of all pops for sp in spops: block.newRow(popsep, popsep / 2.) for tp in tpops: pblk = block.newElement(popsep, popsep / 2., sp, tp) pblk.newRow(synsep, synsep / 2.) # Find all connections with matching properties # all information we need here is synapse model. # We store this in a dictionary mapping synapse # patch column to synapse model, for use below. syns = dict( [(self._synAttr[c.synmodel].c, c.synmodel) for c in _flattened(self._cTable.values()) if c.matches(sl.name, sp, tl.name, tp)]) # create all synapse patches for n in range(nsyncols): # Do not duplicate existing axes. if (sl.name, sp, tl.name, tp, n) in axset: continue # Create patch. We must create also such # patches that do not have synapses, since # spacing would go wrong otherwise. p = pblk.newElement(synsep, 0.0, size=patchsize) # if patch represents existing synapse, # register if n in syns: self._patchTable[(sl.name, sp, tl.name, tp, syns[n])] = p block.addMargin(popsep / 2., popsep / 2.) self._axes.addMargin(rmargin, bmargin) if showLegend: self._axes.addMargin(0, cbmargin) # add color bar at bottom figwidth = self._axes.lr[0] - self._axes.tl[ 0] - rmargin # keep right marg out of calc if mode == 'totals' or mode == 'population': # single patch at right edge, 20% of figure if plotParams.cbwidth: lwidth = plotParams.cbwidth * figwidth else: lwidth = 0.2 * figwidth if lwidth > 100.0: # colorbar shouldn't be wider than 10cm lwidth = 100.0 lheight = (plotParams.cbheight * cbmargin if plotParams.cbheight else 0.3 * cbmargin) if plotParams.legend_location is None: cblift = 0.9 * cbmargin else: cblift = 0.7 * cbmargin self._cbPatches = self._Patch(self._axes.tl[0], self._axes.lr[1] - cblift, None, None, lwidth, lheight) else: # one patch per synapse type, 20% of figure or less # we need to get the synapse names in ascending order # of synapse indices snames = [s[0] for s in sorted([(k, v) for k, v in self._synAttr.items()], key=lambda kv: kv[1].index) ] snum = len(snames) if plotParams.cbwidth: lwidth = plotParams.cbwidth * figwidth if plotParams.cbspace: lstep = plotParams.cbspace * figwidth else: lstep = 0.5 * lwidth else: if snum < 5: lwidth = 0.15 * figwidth lstep = 0.1 * figwidth else: lwidth = figwidth / (snum + 1.0) lstep = (figwidth - snum * lwidth) / (snum - 1.0) if lwidth > 100.0: # colorbar shouldn't be wider than 10cm lwidth = 100.0 lstep = 30.0 lheight = (plotParams.cbheight * cbmargin if plotParams.cbheight else 0.3 * cbmargin) if plotParams.cboffset is not None: offset = plotParams.cboffset else: offset = lstep if plotParams.legend_location is None: cblift = 0.9 * cbmargin else: cblift = 0.7 * cbmargin self._cbPatches = {} for j in range(snum): self._cbPatches[snames[j]] = \ self._Patch( self._axes.tl[0] + offset + j * (lstep + lwidth), self._axes.lr[1] - cblift, None, None, lwidth, lheight) # ------------------------------------------------------------------------ def _scaledBox(self, p): """Scaled axes rectangle for patch, reverses y-direction.""" xsc, ysc = self._axes.lr return self._figscale * np.array( [p.l / xsc, 1 - (p.t + p.h) / ysc, p.w / xsc, p.h / ysc]) # ------------------------------------------------------------------------ def _scaledBoxNR(self, p): """Scaled axes rectangle for patch, does not reverse y-direction.""" xsc, ysc = self._axes.lr return self._figscale * np.array( [p.l / xsc, p.t / ysc, p.w / xsc, p.h / ysc]) # ------------------------------------------------------------------------ def _configSynapses(self, cList, synTypes): """Configure synapse information based on connections and user info.""" # compile information on synapse types and weights synnames = set(c[2]['synapse_model'] for c in cList) synweights = set(_weighteval(c[2]['weights']) for c in cList) # set up synTypes for all pre-defined cases if synTypes: # check if there is info for all synapse types stnames = _flattened([[s.name for s in r] for r in synTypes]) if len(stnames) != len(set(stnames)): raise ValueError( 'Names of synapse types in synTypes must be unique!') if len(synnames) > 1 and not synnames.issubset(set(stnames)): raise ValueError('synTypes must provide information about' + 'all synapse types.') elif len(synnames) == 1: # only one synapse type used if min(synweights) >= 0: # all weights positive synTypes = ((SynType('exc', 1.0, 'red'),),) elif max(synweights) <= 0: # all weights negative synTypes = ((SynType('inh', -1.0, 'blue'),),) else: # positive and negative weights, assume Dale holds synTypes = ((SynType('exc', 1.0, 'red'),), (SynType('inh', -1.0, 'blue'),)) elif synnames == set(['AMPA', 'GABA_A']): # only AMPA and GABA_A synTypes = ((SynType('AMPA', 1.0, 'red'),), (SynType('GABA_A', -1.0, 'blue'),)) elif synnames.issubset(set(['AMPA', 'NMDA', 'GABA_A', 'GABA_B'])): synTypes = ((SynType('AMPA', 1.0, 'red'), SynType('NMDA', 1.0, 'orange'),), (SynType('GABA_A', -1.0, 'blue'), SynType('GABA_B', -1.0, 'purple'),)) else: raise ValueError('Connection list contains unknown synapse ' + 'models; synTypes required.') # now build _synAttr by assigning blocks to rows self._synAttr = {} row = 0 ctr = 0 for sgroup in synTypes: col = 0 for stype in sgroup: self._synAttr[stype.name] = self._SynProps(row, col, stype.relweight, stype.cmap, ctr) col += 1 ctr += 1 row += 1 # ------------------------------------------------------------------------ def __init__(self, lList, cList, synTypes=None, intensity='wp', mList=None, Vmem=None, poporder=None): """ lList : layer list cList : connection list synTypes : nested list of synapse types intensity: 'wp' - weight * probability 'p' - probability 'tcd' - |total charge deposited| * probability requires mList; currently only for ht_model proper results only if Vmem within reversal potentials mList : model list; only needed with 'tcd' Vmem : reference membrane potential for 'tcd' poporder : dictionary mapping population names to numbers; populations will be sorted in diagram in order of increasing numbers. """ # extract layers to dict mapping name to extent self._layers = [self._LayerProps(l[0], l[1]['extent']) for l in lList] # ensure layer names are unique lnames = [l.name for l in self._layers] if len(lnames) != len(set(lnames)): raise ValueError('Layer names must be unique.') # set up synapse attributes self._configSynapses(cList, synTypes) # if tcd mode, build tcd representation if intensity != 'tcd': tcd = None else: assert (mList) from . import tcd_nest tcd = tcd_nest.TCD(mList) # Build internal representation of connections. # This representation contains one entry for each sender pop, # target pop, synapse type tuple. Creating the connection object # implies computation of the kernel. # Several connection may agree in all properties, these need to be # added here. Therefore, we need to build iteratively and store # everything in a dictionary, so we can find early instances. self._cTable = {} for conn in cList: key, val = self._Connection(conn, self._layers, self._synAttr, intensity, tcd, Vmem).keyval if key: if key in self._cTable: self._cTable[key].append(val) else: self._cTable[key] = [val] # number of layers self._nlyr = len(self._layers) # compile list of populations, list(set()) makes list unique self._pops = list( set(_flattened([[(c.slayer, c.snrn), (c.tlayer, c.tnrn)] for c in _flattened(self._cTable.values())]))) self._npop = len(self._pops) # store population ordering; if not given, use alphabetical ordering # also add any missing populations alphabetically at end # layers are ignored # create alphabetically sorted list of unique population names popnames = sorted(list(set([p[1] for p in self._pops])), key=lambda x: x if x is not None else "") if poporder: self._poporder = poporder next = max(self._poporder.values()) + 1 # next free sorting index else: self._poporder = {} next = 0 for pname in popnames: if pname not in self._poporder: self._poporder[pname] = next next += 1 # compile list of synapse types self._synTypes = list( set([c.synmodel for c in _flattened(self._cTable.values())])) # ------------------------------------------------------------------------ def plot(self, aggrGroups=False, aggrSyns=False, globalColors=False, colorLimits=None, showLegend=True, selectSyns=None, file=None, fixedWidth=None): """ Plot connection pattern. By default, connections between any pair of populations are plotted on the screen, with separate color scales for all patches. Arguments: aggrGroups If True, aggregate projections with the same synapse type and the same source and target groups (default: False) aggrSyns If True, aggregate projections with the same synapse model (default: False) globalColors If True, use global color scale, otherwise local (default: False) colorLimits If given, must be two element vector for lower and upper limits of color scale. Implies globalColors (default: None) showLegend If True, show legend below CPT (default: True). selectSyns If tuple of synapse models, show only connections of the give types. Cannot be combined with aggregation. file If given, save plot to given file name; file may also be a tuple of file names, the figure will then be saved to all files. This may be useful if you want to save the same figure in several formats. fixedWidth Figure will be scaled to this width in mm by changing patch size. Returns: kern_min, kern_max Minimal and maximal values of kernels, with kern_min <= 0, kern_max >= 0. Output: figure created """ # translate new to old paramter names (per v 0.5) normalize = globalColors if colorLimits: normalize = True if selectSyns: if aggrPops or aggrSyns: raise ValueError( 'selectSyns cannot be combined with aggregation.') selected = selectSyns mode = 'select' elif aggrGroups and aggrSyns: mode = 'totals' elif aggrGroups and not aggrSyns: mode = 'layer' elif aggrSyns and not aggrGroups: mode = 'population' else: mode = None if mode == 'layer': # reduce to dimensions sender layer, target layer, synapse type # add all kernels agreeing on these three attributes plotKerns = [] for slayer in self._layers: for tlayer in self._layers: for synmodel in self._synTypes: kerns = [c.kernval for c in _flattened(self._cTable.values()) if c.matches(sl=slayer.name, tl=tlayer.name, syn=synmodel)] if len(kerns) > 0: plotKerns.append( self._PlotKern(slayer.name, None, tlayer.name, None, synmodel, _addKernels(kerns))) elif mode == 'population': # reduce to dimensions sender layer, target layer # all all kernels, weighting according to synapse type plotKerns = [] for spop in self._pops: for tpop in self._pops: kerns = [self._synAttr[c.synmodel].tw * c.kernval for c in _flattened(self._cTable.values()) if c.matches(sl=spop[0], sn=spop[1], tl=tpop[0], tn=tpop[1])] if len(kerns) > 0: plotKerns.append( self._PlotKern(spop[0], spop[1], tpop[0], tpop[1], None, _addKernels(kerns))) elif mode == 'totals': # reduce to dimensions sender layer, target layer # all all kernels, weighting according to synapse type plotKerns = [] for slayer in self._layers: for tlayer in self._layers: kerns = [self._synAttr[c.synmodel].tw * c.kernval for c in _flattened(self._cTable.values()) if c.matches(sl=slayer.name, tl=tlayer.name)] if len(kerns) > 0: plotKerns.append( self._PlotKern(slayer.name, None, tlayer.name, None, None, _addKernels(kerns))) elif mode == 'select': # copy only those kernels that have the requested synapse type, # no dimension reduction # We need to sum all kernels in the list for a set of attributes plotKerns = [ self._PlotKern(clist[0].slayer, clist[0].snrn, clist[0].tlayer, clist[0].tnrn, clist[0].synmodel, _addKernels([c.kernval for c in clist])) for clist in self._cTable.values() if clist[0].synmodel in selected] else: # copy all # We need to sum all kernels in the list for a set of attributes plotKerns = [ self._PlotKern(clist[0].slayer, clist[0].snrn, clist[0].tlayer, clist[0].tnrn, clist[0].synmodel, _addKernels([c.kernval for c in clist])) for clist in self._cTable.values()] self._prepareAxes(mode, showLegend) if fixedWidth: margs = plotParams.margins.left + plotParams.margins.right if fixedWidth <= margs: raise ValueError('Requested width must be less than ' + 'width of margins (%g mm)' % margs) currWidth = self._axes.lr[0] currPatchMax = plotParams.patch_size # store # compute required patch size plotParams.patch_size = ((fixedWidth - margs) / (currWidth - margs) * currPatchMax) # build new axes del self._axes self._prepareAxes(mode, showLegend) # restore patch size plotParams.patch_size = currPatchMax # create figure with desired size fsize = np.array(self._axes.lr) / 25.4 # convert mm to inches f = plt.figure(figsize=fsize, facecolor='w') # size will be rounded according to DPI setting, adjust fsize dpi = f.get_dpi() fsize = np.floor(fsize * dpi) / dpi # check that we got the correct size actsize = np.array([f.get_figwidth(), f.get_figheight()], dtype=float) if all(actsize == fsize): self._figscale = 1.0 # no scaling else: warnings.warn(""" WARNING: Figure shrunk on screen! The figure is shrunk to fit onto the screen. Please specify a different backend using the -d option to obtain full-size figures. Your current backend is: %s """ % mpl.get_backend()) plt.close(f) # determine scale: most shrunk dimension self._figscale = np.min(actsize / fsize) # create shrunk on-screen figure f = plt.figure(figsize=self._figscale * fsize, facecolor='w') # just ensure all is well now actsize = np.array([f.get_figwidth(), f.get_figheight()], dtype=float) # add decoration for block in _flattened(self._axes.elements): ax = f.add_axes(self._scaledBox(block), axisbg=plotParams.layer_bg[block.location], xticks=[], yticks=[], zorder=plotParams.z_layer) if hasattr(ax, 'frame'): ax.frame.set_visible(False) else: for sp in ax.spines.values(): # turn off axis lines, make room for frame edge sp.set_color('none') if block.l <= self._axes.l_patches and block.slbl: ax.set_ylabel(block.slbl, rotation=plotParams.layer_orientation['sender'], fontproperties=plotParams.layer_font) if block.t <= self._axes.t_patches and block.tlbl: ax.set_xlabel(block.tlbl, rotation=plotParams.layer_orientation['target'], fontproperties=plotParams.layer_font) ax.xaxis.set_label_position('top') # inner blocks for population labels if mode not in ('totals', 'layer'): for pb in _flattened(block.elements): if not isinstance(pb, self._Block): continue # should not happen ax = f.add_axes(self._scaledBox(pb), axisbg='none', xticks=[], yticks=[], zorder=plotParams.z_pop) if hasattr(ax, 'frame'): ax.frame.set_visible(False) else: for sp in ax.spines.values(): # turn off axis lines, make room for frame edge sp.set_color('none') if pb.l + pb.w >= self._axes.r_patches and pb.slbl: ax.set_ylabel(pb.slbl, rotation=plotParams.pop_orientation[ 'sender'], fontproperties=plotParams.pop_font) ax.yaxis.set_label_position('right') if pb.t + pb.h >= self._axes.b_patches and pb.tlbl: ax.set_xlabel(pb.tlbl, rotation=plotParams.pop_orientation[ 'target'], fontproperties=plotParams.pop_font) # determine minimum and maximum values across all kernels, # but set min <= 0, max >= 0 kern_max = max(0.0, max([np.max(kern.kern) for kern in plotKerns])) kern_min = min(0.0, min([np.min(kern.kern) for kern in plotKerns])) # determine color limits for plots if colorLimits: c_min, c_max = colorLimits # explicit values else: # default values for color limits # always 0 as lower limit so anything > 0 is non-white, # except when totals or populations c_min = None if mode in ('totals', 'population') else 0.0 c_max = None # use patch maximum as upper limit if normalize: # use overall maximum, at least 0 c_max = kern_max if aggrSyns: # use overall minimum, if negative, otherwise 0 c_min = kern_min # for c_max, use the larger of the two absolute values c_max = kern_max # if c_min is non-zero, use same color scale for neg values if c_min < 0: c_min = -c_max # Initialize dict storing sample patches for each synapse type for use # in creating color bars. We will store the last patch of any given # synapse type for reference. When aggrSyns, we have only one patch # type and store that. if not aggrSyns: samplePatches = dict( [(sname, None) for sname in self._synAttr.keys()]) else: # only single type of patches samplePatches = None for kern in plotKerns: p = self._patchTable[(kern.sl, kern.sn, kern.tl, kern.tn, kern.syn)] p.ax = f.add_axes(self._scaledBox(p), aspect='equal', xticks=[], yticks=[], zorder=plotParams.z_conn) p.ax.patch.set_edgecolor('none') if hasattr(p.ax, 'frame'): p.ax.frame.set_visible(False) else: for sp in p.ax.spines.values(): # turn off axis lines, make room for frame edge sp.set_color('none') if not aggrSyns: # we have synapse information -> not totals, a vals positive assert (kern.syn) assert (np.min(kern.kern) >= 0.0) # we may overwrite here, but this does not matter, we only need # some reference patch samplePatches[kern.syn] = p.ax.imshow(kern.kern, vmin=c_min, vmax=c_max, cmap=self._synAttr[ kern.syn].cmap) # , # interpolation='nearest') else: # we have totals, special color table and normalization # we may overwrite here, but this does not matter, we only need # some reference patch samplePatches = p.ax.imshow(kern.kern, vmin=c_min, vmax=c_max, cmap=cm.bluered, norm=cm.ZeroCenterNorm()) # interpolation='nearest') # Create colorbars at bottom of figure if showLegend: # FIXME: rewrite the function to avoid comparisons with None! f_min = float("-inf") if c_min is None else c_min f_max = float("-inf") if c_max is None else c_max # Do we have kernel values exceeding the color limits? if f_min <= kern_min and kern_max <= f_max: extmode = 'neither' elif f_min > kern_min and kern_max <= f_max: extmode = 'min' elif f_min <= kern_min and kern_max > f_max: extmode = 'max' else: extmode = 'both' if aggrSyns: cbax = f.add_axes(self._scaledBox(self._cbPatches)) # by default, use 4 ticks to avoid clogging # according to docu, we need a separate Locator object # for each axis. if plotParams.legend_ticks: tcks = plotParams.legend_ticks else: tcks = mpl.ticker.MaxNLocator(nbins=4) if normalize: # colorbar with freely settable ticks cb = f.colorbar(samplePatches, cax=cbax, orientation='horizontal', ticks=tcks, format=plotParams.legend_tick_format, extend=extmode) else: # colorbar with tick labels 'Exc', 'Inh' # we add the color bare here explicitly, so we get no # problems if the sample patch includes only pos or # only neg values cb = mpl.colorbar.ColorbarBase(cbax, cmap=cm.bluered, orientation='horizontal') cbax.set_xticks([0, 1]) cbax.set_xticklabels(['Inh', 'Exc']) cb.outline.set_linewidth(0.5) # narrower line around colorbar # fix font for ticks plt.setp(cbax.get_xticklabels(), fontproperties=plotParams.legend_tick_font) # no title in this case else: # loop over synapse types for syn in self._synAttr.keys(): cbax = f.add_axes(self._scaledBox(self._cbPatches[syn])) if plotParams.legend_location is None: cbax.set_ylabel( syn, fontproperties=plotParams.legend_title_font, rotation='horizontal') else: cbax.set_title( syn, fontproperties=plotParams.legend_title_font, rotation='horizontal') if normalize: # by default, use 4 ticks to avoid clogging # according to docu, we need a separate Locator object # for each axis. if plotParams.legend_ticks: tcks = plotParams.legend_ticks else: tcks = mpl.ticker.MaxNLocator(nbins=4) # proper colorbar cb = f.colorbar(samplePatches[syn], cax=cbax, orientation='horizontal', ticks=tcks, format=plotParams.legend_tick_format, extend=extmode) cb.outline.set_linewidth( 0.5) # narrower line around colorbar # fix font for ticks plt.setp(cbax.get_xticklabels(), fontproperties=plotParams.legend_tick_font) else: # just a solid color bar with no ticks cbax.set_xticks([]) cbax.set_yticks([]) # full-intensity color from color map cbax.set_axis_bgcolor(self._synAttr[syn].cmap(1.0)) # narrower border if hasattr(cbax, 'frame'): cbax.frame.set_linewidth(0.5) else: for sp in cbax.spines.values(): sp.set_linewidth(0.5) # save to file(s), use full size f.set_size_inches(fsize) if isinstance(file, (list, tuple)): for fn in file: f.savefig(fn) elif isinstance(file, str): f.savefig(file) f.set_size_inches(actsize) # reset size for further interactive work return kern_min, kern_max # ------------------------------------------------------------------------ def toLaTeX(self, file, standalone=False, enumerate=False, legend=True): """ Write connection table to file. Arguments: file output file name standalone create complete LaTeX file (default: False) enumerate enumerate connections (default: False) legend add explanation of functions used (default: True) """ lfile = open(file, 'w') if not lfile: raise Exception('Could not open file "%s"' % file) if standalone: lfile.write( r""" \documentclass[a4paper,american]{article} \usepackage[pdftex,margin=1in,centering, noheadfoot,a4paper]{geometry} \usepackage[T1]{fontenc} \usepackage[utf8]{inputenc} \usepackage{color} \usepackage{calc} \usepackage{tabularx} % autom. adjusts column width in tables \usepackage{multirow} % allows entries spanning several rows \usepackage{colortbl} % allows coloring tables \usepackage[fleqn]{amsmath} \setlength{\mathindent}{0em} \usepackage{mathpazo} \usepackage[scaled=.95]{helvet} \renewcommand\familydefault{\sfdefault} \renewcommand\arraystretch{1.2} \pagestyle{empty} % \hdr{ncols}{label}{title} % % Typeset header bar across table with ncols columns % with label at left margin and centered title % \newcommand{\hdr}[3]{% \multicolumn{#1}{|l|}{% \color{white}\cellcolor[gray]{0.0}% \textbf{\makebox[0pt]{#2}\hspace{0.5\linewidth}% \makebox[0pt][c]{#3}}% }% } \begin{document} """) lfile.write( r""" \noindent\begin{tabularx}{\linewidth}{%s|l|l|l|c|c|X|}\hline \hdr{%d}{}{Connectivity}\\\hline %s \textbf{Src} & \textbf{Tgt} & \textbf{Syn} & \textbf{Wght} & \textbf{Mask} & \textbf{Kernel} \\\hline """ % (('|r', 7, '&') if enumerate else ('', 6, ''))) # ensure sorting according to keys, gives some alphabetic sorting haveU, haveG = False, False cctr = 0 # connection counter for ckey in sorted(self._cTable.keys()): for conn in self._cTable[ckey]: cctr += 1 if enumerate: lfile.write('%d &' % cctr) # take care to escape _ in names such as GABA_A # also remove any pending '/None' lfile.write((r'%s/%s & %s/%s & %s' % (conn.slayer, conn.snrn, conn.tlayer, conn.tnrn, conn.synmodel)).replace('_', r'\_').replace( '/None', '')) lfile.write(' & \n') if isinstance(conn.weight, (int, float)): lfile.write(r'%g' % conn.weight) elif 'uniform' in conn.weight: cw = conn.weight['uniform'] lfile.write( r'$\mathcal{U}[%g, %g)$' % (cw['min'], cw['max'])) haveU = True else: raise ValueError( 'Unkown weight type "%s"' % conn.weight.__str__) lfile.write(' & \n') if 'circular' in conn.mask: lfile.write(r'$\leq %g$' % conn.mask['circular']['radius']) elif 'rectangular' in conn.mask: cmr = conn.mask['rectangular'] lfile.write( r"""$[(%+g, %+g), (%+g, %+g)]$""" % (cmr['lower_left'][0], cmr['lower_left'][1], cmr['upper_right'][0], cmr['upper_right'][1])) else: raise ValueError( 'Unknown mask type "%s"' % conn.mask.__str__) lfile.write(' & \n') if isinstance(conn.kernel, (int, float)): lfile.write(r'$%g$' % conn.kernel) elif 'gaussian' in conn.kernel: ckg = conn.kernel['gaussian'] lfile.write(r'$\mathcal{G}(p_0 = %g, \sigma = %g)$' % (ckg['p_center'], ckg['sigma'])) haveG = True else: raise ValueError( 'Unkown kernel type "%s"' % conn.kernel.__str__) lfile.write('\n') lfile.write(r'\\\hline' '\n') if legend and (haveU or haveG): # add bottom line with legend lfile.write(r'\hline' '\n') lfile.write(r'\multicolumn{%d}{|l|}{\footnotesize ' % (7 if enumerate else 6)) if haveG: lfile.write(r'$\mathcal{G}(p_0, \sigma)$: ' + r'$p(\mathbf{x})=p_0 e^{-\mathbf{x}^2/2\sigma^2}$') if haveG and haveU: lfile.write(r', ') if haveU: lfile.write( r'$\mathcal{U}[a, b)$: uniform distribution on $[a, b)$') lfile.write(r'}\\\hline' '\n') lfile.write(r'\end{tabularx}' '\n\n') if standalone: lfile.write(r'\end{document}''\n') lfile.close() # ---------------------------------------------------------------------------- def _evalkernel(mask, kernel, weight, extent, intensity, tcd): """ Plot kernel within extent. Kernel values are multiplied with abs(weight). If weight is a distribution, the mean value is used. Result is a masked array, in which the values outside the mask are masked. """ # determine resolution, number of data points dx = max(extent) / plotParams.n_kern nx = np.ceil(extent[0] / dx) ny = np.ceil(extent[1] / dx) x = np.linspace(-0.5 * extent[0], 0.5 * extent[0], nx) y = np.linspace(-0.5 * extent[1], 0.5 * extent[1], ny) X, Y = np.meshgrid(x, y) if intensity == 'wp': return np.ma.masked_array(abs(weight) * _kerneval(X, Y, kernel), np.logical_not(_maskeval(X, Y, mask))) elif intensity == 'p': return np.ma.masked_array(_kerneval(X, Y, kernel), np.logical_not(_maskeval(X, Y, mask))) elif intensity == 'tcd': return np.ma.masked_array( abs(tcd) * abs(weight) * _kerneval(X, Y, kernel), np.logical_not(_maskeval(X, Y, mask))) # ---------------------------------------------------------------------------- def _weighteval(weight): """Returns weight, or mean of distribution, signed.""" w = None if isinstance(weight, (float, int)): w = weight elif isinstance(weight, dict): assert (len(weight) == 1) if 'uniform' in weight: w = 0.5 * (weight['uniform']['min'] + weight['uniform']['max']) elif 'gaussian' in weight: w = weight['gaussian']['mean'] else: raise Exception( 'Unknown weight type "%s"' % tuple(weight.keys())[0]) if not w: raise Exception('Cannot handle weight.') return float(w) # ---------------------------------------------------------------------------- def _maskeval(x, y, mask): """ Evaluate mask given as topology style dict at (x,y). Assume x,y are 2d numpy matrices. """ assert (len(mask) == 1) if 'circular' in mask: r = mask['circular']['radius'] m = x ** 2 + y ** 2 <= r ** 2 elif 'doughnut' in mask: ri = mask['doughnut']['inner_radius'] ro = mask['doughnut']['outer_radius'] d = x ** 2 + y ** 2 m = np.logical_and(ri <= d, d <= ro) elif 'rectangular' in mask: ll = mask['rectangular']['lower_left'] ur = mask['rectangular']['upper_right'] m = np.logical_and(np.logical_and(ll[0] <= x, x <= ur[0]), np.logical_and(ll[1] <= y, y <= ur[1])) else: raise Exception('Unknown mask type "%s"' % tuple(mask.keys())[0]) return m # ---------------------------------------------------------------------------- def _kerneval(x, y, fun): """ Evaluate function given as topology style dict at (x,y). Assume x,y are 2d numpy matrices """ if isinstance(fun, (float, int)): return float(fun) * np.ones(np.shape(x)) elif isinstance(fun, dict): assert (len(fun) == 1) if 'gaussian' in fun: g = fun['gaussian'] p0 = g['p_center'] sig = g['sigma'] return p0 * np.exp(-0.5 * (x ** 2 + y ** 2) / sig ** 2) else: raise Exception('Unknown kernel "%s"', tuple(fun.keys())[0]) # something very wrong raise Exception('Cannot handle kernel.') # ---------------------------------------------------------------------------- def _addKernels(kList): """ Add a list of kernels. Arguments: kList: List of masked arrays of equal size. Returns: Masked array of same size as input. All values are added, setting masked values to 0. The mask for the sum is the logical AND of all individual masks, so that only such values are masked that are masked in all kernels. _addKernels always returns a new array object, even if kList has only a single element. """ assert (len(kList) > 0) if len(kList) < 2: return kList[0].copy() d = np.ma.filled(kList[0], fill_value=0).copy() m = kList[0].mask.copy() for k in kList[1:]: d += np.ma.filled(k, fill_value=0) m = np.logical_and(m, k.mask) return np.ma.masked_array(d, m) # ---------------------------------------------------------------------------- def _flattened(lst): """Returned list flattend at first level.""" return sum(lst, []) # ---------------------------------------------------------------------------- """ if __name__ == "__main__": import sys sys.path += ['./examples'] # import simple # reload(simple) cp = ConnectionPattern(simple.layerList, simple.connectList) import simple2 reload(simple2) cp2 = ConnectionPattern(simple2.layerList, simple2.connectList) st3 = ((SynType('GABA_B', -5.0, 'orange'), SynType('GABA_A', -1.0, 'm')), (SynType('NMDA', 5.0, 'b'), SynType('FOO', 1.0, 'aqua'), SynType('AMPA', 3.0, 'g'))) cp3s = ConnectionPattern(simple2.layerList, simple2.connectList, synTypes=st3) import simple3 reload(simple3) cp3 = ConnectionPattern(simple3.layerList, simple3.connectList) # cp._prepareAxes('by layer') # cp2._prepareAxes('by layer') # cp3._prepareAxes('detailed') cp2.plot() cp2.plot(mode='layer') cp2.plot(mode='population') cp2.plot(mode='totals') cp2.plot(mode=('AMPA',)) cp2.plot(mode=('AMPA','GABA_B')) # cp3.plot() # cp3.plot(mode='population') # cp3.plot(mode='layer') # cp3.plot(mode='totals') # cp.plot(normalize=True) # cp.plot(totals=True, normalize=True) # cp2.plot() # cp2.plot(file=('cp3.eps')) # cp2.plot(byLayer=True) # cp2.plot(totals=True) """
[ "matplotlib.colorbar.ColorbarBase", "numpy.array", "matplotlib.ticker.MaxNLocator", "matplotlib.colors.colorConverter.to_rgb", "matplotlib.get_backend", "numpy.max", "matplotlib.pyplot.close", "numpy.ma.filled", "numpy.linspace", "numpy.exp", "numpy.min", "numpy.meshgrid", "numpy.ma.masked_a...
[((78074, 78097), 'numpy.ceil', 'np.ceil', (['(extent[0] / dx)'], {}), '(extent[0] / dx)\n', (78081, 78097), True, 'import numpy as np\n'), ((78107, 78130), 'numpy.ceil', 'np.ceil', (['(extent[1] / dx)'], {}), '(extent[1] / dx)\n', (78114, 78130), True, 'import numpy as np\n'), ((78140, 78190), 'numpy.linspace', 'np.linspace', (['(-0.5 * extent[0])', '(0.5 * extent[0])', 'nx'], {}), '(-0.5 * extent[0], 0.5 * extent[0], nx)\n', (78151, 78190), True, 'import numpy as np\n'), ((78199, 78249), 'numpy.linspace', 'np.linspace', (['(-0.5 * extent[1])', '(0.5 * extent[1])', 'ny'], {}), '(-0.5 * extent[1], 0.5 * extent[1], ny)\n', (78210, 78249), True, 'import numpy as np\n'), ((78261, 78278), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (78272, 78278), True, 'import numpy as np\n'), ((81925, 81949), 'numpy.ma.masked_array', 'np.ma.masked_array', (['d', 'm'], {}), '(d, m)\n', (81943, 81949), True, 'import numpy as np\n'), ((9152, 9197), 'matplotlib.font_manager.FontProperties', 'mpl.font_manager.FontProperties', ([], {'size': '"""large"""'}), "(size='large')\n", (9183, 9197), True, 'import matplotlib as mpl\n'), ((9301, 9346), 'matplotlib.font_manager.FontProperties', 'mpl.font_manager.FontProperties', ([], {'size': '"""small"""'}), "(size='small')\n", (9332, 9346), True, 'import matplotlib as mpl\n'), ((9453, 9500), 'matplotlib.font_manager.FontProperties', 'mpl.font_manager.FontProperties', ([], {'size': '"""x-small"""'}), "(size='x-small')\n", (9484, 9500), True, 'import matplotlib as mpl\n'), ((9532, 9580), 'matplotlib.font_manager.FontProperties', 'mpl.font_manager.FontProperties', ([], {'size': '"""xx-small"""'}), "(size='xx-small')\n", (9563, 9580), True, 'import matplotlib as mpl\n'), ((59704, 59744), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'fsize', 'facecolor': '"""w"""'}), "(figsize=fsize, facecolor='w')\n", (59714, 59744), True, 'import matplotlib.pyplot as plt\n'), ((81845, 81874), 'numpy.ma.filled', 'np.ma.filled', (['k'], {'fill_value': '(0)'}), '(k, fill_value=0)\n', (81857, 81874), True, 'import numpy as np\n'), ((81887, 81912), 'numpy.logical_and', 'np.logical_and', (['m', 'k.mask'], {}), '(m, k.mask)\n', (81901, 81912), True, 'import numpy as np\n'), ((46168, 46234), 'numpy.array', 'np.array', (['[p.l / xsc, 1 - (p.t + p.h) / ysc, p.w / xsc, p.h / ysc]'], {}), '([p.l / xsc, 1 - (p.t + p.h) / ysc, p.w / xsc, p.h / ysc])\n', (46176, 46234), True, 'import numpy as np\n'), ((46502, 46556), 'numpy.array', 'np.array', (['[p.l / xsc, p.t / ysc, p.w / xsc, p.h / ysc]'], {}), '([p.l / xsc, p.t / ysc, p.w / xsc, p.h / ysc])\n', (46510, 46556), True, 'import numpy as np\n'), ((59637, 59660), 'numpy.array', 'np.array', (['self._axes.lr'], {}), '(self._axes.lr)\n', (59645, 59660), True, 'import numpy as np\n'), ((59858, 59879), 'numpy.floor', 'np.floor', (['(fsize * dpi)'], {}), '(fsize * dpi)\n', (59866, 59879), True, 'import numpy as np\n'), ((60473, 60485), 'matplotlib.pyplot.close', 'plt.close', (['f'], {}), '(f)\n', (60482, 60485), True, 'import matplotlib.pyplot as plt\n'), ((60569, 60592), 'numpy.min', 'np.min', (['(actsize / fsize)'], {}), '(actsize / fsize)\n', (60575, 60592), True, 'import numpy as np\n'), ((60655, 60712), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(self._figscale * fsize)', 'facecolor': '"""w"""'}), "(figsize=self._figscale * fsize, facecolor='w')\n", (60665, 60712), True, 'import matplotlib.pyplot as plt\n'), ((79995, 80027), 'numpy.logical_and', 'np.logical_and', (['(ri <= d)', '(d <= ro)'], {}), '(ri <= d, d <= ro)\n', (80009, 80027), True, 'import numpy as np\n'), ((80887, 80930), 'numpy.exp', 'np.exp', (['(-0.5 * (x ** 2 + y ** 2) / sig ** 2)'], {}), '(-0.5 * (x ** 2 + y ** 2) / sig ** 2)\n', (80893, 80930), True, 'import numpy as np\n'), ((81735, 81771), 'numpy.ma.filled', 'np.ma.filled', (['kList[0]'], {'fill_value': '(0)'}), '(kList[0], fill_value=0)\n', (81747, 81771), True, 'import numpy as np\n'), ((11458, 11486), 'matplotlib.colors.is_color_like', 'mpl.colors.is_color_like', (['bg'], {}), '(bg)\n', (11482, 11486), True, 'import matplotlib as mpl\n'), ((11638, 11674), 'matplotlib.colors.colorConverter.to_rgb', 'mpl.colors.colorConverter.to_rgb', (['bg'], {}), '(bg)\n', (11670, 11674), True, 'import matplotlib as mpl\n'), ((80684, 80695), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (80692, 80695), True, 'import numpy as np\n'), ((11233, 11262), 'matplotlib.colors.is_color_like', 'mpl.colors.is_color_like', (['bgc'], {}), '(bgc)\n', (11257, 11262), True, 'import matplotlib as mpl\n'), ((38253, 38269), 'numpy.array', 'np.array', (['tl.ext'], {}), '(tl.ext)\n', (38261, 38269), True, 'import numpy as np\n'), ((60442, 60459), 'matplotlib.get_backend', 'mpl.get_backend', ([], {}), '()\n', (60457, 60459), True, 'import matplotlib as mpl\n'), ((63586, 63603), 'numpy.max', 'np.max', (['kern.kern'], {}), '(kern.kern)\n', (63592, 63603), True, 'import numpy as np\n'), ((63662, 63679), 'numpy.min', 'np.min', (['kern.kern'], {}), '(kern.kern)\n', (63668, 63679), True, 'import numpy as np\n'), ((65889, 65906), 'numpy.min', 'np.min', (['kern.kern'], {}), '(kern.kern)\n', (65895, 65906), True, 'import numpy as np\n'), ((67943, 67974), 'matplotlib.ticker.MaxNLocator', 'mpl.ticker.MaxNLocator', ([], {'nbins': '(4)'}), '(nbins=4)\n', (67965, 67974), True, 'import matplotlib as mpl\n'), ((68653, 68727), 'matplotlib.colorbar.ColorbarBase', 'mpl.colorbar.ColorbarBase', (['cbax'], {'cmap': 'cm.bluered', 'orientation': '"""horizontal"""'}), "(cbax, cmap=cm.bluered, orientation='horizontal')\n", (68678, 68727), True, 'import matplotlib as mpl\n'), ((80182, 80220), 'numpy.logical_and', 'np.logical_and', (['(ll[0] <= x)', '(x <= ur[0])'], {}), '(ll[0] <= x, x <= ur[0])\n', (80196, 80220), True, 'import numpy as np\n'), ((80249, 80287), 'numpy.logical_and', 'np.logical_and', (['(ll[1] <= y)', '(y <= ur[1])'], {}), '(ll[1] <= y, y <= ur[1])\n', (80263, 80287), True, 'import numpy as np\n'), ((70224, 70255), 'matplotlib.ticker.MaxNLocator', 'mpl.ticker.MaxNLocator', ([], {'nbins': '(4)'}), '(nbins=4)\n', (70246, 70255), True, 'import matplotlib as mpl\n')]
""" Function that partitions the domain """ import numpy as np import math from find_parametric_intersect import find_parametric_intersect def partition_domain(act_frac_sys, frac_order_vec, tolerance_intersect, number_partitions_x, number_partitions_y): """ :param frac_order_vec: :param act_frac_sys: :param tolerance_intersect: :param number_partitions_x: :param number_partitions_y: :return: """ # Define lowest and highest possible x and y values. xmin = act_frac_sys[:, [0,2]].min(axis=None) xmax = act_frac_sys[:, [0,2]].max(axis=None) ymin = act_frac_sys[:, [1,3]].min(axis=None) ymax = act_frac_sys[:, [1,3]].max(axis=None) interval_x = (xmax - xmin) / number_partitions_x interval_y = (ymax - ymin) / number_partitions_y # Assume the maximum values found above define the domain. # Then, to partition the domain: partitions_x = np.zeros((number_partitions_x - 1, 4)) for i in range(1, number_partitions_x): x_part = xmin + interval_x * i partitions_x[i - 1, :] = np.array([x_part, ymin, x_part, ymax]) partitions_y = np.zeros((number_partitions_y - 1, 4)) for j in range(1, number_partitions_y): y_part = ymin + interval_y * j partitions_y[j - 1, :] = np.array([xmin, y_part, xmax, y_part]) # This array will contain information about the partitioning lines which which can be used to find intersections. # [x0, y0, x1, y1] partitions = np.vstack((partitions_x, partitions_y)) # We use this little trick to make sure the subdomains are determined correctly. act_frac_sys[np.where(act_frac_sys == xmax)] = xmax - 0.01 act_frac_sys[np.where(act_frac_sys == ymax)] = ymax - 0.01 # Variables used to store information in an array later in the program. old_index = 0 new_index = 0 subdomain_sys = np.transpose([np.floor((act_frac_sys[:, 0] - xmin) / interval_x), np.floor((act_frac_sys[:, 1] - ymin) / interval_y), np.floor((act_frac_sys[:, 2] - xmin) / interval_x), np.floor((act_frac_sys[:, 3] - ymin) / interval_y)]) # Change back what we did to get the right subdomains act_frac_sys[np.where(act_frac_sys == xmax - 0.01)] = xmax act_frac_sys[np.where(act_frac_sys == ymax - 0.01)] = ymax fracs_to_part_x = np.where(subdomain_sys[:, 0] != subdomain_sys[:, 2])[0] fracs_to_part_y = np.where(subdomain_sys[:, 1] != subdomain_sys[:, 3])[0] # An array of indices referring to fractures that must be split due to partitioning. fracs_to_part = np.union1d(fracs_to_part_x, fracs_to_part_y) part_frac_sys = act_frac_sys[fracs_to_part] part_frac_subdomains = subdomain_sys[fracs_to_part] # CHECK tot_new_fracs = np.sum(np.abs(subdomain_sys[fracs_to_part, 2] - subdomain_sys[fracs_to_part, 0]) + \ np.abs(subdomain_sys[fracs_to_part, 3] - subdomain_sys[fracs_to_part, 1]), dtype=int) + len(fracs_to_part) # Array where all newly found partitioned fractures will be stored. The number of rows is pretty arbitrary. part_fracs = np.zeros((tot_new_fracs, 5)) # Arrays where all information is stored to, in the end, form frac_order_vec_list. part_frac_order_vec = np.zeros(tot_new_fracs) # To clear some memory, the subdomains which are in part_frac_subdomains can now be deleted from the original array. subdomain_sys = np.delete(subdomain_sys, fracs_to_part, axis=0) ii = -1 for ii_frac in part_frac_sys: ii += 1 # The subdomains of points in this fracture ii_subdomains = part_frac_subdomains[ii, :] # I do not expect a fracture to cross more than 6 partition lines. Still an estimate though. num_ints = int(abs(ii_subdomains[2] - ii_subdomains[0]) + abs(ii_subdomains[3] - ii_subdomains[1])) part_int = np.zeros((num_ints, 2)) # Counts the amount of intersections between the given ii fracture and all partitioning lines. int_counter = 0 # Partition IDs. [subdomain xmin, subdomain xmax, subdomain ymin, subdomain ymax] # (an offset was added to subdomains of y to establish the difference between x and y) partition_ids = [int(min(ii_subdomains[0], ii_subdomains[2])), int(max(ii_subdomains[0], ii_subdomains[2])), int(number_partitions_x - 1 + min(ii_subdomains[1], ii_subdomains[3])), int(number_partitions_x - 1 + max(ii_subdomains[1], ii_subdomains[3]))] # x partitions for jj_part in partitions[partition_ids[0]:partition_ids[1]]: t, s, int_coord = find_parametric_intersect(ii_frac, jj_part) if (t >= (0 - tolerance_intersect) and t <= (1 + tolerance_intersect)) and \ (s >= (0 - tolerance_intersect) and s <= (1 + tolerance_intersect)): # Only store intersections of segments that don't already share a node: if not (np.linalg.norm(ii_frac[:2] - jj_part[:2]) < tolerance_intersect or np.linalg.norm(ii_frac[:2] - jj_part[2:]) < tolerance_intersect or np.linalg.norm(ii_frac[2:] - jj_part[:2]) < tolerance_intersect or np.linalg.norm(ii_frac[2:] - jj_part[2:]) < tolerance_intersect): # Store the intersection coordinates in part_int part_int[int_counter, :] = np.array([int_coord[0], int_coord[1]]) int_counter += 1 # y partitions for jj_part in partitions[partition_ids[2]:partition_ids[3]]: t, s, int_coord = find_parametric_intersect(ii_frac, jj_part) if (t >= (0 - tolerance_intersect) and t <= (1 + tolerance_intersect)) and \ (s >= (0 - tolerance_intersect) and s <= (1 + tolerance_intersect)): # Only store intersections of segments that don't already share a node: if not (np.linalg.norm(ii_frac[:2] - jj_part[:2]) < tolerance_intersect or np.linalg.norm(ii_frac[:2] - jj_part[2:]) < tolerance_intersect or np.linalg.norm(ii_frac[2:] - jj_part[:2]) < tolerance_intersect or np.linalg.norm(ii_frac[2:] - jj_part[2:]) < tolerance_intersect): # Store the intersection coordinates in part_int part_int[int_counter, :] = np.array([int_coord[0], int_coord[1]]) int_counter += 1 # Add x0 and y0 of fracture ii to start of part_int, and x1 and y1 to the end of it. part_int = np.vstack((np.vstack((ii_frac[:2], part_int)), ii_frac[2:])) # Sort on x values part_int = part_int[np.lexsort((part_int[:, 1], part_int[:, 0]))] # Initialization of the array that will contain the information about the new fractures. new_fracs = np.zeros((num_ints+1, 5)) for mm in range(0, num_ints + 1): x0, y0, x1, y1 = part_int[mm, 0], part_int[mm, 1], part_int[mm + 1, 0], part_int[mm + 1, 1] # This is how we find out in which subdomain the fracture will be. We add this ID to new_fracs subdomain_id = math.floor((((x0 + x1) / 2) - xmin) / interval_x) + \ math.floor((((y0 + y1) / 2) - ymin) / interval_y) * number_partitions_x new_fracs[mm, :] = np.array([x0, y0, x1, y1, subdomain_id]) new_index += num_ints+1 # Add fractures to the array that combines them all part_fracs[old_index:new_index] = new_fracs part_frac_order_vec[old_index:new_index] = np.ones(new_index - old_index) * frac_order_vec[fracs_to_part[ii]] old_index = new_index act_frac_sys = np.delete(act_frac_sys, fracs_to_part, axis=0) num_old_fracs = len(subdomain_sys[:, 0]) subdomains_old = subdomain_sys[:, 0] + subdomain_sys[:, 1] * number_partitions_x subdomains_old = subdomains_old.reshape((num_old_fracs,1)) act_frac_sys = np.hstack((act_frac_sys, subdomains_old)) act_frac_sys = np.vstack((act_frac_sys, part_fracs)) frac_order_vec = np.delete(frac_order_vec, fracs_to_part, axis=0) frac_order_vec = np.hstack((frac_order_vec, part_frac_order_vec)) act_frac_sys_list = [] frac_order_vec_list = [] num_subdomains = number_partitions_x * number_partitions_y for p in range(0, num_subdomains): indices = np.where(act_frac_sys[:, 4] == p) act_frac_sys_list.append(act_frac_sys[indices, :4][0]) frac_order_vec_list.append(frac_order_vec[indices]) return act_frac_sys_list, frac_order_vec_list, partitions
[ "numpy.abs", "numpy.union1d", "numpy.ones", "numpy.hstack", "numpy.where", "numpy.delete", "math.floor", "numpy.floor", "find_parametric_intersect.find_parametric_intersect", "numpy.array", "numpy.zeros", "numpy.lexsort", "numpy.vstack", "numpy.linalg.norm" ]
[((914, 952), 'numpy.zeros', 'np.zeros', (['(number_partitions_x - 1, 4)'], {}), '((number_partitions_x - 1, 4))\n', (922, 952), True, 'import numpy as np\n'), ((1128, 1166), 'numpy.zeros', 'np.zeros', (['(number_partitions_y - 1, 4)'], {}), '((number_partitions_y - 1, 4))\n', (1136, 1166), True, 'import numpy as np\n'), ((1481, 1520), 'numpy.vstack', 'np.vstack', (['(partitions_x, partitions_y)'], {}), '((partitions_x, partitions_y))\n', (1490, 1520), True, 'import numpy as np\n'), ((2644, 2688), 'numpy.union1d', 'np.union1d', (['fracs_to_part_x', 'fracs_to_part_y'], {}), '(fracs_to_part_x, fracs_to_part_y)\n', (2654, 2688), True, 'import numpy as np\n'), ((3175, 3203), 'numpy.zeros', 'np.zeros', (['(tot_new_fracs, 5)'], {}), '((tot_new_fracs, 5))\n', (3183, 3203), True, 'import numpy as np\n'), ((3318, 3341), 'numpy.zeros', 'np.zeros', (['tot_new_fracs'], {}), '(tot_new_fracs)\n', (3326, 3341), True, 'import numpy as np\n'), ((3484, 3531), 'numpy.delete', 'np.delete', (['subdomain_sys', 'fracs_to_part'], {'axis': '(0)'}), '(subdomain_sys, fracs_to_part, axis=0)\n', (3493, 3531), True, 'import numpy as np\n'), ((7823, 7869), 'numpy.delete', 'np.delete', (['act_frac_sys', 'fracs_to_part'], {'axis': '(0)'}), '(act_frac_sys, fracs_to_part, axis=0)\n', (7832, 7869), True, 'import numpy as np\n'), ((8086, 8127), 'numpy.hstack', 'np.hstack', (['(act_frac_sys, subdomains_old)'], {}), '((act_frac_sys, subdomains_old))\n', (8095, 8127), True, 'import numpy as np\n'), ((8147, 8184), 'numpy.vstack', 'np.vstack', (['(act_frac_sys, part_fracs)'], {}), '((act_frac_sys, part_fracs))\n', (8156, 8184), True, 'import numpy as np\n'), ((8207, 8255), 'numpy.delete', 'np.delete', (['frac_order_vec', 'fracs_to_part'], {'axis': '(0)'}), '(frac_order_vec, fracs_to_part, axis=0)\n', (8216, 8255), True, 'import numpy as np\n'), ((8278, 8326), 'numpy.hstack', 'np.hstack', (['(frac_order_vec, part_frac_order_vec)'], {}), '((frac_order_vec, part_frac_order_vec))\n', (8287, 8326), True, 'import numpy as np\n'), ((1069, 1107), 'numpy.array', 'np.array', (['[x_part, ymin, x_part, ymax]'], {}), '([x_part, ymin, x_part, ymax])\n', (1077, 1107), True, 'import numpy as np\n'), ((1283, 1321), 'numpy.array', 'np.array', (['[xmin, y_part, xmax, y_part]'], {}), '([xmin, y_part, xmax, y_part])\n', (1291, 1321), True, 'import numpy as np\n'), ((1624, 1654), 'numpy.where', 'np.where', (['(act_frac_sys == xmax)'], {}), '(act_frac_sys == xmax)\n', (1632, 1654), True, 'import numpy as np\n'), ((1687, 1717), 'numpy.where', 'np.where', (['(act_frac_sys == ymax)'], {}), '(act_frac_sys == ymax)\n', (1695, 1717), True, 'import numpy as np\n'), ((2268, 2305), 'numpy.where', 'np.where', (['(act_frac_sys == xmax - 0.01)'], {}), '(act_frac_sys == xmax - 0.01)\n', (2276, 2305), True, 'import numpy as np\n'), ((2331, 2368), 'numpy.where', 'np.where', (['(act_frac_sys == ymax - 0.01)'], {}), '(act_frac_sys == ymax - 0.01)\n', (2339, 2368), True, 'import numpy as np\n'), ((2400, 2452), 'numpy.where', 'np.where', (['(subdomain_sys[:, 0] != subdomain_sys[:, 2])'], {}), '(subdomain_sys[:, 0] != subdomain_sys[:, 2])\n', (2408, 2452), True, 'import numpy as np\n'), ((2478, 2530), 'numpy.where', 'np.where', (['(subdomain_sys[:, 1] != subdomain_sys[:, 3])'], {}), '(subdomain_sys[:, 1] != subdomain_sys[:, 3])\n', (2486, 2530), True, 'import numpy as np\n'), ((3931, 3954), 'numpy.zeros', 'np.zeros', (['(num_ints, 2)'], {}), '((num_ints, 2))\n', (3939, 3954), True, 'import numpy as np\n'), ((6974, 7001), 'numpy.zeros', 'np.zeros', (['(num_ints + 1, 5)'], {}), '((num_ints + 1, 5))\n', (6982, 7001), True, 'import numpy as np\n'), ((8504, 8537), 'numpy.where', 'np.where', (['(act_frac_sys[:, 4] == p)'], {}), '(act_frac_sys[:, 4] == p)\n', (8512, 8537), True, 'import numpy as np\n'), ((1881, 1931), 'numpy.floor', 'np.floor', (['((act_frac_sys[:, 0] - xmin) / interval_x)'], {}), '((act_frac_sys[:, 0] - xmin) / interval_x)\n', (1889, 1931), True, 'import numpy as np\n'), ((1967, 2017), 'numpy.floor', 'np.floor', (['((act_frac_sys[:, 1] - ymin) / interval_y)'], {}), '((act_frac_sys[:, 1] - ymin) / interval_y)\n', (1975, 2017), True, 'import numpy as np\n'), ((2053, 2103), 'numpy.floor', 'np.floor', (['((act_frac_sys[:, 2] - xmin) / interval_x)'], {}), '((act_frac_sys[:, 2] - xmin) / interval_x)\n', (2061, 2103), True, 'import numpy as np\n'), ((2139, 2189), 'numpy.floor', 'np.floor', (['((act_frac_sys[:, 3] - ymin) / interval_y)'], {}), '((act_frac_sys[:, 3] - ymin) / interval_y)\n', (2147, 2189), True, 'import numpy as np\n'), ((4729, 4772), 'find_parametric_intersect.find_parametric_intersect', 'find_parametric_intersect', (['ii_frac', 'jj_part'], {}), '(ii_frac, jj_part)\n', (4754, 4772), False, 'from find_parametric_intersect import find_parametric_intersect\n'), ((5717, 5760), 'find_parametric_intersect.find_parametric_intersect', 'find_parametric_intersect', (['ii_frac', 'jj_part'], {}), '(ii_frac, jj_part)\n', (5742, 5760), False, 'from find_parametric_intersect import find_parametric_intersect\n'), ((6810, 6854), 'numpy.lexsort', 'np.lexsort', (['(part_int[:, 1], part_int[:, 0])'], {}), '((part_int[:, 1], part_int[:, 0]))\n', (6820, 6854), True, 'import numpy as np\n'), ((7466, 7506), 'numpy.array', 'np.array', (['[x0, y0, x1, y1, subdomain_id]'], {}), '([x0, y0, x1, y1, subdomain_id])\n', (7474, 7506), True, 'import numpy as np\n'), ((7705, 7735), 'numpy.ones', 'np.ones', (['(new_index - old_index)'], {}), '(new_index - old_index)\n', (7712, 7735), True, 'import numpy as np\n'), ((2833, 2906), 'numpy.abs', 'np.abs', (['(subdomain_sys[fracs_to_part, 2] - subdomain_sys[fracs_to_part, 0])'], {}), '(subdomain_sys[fracs_to_part, 2] - subdomain_sys[fracs_to_part, 0])\n', (2839, 2906), True, 'import numpy as np\n'), ((2938, 3011), 'numpy.abs', 'np.abs', (['(subdomain_sys[fracs_to_part, 3] - subdomain_sys[fracs_to_part, 1])'], {}), '(subdomain_sys[fracs_to_part, 3] - subdomain_sys[fracs_to_part, 1])\n', (2944, 3011), True, 'import numpy as np\n'), ((6704, 6738), 'numpy.vstack', 'np.vstack', (['(ii_frac[:2], part_int)'], {}), '((ii_frac[:2], part_int))\n', (6713, 6738), True, 'import numpy as np\n'), ((7281, 7328), 'math.floor', 'math.floor', (['(((x0 + x1) / 2 - xmin) / interval_x)'], {}), '(((x0 + x1) / 2 - xmin) / interval_x)\n', (7291, 7328), False, 'import math\n'), ((5516, 5554), 'numpy.array', 'np.array', (['[int_coord[0], int_coord[1]]'], {}), '([int_coord[0], int_coord[1]])\n', (5524, 5554), True, 'import numpy as np\n'), ((6504, 6542), 'numpy.array', 'np.array', (['[int_coord[0], int_coord[1]]'], {}), '([int_coord[0], int_coord[1]])\n', (6512, 6542), True, 'import numpy as np\n'), ((7362, 7409), 'math.floor', 'math.floor', (['(((y0 + y1) / 2 - ymin) / interval_y)'], {}), '(((y0 + y1) / 2 - ymin) / interval_y)\n', (7372, 7409), False, 'import math\n'), ((5060, 5101), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[:2] - jj_part[:2])'], {}), '(ii_frac[:2] - jj_part[:2])\n', (5074, 5101), True, 'import numpy as np\n'), ((5151, 5192), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[:2] - jj_part[2:])'], {}), '(ii_frac[:2] - jj_part[2:])\n', (5165, 5192), True, 'import numpy as np\n'), ((5242, 5283), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[2:] - jj_part[:2])'], {}), '(ii_frac[2:] - jj_part[:2])\n', (5256, 5283), True, 'import numpy as np\n'), ((5333, 5374), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[2:] - jj_part[2:])'], {}), '(ii_frac[2:] - jj_part[2:])\n', (5347, 5374), True, 'import numpy as np\n'), ((6048, 6089), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[:2] - jj_part[:2])'], {}), '(ii_frac[:2] - jj_part[:2])\n', (6062, 6089), True, 'import numpy as np\n'), ((6139, 6180), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[:2] - jj_part[2:])'], {}), '(ii_frac[:2] - jj_part[2:])\n', (6153, 6180), True, 'import numpy as np\n'), ((6230, 6271), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[2:] - jj_part[:2])'], {}), '(ii_frac[2:] - jj_part[:2])\n', (6244, 6271), True, 'import numpy as np\n'), ((6321, 6362), 'numpy.linalg.norm', 'np.linalg.norm', (['(ii_frac[2:] - jj_part[2:])'], {}), '(ii_frac[2:] - jj_part[2:])\n', (6335, 6362), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy as np from dewloosh.math.linalg.frame import ReferenceFrame as FrameLike from dewloosh.geom.space.utils import frame_of_plane from .mesh import FemMesh class FemMesh2d(FemMesh): def __init__(self, *args, coords=None, frame:FrameLike=None, **kwargs): if len(coords.shape) == 2: coords3d = np.zeros((coords.shape[0], 3), dtype=coords.dtype) coords3d[:, :2] = coords[:, :2] coords = coords3d if frame is not None: tr = frame.trMatrix() # transform coordinates to global else: center, tr = frame_of_plane(coords) frame = FrameLike(origo=center, axes=tr) super().__init__(*args, coords=coords, frame=frame, **kwargs)
[ "numpy.zeros", "dewloosh.math.linalg.frame.ReferenceFrame", "dewloosh.geom.space.utils.frame_of_plane" ]
[((359, 409), 'numpy.zeros', 'np.zeros', (['(coords.shape[0], 3)'], {'dtype': 'coords.dtype'}), '((coords.shape[0], 3), dtype=coords.dtype)\n', (367, 409), True, 'import numpy as np\n'), ((633, 655), 'dewloosh.geom.space.utils.frame_of_plane', 'frame_of_plane', (['coords'], {}), '(coords)\n', (647, 655), False, 'from dewloosh.geom.space.utils import frame_of_plane\n'), ((676, 708), 'dewloosh.math.linalg.frame.ReferenceFrame', 'FrameLike', ([], {'origo': 'center', 'axes': 'tr'}), '(origo=center, axes=tr)\n', (685, 708), True, 'from dewloosh.math.linalg.frame import ReferenceFrame as FrameLike\n')]
# 3rd-party imports import tensorflow as tf from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as vis_util from object_detection.utils import ops as utils_ops import numpy as np # local imports from ...base import BaseDetector class Detector(BaseDetector): def __init__( self, model_path: str, labels_path: str, min_score_threshold: int = 0.5 ) -> None: super().__init__() self._model_path = model_path self._category_index = label_map_util.create_category_index_from_labelmap(labels_path, use_display_name=True) self._detection_graph = None self._session = None self._tensor_dict = None self._image_tensor = None self._min_score_threshold = min_score_threshold def _init_model(self) -> None: # Load a (frozen) Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(self._model_path, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') self._detection_graph = detection_graph def init_session(self) -> None: self._init_model() with self._detection_graph.as_default(): self._session = tf.Session() # Get handles to input and output tensors ops = tf.get_default_graph().get_operations() all_tensor_names = {output.name for op in ops for output in op.outputs} tensor_dict = {} for key in [ 'num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks' ]: tensor_name = key + ':0' if tensor_name in all_tensor_names: tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name) if 'detection_masks' in tensor_dict: # The following processing is only for single image detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0]) # Reframe is required to translate mask from box coordinates to image coordinates # and fit the image size. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32) detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks( detection_masks, detection_boxes, image.shape[0], image.shape[1]) detection_masks_reframed = tf.cast( tf.greater(detection_masks_reframed, 0.5), tf.uint8) # Follow the convention by adding back the batch dimension tensor_dict['detection_masks'] = tf.expand_dims( detection_masks_reframed, 0) image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0') self._tensor_dict = tensor_dict self._image_tensor = image_tensor def close_session(self) -> None: self._session.close() def _run_inference(self, image: np.ndarray) -> dict: # Run inference output_dict = self._session.run(self._tensor_dict, feed_dict = {self._image_tensor: np.expand_dims(image, 0)}) # all outputs are float32 numpy arrays, so convert types as appropriate output_dict['num_detections'] = int(output_dict['num_detections'][0]) output_dict['detection_classes'] = output_dict[ 'detection_classes'][0].astype(np.uint8) output_dict['detection_boxes'] = output_dict['detection_boxes'][0] output_dict['detection_scores'] = output_dict['detection_scores'][0] if 'detection_masks' in output_dict: output_dict['detection_masks'] = output_dict['detection_masks'][0] return output_dict def _visualize(self, image: np.ndarray, detections: dict) -> np.ndarray: # Visualization of the results of a detection. result_image = image.copy() vis_util.visualize_boxes_and_labels_on_image_array( result_image, detections['detection_boxes'], detections['detection_classes'], detections['detection_scores'], self._category_index, instance_masks = detections.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8, min_score_thresh=self._min_score_threshold) return result_image
[ "tensorflow.Graph", "tensorflow.slice", "tensorflow.Session", "object_detection.utils.ops.reframe_box_masks_to_image_masks", "tensorflow.GraphDef", "object_detection.utils.label_map_util.create_category_index_from_labelmap", "tensorflow.import_graph_def", "tensorflow.gfile.GFile", "tensorflow.expand...
[((564, 654), 'object_detection.utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['labels_path'], {'use_display_name': '(True)'}), '(labels_path,\n use_display_name=True)\n', (614, 654), False, 'from object_detection.utils import label_map_util\n'), ((1040, 1050), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (1048, 1050), True, 'import tensorflow as tf\n'), ((1121, 1134), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (1132, 1134), True, 'import tensorflow as tf\n'), ((1557, 1569), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1567, 1569), True, 'import tensorflow as tf\n'), ((1152, 1190), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['self._model_path', '"""rb"""'], {}), "(self._model_path, 'rb')\n", (1166, 1190), True, 'import tensorflow as tf\n'), ((1324, 1366), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['od_graph_def'], {'name': '""""""'}), "(od_graph_def, name='')\n", (1343, 1366), True, 'import tensorflow as tf\n'), ((1642, 1664), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1662, 1664), True, 'import tensorflow as tf\n'), ((2314, 2361), 'tensorflow.squeeze', 'tf.squeeze', (["tensor_dict['detection_boxes']", '[0]'], {}), "(tensor_dict['detection_boxes'], [0])\n", (2324, 2361), True, 'import tensorflow as tf\n'), ((2400, 2447), 'tensorflow.squeeze', 'tf.squeeze', (["tensor_dict['detection_masks']", '[0]'], {}), "(tensor_dict['detection_masks'], [0])\n", (2410, 2447), True, 'import tensorflow as tf\n'), ((2638, 2689), 'tensorflow.cast', 'tf.cast', (["tensor_dict['num_detections'][0]", 'tf.int32'], {}), "(tensor_dict['num_detections'][0], tf.int32)\n", (2645, 2689), True, 'import tensorflow as tf\n'), ((2728, 2787), 'tensorflow.slice', 'tf.slice', (['detection_boxes', '[0, 0]', '[real_num_detection, -1]'], {}), '(detection_boxes, [0, 0], [real_num_detection, -1])\n', (2736, 2787), True, 'import tensorflow as tf\n'), ((2826, 2892), 'tensorflow.slice', 'tf.slice', (['detection_masks', '[0, 0, 0]', '[real_num_detection, -1, -1]'], {}), '(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n', (2834, 2892), True, 'import tensorflow as tf\n'), ((2940, 3052), 'object_detection.utils.ops.reframe_box_masks_to_image_masks', 'utils_ops.reframe_box_masks_to_image_masks', (['detection_masks', 'detection_boxes', 'image.shape[0]', 'image.shape[1]'], {}), '(detection_masks, detection_boxes,\n image.shape[0], image.shape[1])\n', (2982, 3052), True, 'from object_detection.utils import ops as utils_ops\n'), ((3340, 3383), 'tensorflow.expand_dims', 'tf.expand_dims', (['detection_masks_reframed', '(0)'], {}), '(detection_masks_reframed, 0)\n', (3354, 3383), True, 'import tensorflow as tf\n'), ((3880, 3904), 'numpy.expand_dims', 'np.expand_dims', (['image', '(0)'], {}), '(image, 0)\n', (3894, 3904), True, 'import numpy as np\n'), ((3154, 3195), 'tensorflow.greater', 'tf.greater', (['detection_masks_reframed', '(0.5)'], {}), '(detection_masks_reframed, 0.5)\n', (3164, 3195), True, 'import tensorflow as tf\n'), ((3440, 3462), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (3460, 3462), True, 'import tensorflow as tf\n'), ((2095, 2117), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2115, 2117), True, 'import tensorflow as tf\n')]
from __future__ import print_function from future.utils import native_str from builtins import str from builtins import range #import mermaid.set_pyreg_paths import matplotlib as matplt from mermaid.config_parser import MATPLOTLIB_AGG if MATPLOTLIB_AGG: matplt.use('Agg') import matplotlib.pyplot as plt import scipy.ndimage as ndimage import mermaid.utils as utils import mermaid.finite_differences as fd import mermaid.custom_pytorch_extensions_module_version as ce import mermaid.smoother_factory as sf import mermaid.deep_smoothers as ds from mermaid.data_wrapper import AdaptVal, MyTensor import mermaid.fileio as fio import mermaid.rungekutta_integrators as rk import mermaid.forward_models as fm import mermaid.module_parameters as pars import torch import numpy as np # todo: find out a good way to fix this; this may be related to the MKL libraries print('WARNING: Disabled square root warning for numpy; this may be an issue of the MKL') np.warnings.filterwarnings('ignore','invalid value encountered in sqrt') import os import random def subsampled_quiver(u,v,color='red', scale=1, subsample=3): sz = u.shape xc,yc = np.meshgrid(range(sz[0]),range(sz[1])) plt.quiver(xc[::subsample,::subsample],yc[::subsample,::subsample],u[::subsample,::subsample], v[::subsample,::subsample], color=color, scale=scale) def create_momentum(input_im,centered_map, randomize_momentum_on_circle,randomize_in_sectors, smooth_initial_momentum, sz,spacing,nr_of_angles=10,multiplier_factor=1.0,momentum_smoothing=0.05,visualize=False, publication_figures_directory=None, publication_prefix=None, image_pair_nr=None): # assumes an input image is given (at least roughly centered in the middle of the image) # and computes a random momentum fd_np = fd.FD_np(spacing) # finite differences expect BxXxYxZ (without image channel) # gradients for the input image (to determine where the edges are) dxc = fd_np.dXc(input_im[:, 0, ...]) dyc = fd_np.dYc(input_im[:, 0, ...]) # compute the current distance map (relative to the center) dist_map = (centered_map[:, 0, ...] ** 2 + centered_map[:, 1, ...] ** 2) ** 0.5 # gradients for the distance map (to get directions) dxc_d = fd_np.dXc(dist_map) dyc_d = fd_np.dYc(dist_map) # zero them out everywhere, where the input image does not have a gradient ind_zero = (dxc ** 2 + dyc ** 2 == 0) dxc_d[ind_zero] = 0 dyc_d[ind_zero] = 0 #plt.clf() #plt.quiver(dyc_d[0,...],dxc_d[0,...],scale=5) #plt.show() # and now randomly flip the sign ring by ring maxr = int(input_im.max()) # identity map to define the sectors id_c = utils.centered_identity_map_multiN(sz, spacing, dtype='float32') already_flipped = np.zeros_like(dxc_d) for r in range(1,maxr+1): cur_ring_val = r if randomize_momentum_on_circle: randomize_over_angles = randomize_in_sectors if randomize_over_angles: angles = np.sort(2 * np.pi * np.random.rand(nr_of_angles)).astype('float32') for a in range(nr_of_angles): afrom = a ato = (a + 1) % nr_of_angles nx_from = -np.sin(angles[afrom]) ny_from = np.cos(angles[afrom]) nx_to = -np.sin(angles[ato]) ny_to = np.cos(angles[ato]) dilated_input_im = ndimage.binary_dilation(input_im[:,0,...]==cur_ring_val) indx = ((dilated_input_im!=0) & (already_flipped==0) & (dxc ** 2 + dyc ** 2 != 0) & (id_c[:, 0, ...] * nx_from + id_c[:, 1, ...] * ny_from >= 0) & (id_c[:, 0, ...] * nx_to + id_c[:, 1, ...] * ny_to < 0)) c_rand_choice = np.random.randint(0, 3) if c_rand_choice == 0: multiplier = multiplier_factor elif c_rand_choice == 1: multiplier = 0.0 else: multiplier = -multiplier_factor c_rand_val_field = multiplier * np.random.rand(*list(indx.shape)).astype('float32') dxc_d[indx] = dxc_d[indx] * c_rand_val_field[indx] dyc_d[indx] = dyc_d[indx] * c_rand_val_field[indx] already_flipped[indx] = 1 #print(c_rand_choice) #plt.clf() #plt.subplot(121) #plt.quiver(dyc_d[0, ...], dxc_d[0, ...], scale=5) #plt.subplot(122) #plt.imshow(indx[0,...]) #plt.show() else: dilated_input_im = ndimage.binary_dilation(input_im[:, 0, ...] == cur_ring_val) indx = ((dilated_input_im!=0) & (already_flipped==0) & (dxc ** 2 + dyc ** 2 != 0)) already_flipped[indx] = 1 c_rand_val_field = 2 * 2 * (np.random.rand(*list(indx.shape)).astype('float32') - 0.5) dxc_d[indx] = dxc_d[indx] * c_rand_val_field[indx] dyc_d[indx] = dyc_d[indx] * c_rand_val_field[indx] else: dilated_input_im = ndimage.binary_dilation(input_im[:, 0, ...] == cur_ring_val) indx = ((dilated_input_im!=0) & (already_flipped==0) & (dxc ** 2 + dyc ** 2 != 0)) already_flipped[indx] = 1 # multiply by a random number in [-1,1] c_rand_val = 2 * (np.random.rand().astype('float32') - 0.5)*multiplier_factor dxc_d[indx] = dxc_d[indx] * c_rand_val dyc_d[indx] = dyc_d[indx] * c_rand_val # now create desired initial momentum m_orig = np.zeros_like(id_c) m_orig[0, 0, ...] = dxc_d m_orig[0, 1, ...] = dyc_d if visualize: plt.clf() plt.quiver(m_orig[0, 1, ...], m_orig[0, 0, ...],color='red',scale=5) plt.axis('equal') plt.show() if publication_figures_directory is not None: plt.clf() plt.imshow(input_im[0, 0, ...],origin='lower') plt.quiver(m_orig[0, 1, ...], m_orig[0, 0, ...],color='red',scale=5) plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_m_orig_{:d}.pdf'.format(publication_prefix,image_pair_nr)),bbox_inches='tight',pad_inches=0) if smooth_initial_momentum: s_m_params = pars.ParameterDict() s_m_params['smoother']['type'] = 'gaussian' s_m_params['smoother']['gaussian_std'] = momentum_smoothing s_m = sf.SmootherFactory(sz[2::], spacing).create_smoother(s_m_params) m = s_m.smooth(AdaptVal(torch.from_numpy(m_orig))).detach().cpu().numpy() if visualize: plt.clf() plt.subplot(121) plt.imshow(m_orig[0, 0, ...]) plt.subplot(122) plt.imshow(m[0, 0, ...]) plt.suptitle('smoothed mx') plt.show() if publication_figures_directory is not None: plt.clf() plt.imshow(input_im[0,0,...],origin='lower') subsampled_quiver(m[0, 1, ...], m[0, 0, ...], color='red', scale=1,subsample=3) plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_m_smoothed_orig_{:d}.pdf'.format(publication_prefix,image_pair_nr)),bbox_inches='tight') else: m = m_orig return m def compute_overall_std(weights,multi_gaussian_stds,kernel_weighting_type): # standard deviation image (only for visualization; this is the desired ground truth) sh_std_im = weights.shape[2:] std_im = np.zeros(sh_std_im, dtype='float32') nr_of_mg_weights = weights.shape[1] # now compute the resulting standard deviation image (based on the computed weights) for g in range(nr_of_mg_weights): if kernel_weighting_type=='w_K_w': std_im += (weights[0,g,...]**2)*multi_gaussian_stds[g]**2 else: std_im += weights[0,g,...]*multi_gaussian_stds[g]**2 std_im = std_im**0.5 return std_im def create_rings(levels_in,multi_gaussian_weights,default_multi_gaussian_weights, multi_gaussian_stds,put_weights_between_circles,kernel_weighting_type, sz,spacing,visualize=False): if len(multi_gaussian_weights)+1!=len(levels_in): raise ValueError('There needs to be one more level than the number of weights, to define this example') id_c = utils.centered_identity_map_multiN(sz, spacing, dtype='float32') sh_id_c = id_c.shape # create the weights that will be used for the multi-Gaussian nr_of_mg_weights = len(default_multi_gaussian_weights) # format for weights: B x nr_gaussians x X x Y x Z sh_weights = [sh_id_c[0]] + [nr_of_mg_weights] + list(sh_id_c[2:]) weights = np.zeros(sh_weights,dtype='float32') # set the default for g in range(nr_of_mg_weights): weights[:,g,...] = default_multi_gaussian_weights[g] # now get the memory for the ring data sh_ring_im = list(sh_id_c[2:]) ring_im = np.zeros(sh_ring_im,dtype='float32') # just add one more level in case we put weights in between (otherwise add a dummy) levels = np.zeros(len(levels_in)+1,dtype='float32') levels[0:-1] = levels_in if put_weights_between_circles: levels[-1] = levels_in[-1]+levels_in[-1]-levels_in[-2] else: levels[-1]=-1. for i in range(len(levels)-2): cl = levels[i] nl = levels[i+1] nnl = levels[i+2] cval = i+1 indices_ring = (id_c[0,0,...]**2+id_c[0,1,...]**2>=cl**2) & (id_c[0,0,...]**2+id_c[0,1,...]**2<=nl**2) ring_im[indices_ring] = cval # as the momenta will be supported on the ring boundaries, we may want the smoothing to be changing in the middle of the rings if put_weights_between_circles: indices_weight = (id_c[0,0,...]**2+id_c[0,1,...]**2>=((cl+nl)/2)**2) & (id_c[0,0,...]**2+id_c[0,1,...]**2<=((nl+nnl)/2)**2) else: indices_weight = (id_c[0, 0, ...] ** 2 + id_c[0, 1, ...] ** 2 >= cl ** 2) & (id_c[0, 0, ...] ** 2 + id_c[0, 1, ...] ** 2 <= nl ** 2) # set the desired weights in this ring current_desired_weights = multi_gaussian_weights[i] for g in range(nr_of_mg_weights): current_weights = weights[0,g,...] current_weights[indices_weight] = current_desired_weights[g] std_im = compute_overall_std(weights,multi_gaussian_stds,kernel_weighting_type=kernel_weighting_type) ring_im = ring_im.view().reshape([1,1] + sh_ring_im) if visualize: #grad_norm_sqr = dxc**2 + dyc**2 plt.clf() plt.subplot(221) plt.imshow(id_c[0, 0, ...]) plt.colorbar() plt.subplot(222) plt.imshow(id_c[0, 1, ...]) plt.colorbar() plt.subplot(223) plt.imshow(ring_im[0,0,...]) plt.colorbar() plt.subplot(224) #plt.imshow(grad_norm_sqr[0,...]>0) #plt.colorbar() plt.show() plt.clf() nr_of_weights = weights.shape[1] for cw in range(nr_of_weights): plt.subplot(2,3,1+nr_of_weights) plt.imshow(weights[0,cw,...],vmin=0.0,vmax=1.0) plt.colorbar() plt.subplot(236) plt.imshow(std_im) plt.colorbar() plt.suptitle('weights') plt.show() return weights,ring_im,std_im def _compute_ring_radii(extent, nr_of_rings, randomize_radii, randomize_factor=0.75): if randomize_radii: rings_at_default = np.linspace(0., extent, nr_of_rings + 1).astype('float32') diff_r = rings_at_default[1] - rings_at_default[0] rings_at = np.sort(rings_at_default + (np.random.random(nr_of_rings + 1).astype('float32') - 0.5) * diff_r * randomize_factor) else: rings_at = np.linspace(0., extent, nr_of_rings + 1).astype('float32') # first one needs to be zero: rings_at[0] = 0 return rings_at def compute_localized_velocity_from_momentum(m,weights,multi_gaussian_stds,sz,spacing,kernel_weighting_type='w_K',visualize=False): nr_of_gaussians = len(multi_gaussian_stds) # create a velocity field from this momentum using a multi-Gaussian kernel gaussian_fourier_filter_generator = ce.GaussianFourierFilterGenerator(sz[2:], spacing, nr_of_slots=nr_of_gaussians) t_weights = AdaptVal(torch.from_numpy(weights)) t_momentum = AdaptVal(torch.from_numpy(m)) if kernel_weighting_type=='sqrt_w_K_sqrt_w': sqrt_weights = torch.sqrt(t_weights) sqrt_weighted_multi_smooth_v = ds.compute_weighted_multi_smooth_v(momentum=t_momentum, weights=sqrt_weights, gaussian_stds=multi_gaussian_stds, gaussian_fourier_filter_generator=gaussian_fourier_filter_generator) elif kernel_weighting_type=='w_K_w': # now create the weighted multi-smooth-v weighted_multi_smooth_v = ds.compute_weighted_multi_smooth_v(momentum=t_momentum, weights=t_weights, gaussian_stds=multi_gaussian_stds, gaussian_fourier_filter_generator=gaussian_fourier_filter_generator) elif kernel_weighting_type=='w_K': multi_smooth_v = ce.fourier_set_of_gaussian_convolutions(t_momentum, gaussian_fourier_filter_generator=gaussian_fourier_filter_generator, sigma=AdaptVal(torch.from_numpy(multi_gaussian_stds)), compute_std_gradients=False) # now compute the localized_velocity # compute velocity based on localized weights sz_m = m.shape # get the size of the multi-velocity field; multi_v x batch x channels x X x Y sz_mv = [nr_of_gaussians] + list(sz_m) # create the output tensor: will be of dimension: batch x channels x X x Y localized_v = AdaptVal(MyTensor(*sz_m)) dims = localized_v.shape[1] # now we apply this weight across all the channels; weight output is B x weights x X x Y for n in range(dims): # reverse the order so that for a given channel we have batch x multi_velocity x X x Y # i.e., the multi-velocity field output is treated as a channel # reminder: # format of multi_smooth_v is multi_v x batch x channels x X x Y # (channels here are the vector field components); i.e. as many as there are dimensions # each one of those should be smoothed the same # let's smooth this on the fly, as the smoothing will be of form # w_i*K_i*(w_i m) if kernel_weighting_type == 'sqrt_w_K_sqrt_w': # roc should be: batch x multi_v x X x Y roc = sqrt_weighted_multi_smooth_v[:, :, n, ...] # print(sqrt_weighted_multi_smooth_v.shape, sqrt_weights.shape,roc.shape) yc = torch.sum(roc * sqrt_weights, dim=1) elif kernel_weighting_type == 'w_K_w': # roc should be: batch x multi_v x X x Y roc = weighted_multi_smooth_v[:, :, n, ...] yc = torch.sum(roc * t_weights, dim=1) elif kernel_weighting_type == 'w_K': # roc should be: batch x multi_v x X x Y roc = torch.transpose(multi_smooth_v[:, :, n, ...], 0, 1) yc = torch.sum(roc * t_weights, dim=1) else: raise ValueError('Unknown weighting_type: {}'.format(kernel_weighting_type)) localized_v[:, n, ...] = yc # localized_v is: batch x channels x X x Y localized_v = localized_v.cpu().numpy() if visualize: norm_localized_v = (localized_v[0, 0, ...] ** 2 + localized_v[0, 1, ...] ** 2) ** 0.5 plt.clf() plt.subplot(121) plt.imshow(norm_localized_v) plt.axis('image') plt.colorbar() plt.subplot(121) plt.quiver(m[0,1,...],m[0,0,...]) plt.axis('equal') plt.show() return localized_v def compute_map_from_v(localized_v,sz,spacing): # now compute the deformation that belongs to this velocity field params = pars.ParameterDict() params['number_of_time_steps'] = 40 advectionMap = fm.AdvectMap( sz[2:], spacing ) pars_to_pass = utils.combine_dict({'v':AdaptVal(torch.from_numpy(localized_v))}, dict() ) integrator = rk.RK4(advectionMap.f, advectionMap.u, pars_to_pass, params) tFrom = 0. tTo = 1. phi0 = AdaptVal(torch.from_numpy(utils.identity_map_multiN(sz,spacing))) phi1 = integrator.solve([phi0], tFrom, tTo )[0] return phi0,phi1 def add_texture(im_orig,texture_gaussian_smoothness=0.1,texture_magnitude=0.3): # do this separately for each integer intensity level levels = np.unique((np.floor(im_orig)).astype('int')) im = np.zeros_like(im_orig) for current_level in levels: sz = im_orig.shape rand_noise = np.random.random(sz[2:]).astype('float32')-0.5 rand_noise = rand_noise.view().reshape(sz) r_params = pars.ParameterDict() r_params['smoother']['type'] = 'gaussian' r_params['smoother']['gaussian_std'] = texture_gaussian_smoothness s_r = sf.SmootherFactory(sz[2::], spacing).create_smoother(r_params) rand_noise_smoothed = s_r.smooth(AdaptVal(torch.from_numpy(rand_noise))).detach().cpu().numpy() rand_noise_smoothed /= rand_noise_smoothed.max() rand_noise_smoothed *= texture_magnitude c_indx = (im_orig>=current_level-0.5) im[c_indx] = im_orig[c_indx] + rand_noise_smoothed[c_indx] return im def create_random_image_pair(weights_not_fluid,weights_fluid,weights_neutral,weight_smoothing_std,multi_gaussian_stds, kernel_weighting_type, randomize_momentum_on_circle,randomize_in_sectors, put_weights_between_circles, start_with_fluid_weight, use_random_source, use_fixed_source, add_texture_to_image, texture_gaussian_smoothness, texture_magnitude, nr_of_circles_to_generate, circle_extent, sz,spacing, nr_of_angles=10,multiplier_factor=1.0,momentum_smoothing=0.05, visualize=False,visualize_warped=False,print_warped_name=None, publication_figures_directory=None, image_pair_nr=None): nr_of_rings = nr_of_circles_to_generate extent = circle_extent randomize_factor = 0.25 randomize_radii = not use_fixed_source smooth_initial_momentum = True # create ordered set of weights multi_gaussian_weights = [] for r in range(nr_of_rings): if r%2==0: if start_with_fluid_weight: multi_gaussian_weights.append(weights_fluid) else: multi_gaussian_weights.append(weights_not_fluid) else: if start_with_fluid_weight: multi_gaussian_weights.append(weights_not_fluid) else: multi_gaussian_weights.append(weights_fluid) rings_at = _compute_ring_radii(extent=extent, nr_of_rings=nr_of_rings, randomize_radii=randomize_radii, randomize_factor=randomize_factor) weights_orig,ring_im_orig,std_im_orig = create_rings(rings_at,multi_gaussian_weights=multi_gaussian_weights, default_multi_gaussian_weights=weights_neutral, multi_gaussian_stds=multi_gaussian_stds, put_weights_between_circles=put_weights_between_circles, kernel_weighting_type=kernel_weighting_type, sz=sz,spacing=spacing, visualize=visualize) if weight_smoothing_std is not None: if weight_smoothing_std>0: s_m_params = pars.ParameterDict() s_m_params['smoother']['type'] = 'gaussian' s_m_params['smoother']['gaussian_std'] = weight_smoothing_std # smooth the weights smoother = sf.SmootherFactory(weights_orig.shape[2::], spacing).create_smoother(s_m_params) #weights_old = np.zeros_like(weights_orig) #weights_old[:] = weights_orig weights_orig = (smoother.smooth(AdaptVal(torch.from_numpy(weights_orig)))).detach().cpu().numpy() # make sure they are strictly positive weights_orig[weights_orig<0] = 0 if publication_figures_directory is not None: plt.clf() plt.imshow(ring_im_orig[0,0,...],origin='lower') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory,'ring_im_orig_{:d}.pdf'.format(image_pair_nr)),bbox_inches='tight',pad_inches=0) plt.clf() plt.imshow(std_im_orig,origin='lower') plt.axis('off') plt.colorbar() plt.savefig(os.path.join(publication_figures_directory,'std_im_orig_{:d}.pdf'.format(image_pair_nr)),bbox_inches='tight',pad_inches=0) id_c = utils.centered_identity_map_multiN(sz, spacing, dtype='float32') m_orig = create_momentum(ring_im_orig, centered_map=id_c, randomize_momentum_on_circle=randomize_momentum_on_circle, randomize_in_sectors=randomize_in_sectors, smooth_initial_momentum=smooth_initial_momentum, sz=sz, spacing=spacing, nr_of_angles=nr_of_angles, multiplier_factor=multiplier_factor, momentum_smoothing=momentum_smoothing, publication_figures_directory=publication_figures_directory, publication_prefix='circle_init', image_pair_nr=image_pair_nr) localized_v_orig = compute_localized_velocity_from_momentum(m=m_orig,weights=weights_orig,multi_gaussian_stds=multi_gaussian_stds,sz=sz,spacing=spacing,kernel_weighting_type=kernel_weighting_type) if publication_figures_directory is not None: plt.clf() plt.imshow(ring_im_orig[0, 0, ...], origin='lower') subsampled_quiver(localized_v_orig[0,1,...],localized_v_orig[0,0,...],color='red', scale=1, subsample=3) plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory,'{:s}_{:d}.pdf'.format('localized_v_orig', image_pair_nr)),bbox_inches='tight',pad_inches=0) phi0_orig,phi1_orig = compute_map_from_v(localized_v_orig,sz,spacing) if add_texture_to_image: ring_im = add_texture(ring_im_orig,texture_gaussian_smoothness=texture_gaussian_smoothness,texture_magnitude=texture_magnitude) if publication_figures_directory is not None: plt.clf() plt.imshow(ring_im[0, 0, ...],origin='lower') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, 'ring_im_orig_textured_{:d}.pdf'.format(image_pair_nr)),bbox_inches='tight',pad_inches=0) # plt.clf() # plt.subplot(1,2,1) # plt.imshow(ring_im[0,0,...],clim=(-0.5,2.5)) # plt.colorbar() # plt.subplot(1,2,2) # plt.imshow(ring_im_orig[0, 0, ...], clim=(-0.5, 2.5)) # plt.colorbar() # plt.show() else: ring_im = ring_im_orig # deform image based on this map I0_source_orig = AdaptVal(torch.from_numpy(ring_im)) I1_warped_orig = utils.compute_warped_image_multiNC(I0_source_orig, phi1_orig, spacing, spline_order=1) # define the label images I0_label_orig = AdaptVal(torch.from_numpy(ring_im_orig)) I1_label_orig = utils.get_warped_label_map(I0_label_orig, phi1_orig, spacing ) if publication_figures_directory is not None: plt.clf() plt.imshow(I1_label_orig[0, 0, ...].detach().cpu().numpy(),origin='lower') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, 'ring_im_warped_source_{:d}.pdf'.format(image_pair_nr)),bbox_inches='tight',pad_inches=0) if use_random_source: # the initially created target will become the source id_c_warped_t = utils.compute_warped_image_multiNC(AdaptVal(torch.from_numpy(id_c)), phi1_orig, spacing, spline_order=1) id_c_warped = id_c_warped_t.detach().cpu().numpy() weights_warped_t = utils.compute_warped_image_multiNC(AdaptVal(torch.from_numpy(weights_orig)), phi1_orig, spacing, spline_order=1) weights_warped = weights_warped_t.detach().cpu().numpy() # make sure they are stirctly positive weights_warped[weights_warped<0] = 0 warped_source_im_orig = I1_label_orig.detach().cpu().numpy() m_warped_source = create_momentum(warped_source_im_orig, centered_map=id_c_warped, randomize_momentum_on_circle=randomize_momentum_on_circle, randomize_in_sectors=randomize_in_sectors, smooth_initial_momentum=smooth_initial_momentum, sz=sz, spacing=spacing, nr_of_angles=nr_of_angles, multiplier_factor=multiplier_factor, momentum_smoothing=momentum_smoothing, publication_figures_directory=publication_figures_directory, publication_prefix='random_source', image_pair_nr=image_pair_nr) localized_v_warped = compute_localized_velocity_from_momentum(m=m_warped_source, weights=weights_warped, multi_gaussian_stds=multi_gaussian_stds, sz=sz, spacing=spacing,kernel_weighting_type=kernel_weighting_type) if publication_figures_directory is not None: plt.clf() plt.imshow(warped_source_im_orig[0, 0, ...], origin='lower') subsampled_quiver(localized_v_warped[0, 1, ...], localized_v_warped[0, 0, ...], color='red', scale=1,subsample=3) plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory,'{:s}_{:d}.pdf'.format('random_source_localized_v', image_pair_nr)),bbox_inches='tight',pad_inches=0) phi0_w, phi1_w = compute_map_from_v(localized_v_warped, sz, spacing) if add_texture_to_image: warped_source_im = add_texture(warped_source_im_orig,texture_gaussian_smoothness=texture_gaussian_smoothness,texture_magnitude=texture_magnitude) if publication_figures_directory is not None: plt.clf() plt.imshow(ring_im[0, 0, ...],origin='lower') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, 'random_source_im_textured_{:d}.pdf'.format(image_pair_nr)),bbox_inches='tight',pad_inches=0) else: warped_source_im = warped_source_im_orig # deform these images based on the new map # deform image based on this map I0_source_w = AdaptVal(torch.from_numpy(warped_source_im)) I1_warped_w = utils.compute_warped_image_multiNC(I0_source_w, phi1_w, spacing, spline_order=1) # define the label images I0_label_w = AdaptVal(torch.from_numpy(warped_source_im_orig)) I1_label_w = utils.get_warped_label_map(I0_label_w, phi1_w, spacing) if use_random_source: I0_source = I0_source_w I1_warped = I1_warped_w I0_label = I0_label_w I1_label = I1_label_w m = m_warped_source phi0 = phi0_w phi1 = phi1_w weights = weights_warped else: I0_source = I0_source_orig I1_warped = I1_warped_orig I0_label = I0_label_orig I1_label = I1_label_orig m = m_orig phi0 = phi0_orig phi1 = phi1_orig weights = weights_orig std_im = compute_overall_std(weights,multi_gaussian_stds,kernel_weighting_type=kernel_weighting_type) if visualize_warped: plt.clf() # plot original image, warped image, and grids plt.subplot(3,4,1) plt.imshow(I0_source[0,0,...].detach().cpu().numpy()) plt.title('source') plt.subplot(3,4,2) plt.imshow(I1_warped[0,0,...].detach().cpu().numpy()) plt.title('warped = target') plt.subplot(3,4,3) plt.imshow(I0_source[0,0,...].detach().cpu().numpy()) plt.contour(phi0[0,0,...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.contour(phi0[0,1,...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.subplot(3,4,4) plt.imshow(I1_warped[0,0,...].detach().cpu().numpy()) plt.contour(phi1[0,0,...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.contour(phi1[0,1,...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') nr_of_weights = weights.shape[1] for cw in range(nr_of_weights): plt.subplot(3,4,5+cw) if kernel_weighting_type=='w_K_w': plt.imshow(weights[0, cw, ...]**2, vmin=0.0, vmax=1.0) else: plt.imshow(weights[0, cw, ...], vmin=0.0, vmax=1.0) plt.title('w: std' + str(multi_gaussian_stds[cw])) plt.colorbar() plt.subplot(3,4,12) plt.imshow(std_im) plt.title('std') plt.colorbar() if print_warped_name is not None: plt.savefig(print_warped_name) else: plt.show() if publication_figures_directory is not None: plt.clf() plt.imshow(I0_source[0, 0, ...].detach().cpu().numpy(),origin='lower') plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_{:d}.pdf'.format('source_image', image_pair_nr)),bbox_inches='tight',pad_inches=0) plt.clf() plt.imshow(I1_warped[0, 0, ...].detach().cpu().numpy(),origin='lower') plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_{:d}.pdf'.format('target_image', image_pair_nr)),bbox_inches='tight',pad_inches=0) plt.clf() plt.imshow(I0_source[0, 0, ...].detach().cpu().numpy(),origin='lower') plt.contour(phi0[0, 0, ...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.contour(phi0[0, 1, ...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_{:d}.pdf'.format('source_image_with_grid', image_pair_nr)),bbox_inches='tight',pad_inches=0) plt.clf() plt.imshow(I1_warped[0, 0, ...].detach().cpu().numpy(),origin='lower') plt.contour(phi1[0, 0, ...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.contour(phi1[0, 1, ...].detach().cpu().numpy(), np.linspace(-1, 1, 40), colors='r', linestyles='solid') plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory,'{:s}_{:d}.pdf'.format('target_image_with_grid', image_pair_nr)), bbox_inches='tight',pad_inches=0) plt.clf() plt.imshow(std_im,origin='lower') plt.colorbar() plt.axis('image') plt.axis('off') plt.savefig(os.path.join(publication_figures_directory, '{:s}_{:d}.pdf'.format('std_im_source', image_pair_nr)),bbox_inches='tight',pad_inches=0) return I0_source.detach().cpu().numpy(), I1_warped.detach().cpu().numpy(), weights, \ I0_label.detach().cpu().numpy(), I1_label.detach().cpu().numpy(), phi1.detach().cpu().numpy(), m def get_parameter_value(command_line_par,params, params_name, default_val, params_description): if command_line_par is None: ret = params[(params_name, default_val, params_description)] else: params[params_name]=command_line_par ret = command_line_par return ret def get_parameter_value_flag(command_line_par,params, params_name, default_val, params_description): if command_line_par==default_val: ret = params[(params_name, default_val, params_description)] else: params[params_name]=command_line_par ret = command_line_par return ret if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Creates a synthetic registration results') parser.add_argument('--config', required=False, default=None, help='The main json configuration file that can be used to define the settings') parser.add_argument('--output_directory', required=False, default='synthetic_example_out', help='Where the output was stored (now this will be the input directory)') parser.add_argument('--nr_of_pairs_to_generate', required=False, default=10, type=int, help='number of image pairs to generate') parser.add_argument('--nr_of_circles_to_generate', required=False, default=None, type=int, help='number of circles to generate in an image') #2 parser.add_argument('--circle_extent', required=False, default=None, type=float, help='Size of largest circle; image is [-0.5,0.5]^2') # 0.25 parser.add_argument('--seed', required=False, type=int, default=None, help='Sets the random seed which affects data shuffling') parser.add_argument('--create_publication_figures', action='store_true', help='If set writes out figures illustrating the generation approach of first example') parser.add_argument('--use_fixed_source', action='store_true', help='if set the source image is fixed; like a fixed atlas image') parser.add_argument('--use_random_source', action='store_true', help='if set then inital source is warped randomly, otherwise it is circular') parser.add_argument('--no_texture', action='store_true',help='if set then no texture is used, otherwise (default) texture is generated') parser.add_argument('--texture_gaussian_smoothness', required=False, type=float, default=None, help='Gaussian standard deviation used to smooth a random image to create texture.') parser.add_argument('--texture_magnitude', required=False, type=float, default=None, help='Magnitude of the texture') parser.add_argument('--do_not_randomize_momentum', action='store_true', help='if set, momentum is deterministic') parser.add_argument('--do_not_randomize_in_sectors', action='store_true', help='if set and randomize momentum is on, momentum is only randomized uniformly over circles') parser.add_argument('--put_weights_between_circles', action='store_true', help='if set, the weights will change in-between circles, otherwise they will be colocated with the circles') parser.add_argument('--start_with_fluid_weight', action='store_true', help='if set then the innermost circle is not fluid, otherwise it is fluid') parser.add_argument('--weight_smoothing_std',required=False,default=0.02,type=float,help='Standard deviation to smooth the weights with; to assure sufficient regularity') parser.add_argument('--stds', required=False,type=str, default=None, help='standard deviations for the multi-Gaussian; default=[0.01,0.05,0.1,0.2]') parser.add_argument('--weights_not_fluid', required=False,type=str, default=None, help='weights for a non fluid circle; default=[0,0,0,1]') parser.add_argument('--weights_fluid', required=False,type=str, default=None, help='weights for a fluid circle; default=[0.2,0.5,0.2,0.1]') parser.add_argument('--weights_background', required=False,type=str, default=None, help='weights for the background; default=[0,0,0,1]') parser.add_argument('--kernel_weighting_type', required=False, type=str, default=None, help='Which kernel weighting to use for integration. Specify as [w_K|w_K_w|sqrt_w_K_sqrt_w]; w_K is the default') parser.add_argument('--nr_of_angles', required=False, default=None, type=int, help='number of angles for randomize in sector') #10 parser.add_argument('--multiplier_factor', required=False, default=None, type=float, help='value the random momentum is multiplied by') #1.0 parser.add_argument('--momentum_smoothing', required=False, default=None, type=int, help='how much the randomly generated momentum is smoothed') #0.05 parser.add_argument('--sz', required=False, type=str, default=None, help='Desired size of synthetic example; default=[128,128]') args = parser.parse_args() if args.seed is not None: print('Setting the random seed to {:}'.format(args.seed)) random.seed(args.seed) torch.manual_seed(args.seed) params = pars.ParameterDict() if args.config is not None: # load the configuration params.load_JSON(args.config) visualize = True visualize_warped = True print_images = True nr_of_pairs_to_generate = args.nr_of_pairs_to_generate nr_of_circles_to_generate = get_parameter_value(args.nr_of_circles_to_generate, params, 'nr_of_circles_to_generate', 2, 'number of circles for the synthetic data') circle_extent = get_parameter_value(args.circle_extent, params, 'circle_extent', 0.2, 'Size of largest circle; image is [-0.5,0.5]^2') randomize_momentum_on_circle = get_parameter_value_flag(not args.do_not_randomize_momentum,params=params, params_name='randomize_momentum_on_circle', default_val=True, params_description='randomizes the momentum on the circles') randomize_in_sectors = get_parameter_value_flag(not args.do_not_randomize_in_sectors, params=params, params_name='randomize_in_sectors', default_val=True, params_description='randomized the momentum sector by sector') put_weights_between_circles = get_parameter_value_flag(args.put_weights_between_circles, params=params, params_name='put_weights_between_circles', default_val=False, params_description='if set, the weights will change in-between circles, otherwise they will be colocated with the circles') start_with_fluid_weight = get_parameter_value_flag(args.start_with_fluid_weight, params=params, params_name='start_with_fluid_weight', default_val=False, params_description='if set then the innermost circle is not fluid, otherwise it is fluid') use_random_source = get_parameter_value_flag(args.use_random_source, params=params, params_name='use_random_source', default_val=False, params_description='if set then source image is already deformed (and no longer circular)') use_fixed_source = get_parameter_value_flag(args.use_fixed_source, params=params, params_name='use_fixed_source', default_val=False, params_description='if set then source image will be fixed; like a fixed atlas image)') add_texture_to_image = get_parameter_value_flag(not args.no_texture, params=params, params_name='add_texture_to_image', default_val=True, params_description='When set to true, texture is added to the images (based on texture_gaussian_smoothness)') texture_magnitude = get_parameter_value(args.texture_magnitude, params=params, params_name='texture_magnitude', default_val=0.3, params_description='Largest magnitude of the added texture') texture_gaussian_smoothness = get_parameter_value(args.texture_gaussian_smoothness,params=params,params_name='texture_gaussian_smoothness', default_val=0.02, params_description='How much smoothing is used to create the texture image') kernel_weighting_type = get_parameter_value(args.kernel_weighting_type, params=params, params_name='kernel_weighting_type', default_val='sqrt_w_K_sqrt_w', params_description='Which kernel weighting to use for integration. Specify as [w_K|w_K_w|sqrt_w_K_sqrt_w]; w_K is the default') if use_random_source==True and use_fixed_source==True: raise ValueError('The source image cannot simultaneously be random and fixed. Aborting') nr_of_angles = get_parameter_value(args.nr_of_angles,params,'nr_of_angles',10,'number of angles for randomize in sector') multiplier_factor = get_parameter_value(args.multiplier_factor,params,'multiplier_factor',0.5,'value the random momentum is multiplied by') momentum_smoothing = get_parameter_value(args.momentum_smoothing,params,'momentum_smoothing',0.05,'how much the randomly generated momentum is smoothed') if args.stds is None: multi_gaussian_stds_p = None else: mgsl = [float(item) for item in args.stds.split(',')] multi_gaussian_stds_p = list(np.array(mgsl)) multi_gaussian_stds = get_parameter_value(multi_gaussian_stds_p, params, 'multi_gaussian_stds', list(np.array([0.01, 0.05, 0.1, 0.2])), 'multi gaussian standard deviations') multi_gaussian_stds = np.array(multi_gaussian_stds).astype('float32') if args.weights_not_fluid is None: weights_not_fluid_p = None else: cw = [float(item) for item in args.weights_not_fluid.split(',')] weights_not_fluid_p = list(np.array(cw)) weights_not_fluid = get_parameter_value(weights_not_fluid_p, params, 'weights_not_fluid', list(np.array([0,0,0,1.0])), 'weights for the non-fluid regions') weights_not_fluid = np.array(weights_not_fluid).astype('float32') if len(weights_not_fluid)!=len(multi_gaussian_stds): raise ValueError('Need as many weights as there are standard deviations') if args.weights_fluid is None: weights_fluid_p = None else: cw = [float(item) for item in args.weights_fluid.split(',')] weights_fluid_p = list(np.array(cw)) weights_fluid = get_parameter_value(weights_fluid_p, params, 'weights_fluid', list(np.array([0.2,0.5,0.2,0.1])), 'weights for fluid regions') weights_fluid = np.array(weights_fluid).astype('float32') if len(weights_fluid)!=len(multi_gaussian_stds): raise ValueError('Need as many weights as there are standard deviations') if args.weights_background is None: weights_neutral_p = None else: cw = [float(item) for item in args.weights_background.split(',')] weights_neutral_p = list(np.array(cw)) weights_neutral = get_parameter_value(weights_neutral_p, params, 'weights_neutral', list(np.array([0,0,0,1.0])), 'weights in the neutral/background region') weights_neutral = np.array(weights_neutral).astype('float32') if kernel_weighting_type=='w_K_w': print('INFO: converting weights to w_K_w format, i.e., taking their square root') # square of weights needs to sum up to one, so simply take the square root of the specified weights here weights_fluid = np.sqrt(weights_fluid) weights_neutral = np.sqrt(weights_neutral) weights_not_fluid = np.sqrt(weights_not_fluid) if len(weights_neutral)!=len(multi_gaussian_stds): raise ValueError('Need as many weights as there are standard deviations') if args.sz is None: sz_p = None else: cw = [int(item) for item in args.sz.split(',')] sz_p = np.array(cw).astype('float32') sz = get_parameter_value(sz_p, params, 'sz', [128,128], 'size of the synthetic example') if len(sz) != 2: raise ValueError('Only two dimensional synthetic examples are currently supported for sz parameter') sz = [1, 1, sz[0], sz[1]] spacing = 1.0 / (np.array(sz[2:]).astype('float32') - 1) output_dir = os.path.normpath(args.output_directory)+'_kernel_weighting_type_' + native_str(kernel_weighting_type) image_output_dir = os.path.join(output_dir,'brain_affine_icbm') label_output_dir = os.path.join(output_dir,'label_affine_icbm') misc_output_dir = os.path.join(output_dir,'misc') pdf_output_dir = os.path.join(output_dir,'pdf') publication_figs = os.path.join(output_dir,'publication_figs') if not os.path.isdir(output_dir): os.makedirs(output_dir) if not os.path.isdir(image_output_dir): os.makedirs(image_output_dir) if not os.path.isdir(label_output_dir): os.makedirs(label_output_dir) if not os.path.isdir(misc_output_dir): os.makedirs(misc_output_dir) if not os.path.isdir(pdf_output_dir): os.makedirs(pdf_output_dir) if args.create_publication_figures: if not os.path.isdir(publication_figs): os.makedirs(publication_figs) pt = dict() pt['source_images'] = [] pt['target_images'] = [] pt['source_ids'] = [] pt['target_ids'] = [] im_io = fio.ImageIO() # image hdr hdr = dict() hdr['space origin'] = np.array([0,0,0]) hdr['spacing'] = np.array(list(spacing) + [spacing[-1]]) hdr['space directions'] = np.array([['1', '0', '0'], ['0', '1', '0'], ['0', '0', '1']]) hdr['dimension'] = 3 hdr['space'] = 'left-posterior-superior' hdr['sizes'] = list(sz[2:])+[1] for n in range(nr_of_pairs_to_generate): print('Writing file pair ' + str(n+1) + '/' + str(nr_of_pairs_to_generate)) if print_images: print_warped_name = os.path.join(pdf_output_dir,'registration_image_pair_{:05d}.pdf'.format(2*n+1)) else: print_warped_name = None publication_figures_directory = None if args.create_publication_figures and (n==0): publication_figures_directory = publication_figs I0Source, I1Target, weights, I0Label, I1Label, gt_map, gt_m = \ create_random_image_pair(weights_not_fluid=weights_not_fluid, weights_fluid=weights_fluid, weights_neutral=weights_neutral, weight_smoothing_std=args.weight_smoothing_std, multi_gaussian_stds=multi_gaussian_stds, kernel_weighting_type=kernel_weighting_type, randomize_momentum_on_circle=randomize_momentum_on_circle, randomize_in_sectors=randomize_in_sectors, put_weights_between_circles=put_weights_between_circles, start_with_fluid_weight=start_with_fluid_weight, use_random_source=use_random_source, use_fixed_source=use_fixed_source, add_texture_to_image=add_texture_to_image, texture_gaussian_smoothness=texture_gaussian_smoothness, texture_magnitude=texture_magnitude, nr_of_circles_to_generate=nr_of_circles_to_generate, circle_extent=circle_extent, sz=sz,spacing=spacing, nr_of_angles=nr_of_angles, multiplier_factor=multiplier_factor, momentum_smoothing=momentum_smoothing, visualize=visualize, visualize_warped=visualize_warped, print_warped_name=print_warped_name, publication_figures_directory=publication_figures_directory, image_pair_nr=n) source_filename = os.path.join(image_output_dir,'m{:d}.nii'.format(2*n+1)) target_filename = os.path.join(image_output_dir,'m{:d}.nii'.format(2*n+1+1)) source_label_filename = os.path.join(label_output_dir, 'm{:d}.nii'.format(2 * n + 1)) target_label_filename = os.path.join(label_output_dir, 'm{:d}.nii'.format(2 * n + 1 + 1)) gt_weights_filename = os.path.join(misc_output_dir,'gt_weights_{:05d}.pt'.format(2*n+1)) gt_momentum_filename = os.path.join(misc_output_dir,'gt_momentum_{:05d}.pt'.format(2*n+1)) gt_map_filename = os.path.join(misc_output_dir,'gt_map_{:05d}.pt'.format(2*n+1)) reshape_size = list(sz[2:]) + [1] # save these files im_io.write(filename=source_filename,data=I0Source.view().reshape(reshape_size),hdr=hdr) im_io.write(filename=target_filename,data=I1Target.view().reshape(reshape_size),hdr=hdr) im_io.write(filename=source_label_filename, data=I0Label.view().reshape(reshape_size), hdr=hdr) im_io.write(filename=target_label_filename, data=I1Label.view().reshape(reshape_size), hdr=hdr) torch.save(weights,gt_weights_filename) torch.save(gt_map,gt_map_filename) torch.save(gt_m,gt_momentum_filename) # create source/target configuration pt['source_images'].append(source_filename) pt['target_images'].append(target_filename) pt['source_ids'].append(2*n+1) pt['target_ids'].append(2*n+1+1) filename_pt = os.path.join(output_dir,'used_image_pairs.pt') torch.save(pt,filename_pt) config_json = os.path.join(output_dir,'config.json') params.write_JSON(config_json)
[ "numpy.sqrt", "numpy.random.rand", "torch.sqrt", "torch.from_numpy", "builtins.str", "mermaid.rungekutta_integrators.RK4", "builtins.range", "numpy.array", "torch.sum", "scipy.ndimage.binary_dilation", "numpy.sin", "mermaid.utils.centered_identity_map_multiN", "matplotlib.pyplot.imshow", "...
[((965, 1038), 'numpy.warnings.filterwarnings', 'np.warnings.filterwarnings', (['"""ignore"""', '"""invalid value encountered in sqrt"""'], {}), "('ignore', 'invalid value encountered in sqrt')\n", (991, 1038), True, 'import numpy as np\n'), ((262, 279), 'matplotlib.use', 'matplt.use', (['"""Agg"""'], {}), "('Agg')\n", (272, 279), True, 'import matplotlib as matplt\n'), ((1198, 1361), 'matplotlib.pyplot.quiver', 'plt.quiver', (['xc[::subsample, ::subsample]', 'yc[::subsample, ::subsample]', 'u[::subsample, ::subsample]', 'v[::subsample, ::subsample]'], {'color': 'color', 'scale': 'scale'}), '(xc[::subsample, ::subsample], yc[::subsample, ::subsample], u[::\n subsample, ::subsample], v[::subsample, ::subsample], color=color,\n scale=scale)\n', (1208, 1361), True, 'import matplotlib.pyplot as plt\n'), ((1904, 1921), 'mermaid.finite_differences.FD_np', 'fd.FD_np', (['spacing'], {}), '(spacing)\n', (1912, 1921), True, 'import mermaid.finite_differences as fd\n'), ((2798, 2862), 'mermaid.utils.centered_identity_map_multiN', 'utils.centered_identity_map_multiN', (['sz', 'spacing'], {'dtype': '"""float32"""'}), "(sz, spacing, dtype='float32')\n", (2832, 2862), True, 'import mermaid.utils as utils\n'), ((2886, 2906), 'numpy.zeros_like', 'np.zeros_like', (['dxc_d'], {}), '(dxc_d)\n', (2899, 2906), True, 'import numpy as np\n'), ((2921, 2939), 'builtins.range', 'range', (['(1)', '(maxr + 1)'], {}), '(1, maxr + 1)\n', (2926, 2939), False, 'from builtins import range\n'), ((5862, 5881), 'numpy.zeros_like', 'np.zeros_like', (['id_c'], {}), '(id_c)\n', (5875, 5881), True, 'import numpy as np\n'), ((7824, 7860), 'numpy.zeros', 'np.zeros', (['sh_std_im'], {'dtype': '"""float32"""'}), "(sh_std_im, dtype='float32')\n", (7832, 7860), True, 'import numpy as np\n'), ((8004, 8027), 'builtins.range', 'range', (['nr_of_mg_weights'], {}), '(nr_of_mg_weights)\n', (8009, 8027), False, 'from builtins import range\n'), ((8663, 8727), 'mermaid.utils.centered_identity_map_multiN', 'utils.centered_identity_map_multiN', (['sz', 'spacing'], {'dtype': '"""float32"""'}), "(sz, spacing, dtype='float32')\n", (8697, 8727), True, 'import mermaid.utils as utils\n'), ((9020, 9057), 'numpy.zeros', 'np.zeros', (['sh_weights'], {'dtype': '"""float32"""'}), "(sh_weights, dtype='float32')\n", (9028, 9057), True, 'import numpy as np\n'), ((9092, 9115), 'builtins.range', 'range', (['nr_of_mg_weights'], {}), '(nr_of_mg_weights)\n', (9097, 9115), False, 'from builtins import range\n'), ((9271, 9308), 'numpy.zeros', 'np.zeros', (['sh_ring_im'], {'dtype': '"""float32"""'}), "(sh_ring_im, dtype='float32')\n", (9279, 9308), True, 'import numpy as np\n'), ((12495, 12574), 'mermaid.custom_pytorch_extensions_module_version.GaussianFourierFilterGenerator', 'ce.GaussianFourierFilterGenerator', (['sz[2:]', 'spacing'], {'nr_of_slots': 'nr_of_gaussians'}), '(sz[2:], spacing, nr_of_slots=nr_of_gaussians)\n', (12528, 12574), True, 'import mermaid.custom_pytorch_extensions_module_version as ce\n'), ((14532, 14543), 'builtins.range', 'range', (['dims'], {}), '(dims)\n', (14537, 14543), False, 'from builtins import range\n'), ((16528, 16548), 'mermaid.module_parameters.ParameterDict', 'pars.ParameterDict', ([], {}), '()\n', (16546, 16548), True, 'import mermaid.module_parameters as pars\n'), ((16609, 16638), 'mermaid.forward_models.AdvectMap', 'fm.AdvectMap', (['sz[2:]', 'spacing'], {}), '(sz[2:], spacing)\n', (16621, 16638), True, 'import mermaid.forward_models as fm\n'), ((16752, 16812), 'mermaid.rungekutta_integrators.RK4', 'rk.RK4', (['advectionMap.f', 'advectionMap.u', 'pars_to_pass', 'params'], {}), '(advectionMap.f, advectionMap.u, pars_to_pass, params)\n', (16758, 16812), True, 'import mermaid.rungekutta_integrators as rk\n'), ((17202, 17224), 'numpy.zeros_like', 'np.zeros_like', (['im_orig'], {}), '(im_orig)\n', (17215, 17224), True, 'import numpy as np\n'), ((19305, 19323), 'builtins.range', 'range', (['nr_of_rings'], {}), '(nr_of_rings)\n', (19310, 19323), False, 'from builtins import range\n'), ((21597, 21661), 'mermaid.utils.centered_identity_map_multiN', 'utils.centered_identity_map_multiN', (['sz', 'spacing'], {'dtype': '"""float32"""'}), "(sz, spacing, dtype='float32')\n", (21631, 21661), True, 'import mermaid.utils as utils\n'), ((23980, 24070), 'mermaid.utils.compute_warped_image_multiNC', 'utils.compute_warped_image_multiNC', (['I0_source_orig', 'phi1_orig', 'spacing'], {'spline_order': '(1)'}), '(I0_source_orig, phi1_orig, spacing,\n spline_order=1)\n', (24014, 24070), True, 'import mermaid.utils as utils\n'), ((24179, 24240), 'mermaid.utils.get_warped_label_map', 'utils.get_warped_label_map', (['I0_label_orig', 'phi1_orig', 'spacing'], {}), '(I0_label_orig, phi1_orig, spacing)\n', (24205, 24240), True, 'import mermaid.utils as utils\n'), ((33209, 33288), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Creates a synthetic registration results"""'}), "(description='Creates a synthetic registration results')\n", (33232, 33288), False, 'import argparse\n'), ((37441, 37461), 'mermaid.module_parameters.ParameterDict', 'pars.ParameterDict', ([], {}), '()\n', (37459, 37461), True, 'import mermaid.module_parameters as pars\n'), ((44713, 44758), 'os.path.join', 'os.path.join', (['output_dir', '"""brain_affine_icbm"""'], {}), "(output_dir, 'brain_affine_icbm')\n", (44725, 44758), False, 'import os\n'), ((44781, 44826), 'os.path.join', 'os.path.join', (['output_dir', '"""label_affine_icbm"""'], {}), "(output_dir, 'label_affine_icbm')\n", (44793, 44826), False, 'import os\n'), ((44848, 44880), 'os.path.join', 'os.path.join', (['output_dir', '"""misc"""'], {}), "(output_dir, 'misc')\n", (44860, 44880), False, 'import os\n'), ((44901, 44932), 'os.path.join', 'os.path.join', (['output_dir', '"""pdf"""'], {}), "(output_dir, 'pdf')\n", (44913, 44932), False, 'import os\n'), ((44955, 44999), 'os.path.join', 'os.path.join', (['output_dir', '"""publication_figs"""'], {}), "(output_dir, 'publication_figs')\n", (44967, 44999), False, 'import os\n'), ((45667, 45680), 'mermaid.fileio.ImageIO', 'fio.ImageIO', ([], {}), '()\n', (45678, 45680), True, 'import mermaid.fileio as fio\n'), ((45740, 45759), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (45748, 45759), True, 'import numpy as np\n'), ((45849, 45910), 'numpy.array', 'np.array', (["[['1', '0', '0'], ['0', '1', '0'], ['0', '0', '1']]"], {}), "([['1', '0', '0'], ['0', '1', '0'], ['0', '0', '1']])\n", (45857, 45910), True, 'import numpy as np\n'), ((46031, 46061), 'builtins.range', 'range', (['nr_of_pairs_to_generate'], {}), '(nr_of_pairs_to_generate)\n', (46036, 46061), False, 'from builtins import range\n'), ((50071, 50118), 'os.path.join', 'os.path.join', (['output_dir', '"""used_image_pairs.pt"""'], {}), "(output_dir, 'used_image_pairs.pt')\n", (50083, 50118), False, 'import os\n'), ((50122, 50149), 'torch.save', 'torch.save', (['pt', 'filename_pt'], {}), '(pt, filename_pt)\n', (50132, 50149), False, 'import torch\n'), ((50168, 50207), 'os.path.join', 'os.path.join', (['output_dir', '"""config.json"""'], {}), "(output_dir, 'config.json')\n", (50180, 50207), False, 'import os\n'), ((1167, 1179), 'builtins.range', 'range', (['sz[0]'], {}), '(sz[0])\n', (1172, 1179), False, 'from builtins import range\n'), ((1180, 1192), 'builtins.range', 'range', (['sz[1]'], {}), '(sz[1])\n', (1185, 1192), False, 'from builtins import range\n'), ((5969, 5978), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (5976, 5978), True, 'import matplotlib.pyplot as plt\n'), ((5987, 6057), 'matplotlib.pyplot.quiver', 'plt.quiver', (['m_orig[0, 1, ...]', 'm_orig[0, 0, ...]'], {'color': '"""red"""', 'scale': '(5)'}), "(m_orig[0, 1, ...], m_orig[0, 0, ...], color='red', scale=5)\n", (5997, 6057), True, 'import matplotlib.pyplot as plt\n'), ((6064, 6081), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (6072, 6081), True, 'import matplotlib.pyplot as plt\n'), ((6090, 6100), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6098, 6100), True, 'import matplotlib.pyplot as plt\n'), ((6161, 6170), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6168, 6170), True, 'import matplotlib.pyplot as plt\n'), ((6179, 6226), 'matplotlib.pyplot.imshow', 'plt.imshow', (['input_im[0, 0, ...]'], {'origin': '"""lower"""'}), "(input_im[0, 0, ...], origin='lower')\n", (6189, 6226), True, 'import matplotlib.pyplot as plt\n'), ((6234, 6304), 'matplotlib.pyplot.quiver', 'plt.quiver', (['m_orig[0, 1, ...]', 'm_orig[0, 0, ...]'], {'color': '"""red"""', 'scale': '(5)'}), "(m_orig[0, 1, ...], m_orig[0, 0, ...], color='red', scale=5)\n", (6244, 6304), True, 'import matplotlib.pyplot as plt\n'), ((6311, 6328), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (6319, 6328), True, 'import matplotlib.pyplot as plt\n'), ((6337, 6352), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6345, 6352), True, 'import matplotlib.pyplot as plt\n'), ((6570, 6590), 'mermaid.module_parameters.ParameterDict', 'pars.ParameterDict', ([], {}), '()\n', (6588, 6590), True, 'import mermaid.module_parameters as pars\n'), ((10488, 10511), 'builtins.range', 'range', (['nr_of_mg_weights'], {}), '(nr_of_mg_weights)\n', (10493, 10511), False, 'from builtins import range\n'), ((10867, 10876), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (10874, 10876), True, 'import matplotlib.pyplot as plt\n'), ((10885, 10901), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (10896, 10901), True, 'import matplotlib.pyplot as plt\n'), ((10910, 10937), 'matplotlib.pyplot.imshow', 'plt.imshow', (['id_c[0, 0, ...]'], {}), '(id_c[0, 0, ...])\n', (10920, 10937), True, 'import matplotlib.pyplot as plt\n'), ((10946, 10960), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (10958, 10960), True, 'import matplotlib.pyplot as plt\n'), ((10969, 10985), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (10980, 10985), True, 'import matplotlib.pyplot as plt\n'), ((10994, 11021), 'matplotlib.pyplot.imshow', 'plt.imshow', (['id_c[0, 1, ...]'], {}), '(id_c[0, 1, ...])\n', (11004, 11021), True, 'import matplotlib.pyplot as plt\n'), ((11030, 11044), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (11042, 11044), True, 'import matplotlib.pyplot as plt\n'), ((11053, 11069), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (11064, 11069), True, 'import matplotlib.pyplot as plt\n'), ((11078, 11108), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ring_im[0, 0, ...]'], {}), '(ring_im[0, 0, ...])\n', (11088, 11108), True, 'import matplotlib.pyplot as plt\n'), ((11115, 11129), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (11127, 11129), True, 'import matplotlib.pyplot as plt\n'), ((11138, 11154), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(224)'], {}), '(224)\n', (11149, 11154), True, 'import matplotlib.pyplot as plt\n'), ((11232, 11242), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11240, 11242), True, 'import matplotlib.pyplot as plt\n'), ((11252, 11261), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (11259, 11261), True, 'import matplotlib.pyplot as plt\n'), ((11323, 11343), 'builtins.range', 'range', (['nr_of_weights'], {}), '(nr_of_weights)\n', (11328, 11343), False, 'from builtins import range\n'), ((11486, 11502), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(236)'], {}), '(236)\n', (11497, 11502), True, 'import matplotlib.pyplot as plt\n'), ((11511, 11529), 'matplotlib.pyplot.imshow', 'plt.imshow', (['std_im'], {}), '(std_im)\n', (11521, 11529), True, 'import matplotlib.pyplot as plt\n'), ((11538, 11552), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (11550, 11552), True, 'import matplotlib.pyplot as plt\n'), ((11561, 11584), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""weights"""'], {}), "('weights')\n", (11573, 11584), True, 'import matplotlib.pyplot as plt\n'), ((11593, 11603), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11601, 11603), True, 'import matplotlib.pyplot as plt\n'), ((12601, 12626), 'torch.from_numpy', 'torch.from_numpy', (['weights'], {}), '(weights)\n', (12617, 12626), False, 'import torch\n'), ((12654, 12673), 'torch.from_numpy', 'torch.from_numpy', (['m'], {}), '(m)\n', (12670, 12673), False, 'import torch\n'), ((12748, 12769), 'torch.sqrt', 'torch.sqrt', (['t_weights'], {}), '(t_weights)\n', (12758, 12769), False, 'import torch\n'), ((12809, 12999), 'mermaid.deep_smoothers.compute_weighted_multi_smooth_v', 'ds.compute_weighted_multi_smooth_v', ([], {'momentum': 't_momentum', 'weights': 'sqrt_weights', 'gaussian_stds': 'multi_gaussian_stds', 'gaussian_fourier_filter_generator': 'gaussian_fourier_filter_generator'}), '(momentum=t_momentum, weights=\n sqrt_weights, gaussian_stds=multi_gaussian_stds,\n gaussian_fourier_filter_generator=gaussian_fourier_filter_generator)\n', (12843, 12999), True, 'import mermaid.deep_smoothers as ds\n'), ((14376, 14391), 'mermaid.data_wrapper.MyTensor', 'MyTensor', (['*sz_m'], {}), '(*sz_m)\n', (14384, 14391), False, 'from mermaid.data_wrapper import AdaptVal, MyTensor\n'), ((16137, 16146), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (16144, 16146), True, 'import matplotlib.pyplot as plt\n'), ((16155, 16171), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (16166, 16171), True, 'import matplotlib.pyplot as plt\n'), ((16180, 16208), 'matplotlib.pyplot.imshow', 'plt.imshow', (['norm_localized_v'], {}), '(norm_localized_v)\n', (16190, 16208), True, 'import matplotlib.pyplot as plt\n'), ((16217, 16234), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (16225, 16234), True, 'import matplotlib.pyplot as plt\n'), ((16243, 16257), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (16255, 16257), True, 'import matplotlib.pyplot as plt\n'), ((16266, 16282), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (16277, 16282), True, 'import matplotlib.pyplot as plt\n'), ((16291, 16329), 'matplotlib.pyplot.quiver', 'plt.quiver', (['m[0, 1, ...]', 'm[0, 0, ...]'], {}), '(m[0, 1, ...], m[0, 0, ...])\n', (16301, 16329), True, 'import matplotlib.pyplot as plt\n'), ((16333, 16350), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (16341, 16350), True, 'import matplotlib.pyplot as plt\n'), ((16359, 16369), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16367, 16369), True, 'import matplotlib.pyplot as plt\n'), ((17425, 17445), 'mermaid.module_parameters.ParameterDict', 'pars.ParameterDict', ([], {}), '()\n', (17443, 17445), True, 'import mermaid.module_parameters as pars\n'), ((21093, 21102), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (21100, 21102), True, 'import matplotlib.pyplot as plt\n'), ((21111, 21162), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ring_im_orig[0, 0, ...]'], {'origin': '"""lower"""'}), "(ring_im_orig[0, 0, ...], origin='lower')\n", (21121, 21162), True, 'import matplotlib.pyplot as plt\n'), ((21168, 21183), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (21176, 21183), True, 'import matplotlib.pyplot as plt\n'), ((21337, 21346), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (21344, 21346), True, 'import matplotlib.pyplot as plt\n'), ((21355, 21394), 'matplotlib.pyplot.imshow', 'plt.imshow', (['std_im_orig'], {'origin': '"""lower"""'}), "(std_im_orig, origin='lower')\n", (21365, 21394), True, 'import matplotlib.pyplot as plt\n'), ((21402, 21417), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (21410, 21417), True, 'import matplotlib.pyplot as plt\n'), ((21426, 21440), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (21438, 21440), True, 'import matplotlib.pyplot as plt\n'), ((22603, 22612), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (22610, 22612), True, 'import matplotlib.pyplot as plt\n'), ((22621, 22672), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ring_im_orig[0, 0, ...]'], {'origin': '"""lower"""'}), "(ring_im_orig[0, 0, ...], origin='lower')\n", (22631, 22672), True, 'import matplotlib.pyplot as plt\n'), ((22794, 22811), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (22802, 22811), True, 'import matplotlib.pyplot as plt\n'), ((22820, 22835), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (22828, 22835), True, 'import matplotlib.pyplot as plt\n'), ((23932, 23957), 'torch.from_numpy', 'torch.from_numpy', (['ring_im'], {}), '(ring_im)\n', (23948, 23957), False, 'import torch\n'), ((24127, 24157), 'torch.from_numpy', 'torch.from_numpy', (['ring_im_orig'], {}), '(ring_im_orig)\n', (24143, 24157), False, 'import torch\n'), ((24301, 24310), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (24308, 24310), True, 'import matplotlib.pyplot as plt\n'), ((24402, 24417), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (24410, 24417), True, 'import matplotlib.pyplot as plt\n'), ((27820, 27905), 'mermaid.utils.compute_warped_image_multiNC', 'utils.compute_warped_image_multiNC', (['I0_source_w', 'phi1_w', 'spacing'], {'spline_order': '(1)'}), '(I0_source_w, phi1_w, spacing, spline_order=1\n )\n', (27854, 27905), True, 'import mermaid.utils as utils\n'), ((28028, 28083), 'mermaid.utils.get_warped_label_map', 'utils.get_warped_label_map', (['I0_label_w', 'phi1_w', 'spacing'], {}), '(I0_label_w, phi1_w, spacing)\n', (28054, 28083), True, 'import mermaid.utils as utils\n'), ((28727, 28736), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (28734, 28736), True, 'import matplotlib.pyplot as plt\n'), ((28800, 28820), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(1)'], {}), '(3, 4, 1)\n', (28811, 28820), True, 'import matplotlib.pyplot as plt\n'), ((28889, 28908), 'matplotlib.pyplot.title', 'plt.title', (['"""source"""'], {}), "('source')\n", (28898, 28908), True, 'import matplotlib.pyplot as plt\n'), ((28917, 28937), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(2)'], {}), '(3, 4, 2)\n', (28928, 28937), True, 'import matplotlib.pyplot as plt\n'), ((29006, 29034), 'matplotlib.pyplot.title', 'plt.title', (['"""warped = target"""'], {}), "('warped = target')\n", (29015, 29034), True, 'import matplotlib.pyplot as plt\n'), ((29043, 29063), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(3)'], {}), '(3, 4, 3)\n', (29054, 29063), True, 'import matplotlib.pyplot as plt\n'), ((29360, 29380), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(4)'], {}), '(3, 4, 4)\n', (29371, 29380), True, 'import matplotlib.pyplot as plt\n'), ((29729, 29749), 'builtins.range', 'range', (['nr_of_weights'], {}), '(nr_of_weights)\n', (29734, 29749), False, 'from builtins import range\n'), ((30088, 30109), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(12)'], {}), '(3, 4, 12)\n', (30099, 30109), True, 'import matplotlib.pyplot as plt\n'), ((30116, 30134), 'matplotlib.pyplot.imshow', 'plt.imshow', (['std_im'], {}), '(std_im)\n', (30126, 30134), True, 'import matplotlib.pyplot as plt\n'), ((30143, 30159), 'matplotlib.pyplot.title', 'plt.title', (['"""std"""'], {}), "('std')\n", (30152, 30159), True, 'import matplotlib.pyplot as plt\n'), ((30168, 30182), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (30180, 30182), True, 'import matplotlib.pyplot as plt\n'), ((30365, 30374), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (30372, 30374), True, 'import matplotlib.pyplot as plt\n'), ((30462, 30479), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (30470, 30479), True, 'import matplotlib.pyplot as plt\n'), ((30488, 30503), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (30496, 30503), True, 'import matplotlib.pyplot as plt\n'), ((30666, 30675), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (30673, 30675), True, 'import matplotlib.pyplot as plt\n'), ((30763, 30780), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (30771, 30780), True, 'import matplotlib.pyplot as plt\n'), ((30789, 30804), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (30797, 30804), True, 'import matplotlib.pyplot as plt\n'), ((30967, 30976), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (30974, 30976), True, 'import matplotlib.pyplot as plt\n'), ((31296, 31313), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (31304, 31313), True, 'import matplotlib.pyplot as plt\n'), ((31322, 31337), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (31330, 31337), True, 'import matplotlib.pyplot as plt\n'), ((31510, 31519), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (31517, 31519), True, 'import matplotlib.pyplot as plt\n'), ((31839, 31856), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (31847, 31856), True, 'import matplotlib.pyplot as plt\n'), ((31865, 31880), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (31873, 31880), True, 'import matplotlib.pyplot as plt\n'), ((32053, 32062), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (32060, 32062), True, 'import matplotlib.pyplot as plt\n'), ((32071, 32105), 'matplotlib.pyplot.imshow', 'plt.imshow', (['std_im'], {'origin': '"""lower"""'}), "(std_im, origin='lower')\n", (32081, 32105), True, 'import matplotlib.pyplot as plt\n'), ((32113, 32127), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (32125, 32127), True, 'import matplotlib.pyplot as plt\n'), ((32136, 32153), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (32144, 32153), True, 'import matplotlib.pyplot as plt\n'), ((32162, 32177), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (32170, 32177), True, 'import matplotlib.pyplot as plt\n'), ((37367, 37389), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (37378, 37389), False, 'import random\n'), ((37398, 37426), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (37415, 37426), False, 'import torch\n'), ((43829, 43851), 'numpy.sqrt', 'np.sqrt', (['weights_fluid'], {}), '(weights_fluid)\n', (43836, 43851), True, 'import numpy as np\n'), ((43878, 43902), 'numpy.sqrt', 'np.sqrt', (['weights_neutral'], {}), '(weights_neutral)\n', (43885, 43902), True, 'import numpy as np\n'), ((43931, 43957), 'numpy.sqrt', 'np.sqrt', (['weights_not_fluid'], {}), '(weights_not_fluid)\n', (43938, 43957), True, 'import numpy as np\n'), ((44655, 44688), 'future.utils.native_str', 'native_str', (['kernel_weighting_type'], {}), '(kernel_weighting_type)\n', (44665, 44688), False, 'from future.utils import native_str\n'), ((45011, 45036), 'os.path.isdir', 'os.path.isdir', (['output_dir'], {}), '(output_dir)\n', (45024, 45036), False, 'import os\n'), ((45046, 45069), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (45057, 45069), False, 'import os\n'), ((45082, 45113), 'os.path.isdir', 'os.path.isdir', (['image_output_dir'], {}), '(image_output_dir)\n', (45095, 45113), False, 'import os\n'), ((45123, 45152), 'os.makedirs', 'os.makedirs', (['image_output_dir'], {}), '(image_output_dir)\n', (45134, 45152), False, 'import os\n'), ((45165, 45196), 'os.path.isdir', 'os.path.isdir', (['label_output_dir'], {}), '(label_output_dir)\n', (45178, 45196), False, 'import os\n'), ((45206, 45235), 'os.makedirs', 'os.makedirs', (['label_output_dir'], {}), '(label_output_dir)\n', (45217, 45235), False, 'import os\n'), ((45248, 45278), 'os.path.isdir', 'os.path.isdir', (['misc_output_dir'], {}), '(misc_output_dir)\n', (45261, 45278), False, 'import os\n'), ((45288, 45316), 'os.makedirs', 'os.makedirs', (['misc_output_dir'], {}), '(misc_output_dir)\n', (45299, 45316), False, 'import os\n'), ((45329, 45358), 'os.path.isdir', 'os.path.isdir', (['pdf_output_dir'], {}), '(pdf_output_dir)\n', (45342, 45358), False, 'import os\n'), ((45368, 45395), 'os.makedirs', 'os.makedirs', (['pdf_output_dir'], {}), '(pdf_output_dir)\n', (45379, 45395), False, 'import os\n'), ((49693, 49733), 'torch.save', 'torch.save', (['weights', 'gt_weights_filename'], {}), '(weights, gt_weights_filename)\n', (49703, 49733), False, 'import torch\n'), ((49741, 49776), 'torch.save', 'torch.save', (['gt_map', 'gt_map_filename'], {}), '(gt_map, gt_map_filename)\n', (49751, 49776), False, 'import torch\n'), ((49784, 49822), 'torch.save', 'torch.save', (['gt_m', 'gt_momentum_filename'], {}), '(gt_m, gt_momentum_filename)\n', (49794, 49822), False, 'import torch\n'), ((5365, 5425), 'scipy.ndimage.binary_dilation', 'ndimage.binary_dilation', (['(input_im[:, 0, ...] == cur_ring_val)'], {}), '(input_im[:, 0, ...] == cur_ring_val)\n', (5388, 5425), True, 'import scipy.ndimage as ndimage\n'), ((6908, 6917), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (6915, 6917), True, 'import matplotlib.pyplot as plt\n'), ((6930, 6946), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (6941, 6946), True, 'import matplotlib.pyplot as plt\n'), ((6959, 6988), 'matplotlib.pyplot.imshow', 'plt.imshow', (['m_orig[0, 0, ...]'], {}), '(m_orig[0, 0, ...])\n', (6969, 6988), True, 'import matplotlib.pyplot as plt\n'), ((7001, 7017), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (7012, 7017), True, 'import matplotlib.pyplot as plt\n'), ((7030, 7054), 'matplotlib.pyplot.imshow', 'plt.imshow', (['m[0, 0, ...]'], {}), '(m[0, 0, ...])\n', (7040, 7054), True, 'import matplotlib.pyplot as plt\n'), ((7067, 7094), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""smoothed mx"""'], {}), "('smoothed mx')\n", (7079, 7094), True, 'import matplotlib.pyplot as plt\n'), ((7107, 7117), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7115, 7117), True, 'import matplotlib.pyplot as plt\n'), ((7185, 7194), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (7192, 7194), True, 'import matplotlib.pyplot as plt\n'), ((7207, 7254), 'matplotlib.pyplot.imshow', 'plt.imshow', (['input_im[0, 0, ...]'], {'origin': '"""lower"""'}), "(input_im[0, 0, ...], origin='lower')\n", (7217, 7254), True, 'import matplotlib.pyplot as plt\n'), ((7356, 7373), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (7364, 7373), True, 'import matplotlib.pyplot as plt\n'), ((7386, 7401), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (7394, 7401), True, 'import matplotlib.pyplot as plt\n'), ((11357, 11393), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(1 + nr_of_weights)'], {}), '(2, 3, 1 + nr_of_weights)\n', (11368, 11393), True, 'import matplotlib.pyplot as plt\n'), ((11402, 11453), 'matplotlib.pyplot.imshow', 'plt.imshow', (['weights[0, cw, ...]'], {'vmin': '(0.0)', 'vmax': '(1.0)'}), '(weights[0, cw, ...], vmin=0.0, vmax=1.0)\n', (11412, 11453), True, 'import matplotlib.pyplot as plt\n'), ((11462, 11476), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (11474, 11476), True, 'import matplotlib.pyplot as plt\n'), ((13257, 13444), 'mermaid.deep_smoothers.compute_weighted_multi_smooth_v', 'ds.compute_weighted_multi_smooth_v', ([], {'momentum': 't_momentum', 'weights': 't_weights', 'gaussian_stds': 'multi_gaussian_stds', 'gaussian_fourier_filter_generator': 'gaussian_fourier_filter_generator'}), '(momentum=t_momentum, weights=t_weights,\n gaussian_stds=multi_gaussian_stds, gaussian_fourier_filter_generator=\n gaussian_fourier_filter_generator)\n', (13291, 13444), True, 'import mermaid.deep_smoothers as ds\n'), ((15322, 15358), 'torch.sum', 'torch.sum', (['(roc * sqrt_weights)'], {'dim': '(1)'}), '(roc * sqrt_weights, dim=1)\n', (15331, 15358), False, 'import torch\n'), ((16880, 16918), 'mermaid.utils.identity_map_multiN', 'utils.identity_map_multiN', (['sz', 'spacing'], {}), '(sz, spacing)\n', (16905, 16918), True, 'import mermaid.utils as utils\n'), ((20442, 20462), 'mermaid.module_parameters.ParameterDict', 'pars.ParameterDict', ([], {}), '()\n', (20460, 20462), True, 'import mermaid.module_parameters as pars\n'), ((23299, 23308), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (23306, 23308), True, 'import matplotlib.pyplot as plt\n'), ((23321, 23367), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ring_im[0, 0, ...]'], {'origin': '"""lower"""'}), "(ring_im[0, 0, ...], origin='lower')\n", (23331, 23367), True, 'import matplotlib.pyplot as plt\n'), ((23379, 23394), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (23387, 23394), True, 'import matplotlib.pyplot as plt\n'), ((26520, 26529), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (26527, 26529), True, 'import matplotlib.pyplot as plt\n'), ((26542, 26602), 'matplotlib.pyplot.imshow', 'plt.imshow', (['warped_source_im_orig[0, 0, ...]'], {'origin': '"""lower"""'}), "(warped_source_im_orig[0, 0, ...], origin='lower')\n", (26552, 26602), True, 'import matplotlib.pyplot as plt\n'), ((26741, 26758), 'matplotlib.pyplot.axis', 'plt.axis', (['"""image"""'], {}), "('image')\n", (26749, 26758), True, 'import matplotlib.pyplot as plt\n'), ((26771, 26786), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (26779, 26786), True, 'import matplotlib.pyplot as plt\n'), ((27762, 27796), 'torch.from_numpy', 'torch.from_numpy', (['warped_source_im'], {}), '(warped_source_im)\n', (27778, 27796), False, 'import torch\n'), ((27966, 28005), 'torch.from_numpy', 'torch.from_numpy', (['warped_source_im_orig'], {}), '(warped_source_im_orig)\n', (27982, 28005), False, 'import torch\n'), ((29182, 29204), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (29193, 29204), True, 'import numpy as np\n'), ((29296, 29318), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (29307, 29318), True, 'import numpy as np\n'), ((29499, 29521), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (29510, 29521), True, 'import numpy as np\n'), ((29613, 29635), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (29624, 29635), True, 'import numpy as np\n'), ((29763, 29788), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(3)', '(4)', '(5 + cw)'], {}), '(3, 4, 5 + cw)\n', (29774, 29788), True, 'import matplotlib.pyplot as plt\n'), ((30064, 30078), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (30076, 30078), True, 'import matplotlib.pyplot as plt\n'), ((30238, 30268), 'matplotlib.pyplot.savefig', 'plt.savefig', (['print_warped_name'], {}), '(print_warped_name)\n', (30249, 30268), True, 'import matplotlib.pyplot as plt\n'), ((30295, 30305), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (30303, 30305), True, 'import matplotlib.pyplot as plt\n'), ((31116, 31138), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (31127, 31138), True, 'import numpy as np\n'), ((31232, 31254), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (31243, 31254), True, 'import numpy as np\n'), ((31659, 31681), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (31670, 31681), True, 'import numpy as np\n'), ((31775, 31797), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(40)'], {}), '(-1, 1, 40)\n', (31786, 31797), True, 'import numpy as np\n'), ((41745, 41759), 'numpy.array', 'np.array', (['mgsl'], {}), '(mgsl)\n', (41753, 41759), True, 'import numpy as np\n'), ((41867, 41899), 'numpy.array', 'np.array', (['[0.01, 0.05, 0.1, 0.2]'], {}), '([0.01, 0.05, 0.1, 0.2])\n', (41875, 41899), True, 'import numpy as np\n'), ((41966, 41995), 'numpy.array', 'np.array', (['multi_gaussian_stds'], {}), '(multi_gaussian_stds)\n', (41974, 41995), True, 'import numpy as np\n'), ((42207, 42219), 'numpy.array', 'np.array', (['cw'], {}), '(cw)\n', (42215, 42219), True, 'import numpy as np\n'), ((42321, 42345), 'numpy.array', 'np.array', (['[0, 0, 0, 1.0]'], {}), '([0, 0, 0, 1.0])\n', (42329, 42345), True, 'import numpy as np\n'), ((42406, 42433), 'numpy.array', 'np.array', (['weights_not_fluid'], {}), '(weights_not_fluid)\n', (42414, 42433), True, 'import numpy as np\n'), ((42770, 42782), 'numpy.array', 'np.array', (['cw'], {}), '(cw)\n', (42778, 42782), True, 'import numpy as np\n'), ((42872, 42902), 'numpy.array', 'np.array', (['[0.2, 0.5, 0.2, 0.1]'], {}), '([0.2, 0.5, 0.2, 0.1])\n', (42880, 42902), True, 'import numpy as np\n'), ((42951, 42974), 'numpy.array', 'np.array', (['weights_fluid'], {}), '(weights_fluid)\n', (42959, 42974), True, 'import numpy as np\n'), ((43320, 43332), 'numpy.array', 'np.array', (['cw'], {}), '(cw)\n', (43328, 43332), True, 'import numpy as np\n'), ((43428, 43452), 'numpy.array', 'np.array', (['[0, 0, 0, 1.0]'], {}), '([0, 0, 0, 1.0])\n', (43436, 43452), True, 'import numpy as np\n'), ((43518, 43543), 'numpy.array', 'np.array', (['weights_neutral'], {}), '(weights_neutral)\n', (43526, 43543), True, 'import numpy as np\n'), ((44587, 44626), 'os.path.normpath', 'os.path.normpath', (['args.output_directory'], {}), '(args.output_directory)\n', (44603, 44626), False, 'import os\n'), ((45452, 45483), 'os.path.isdir', 'os.path.isdir', (['publication_figs'], {}), '(publication_figs)\n', (45465, 45483), False, 'import os\n'), ((45497, 45526), 'os.makedirs', 'os.makedirs', (['publication_figs'], {}), '(publication_figs)\n', (45508, 45526), False, 'import os\n'), ((3222, 3241), 'builtins.range', 'range', (['nr_of_angles'], {}), '(nr_of_angles)\n', (3227, 3241), False, 'from builtins import range\n'), ((4878, 4938), 'scipy.ndimage.binary_dilation', 'ndimage.binary_dilation', (['(input_im[:, 0, ...] == cur_ring_val)'], {}), '(input_im[:, 0, ...] == cur_ring_val)\n', (4901, 4938), True, 'import scipy.ndimage as ndimage\n'), ((6725, 6760), 'mermaid.smoother_factory.SmootherFactory', 'sf.SmootherFactory', (['sz[2:]', 'spacing'], {}), '(sz[2:], spacing)\n', (6743, 6760), True, 'import mermaid.smoother_factory as sf\n'), ((11779, 11820), 'numpy.linspace', 'np.linspace', (['(0.0)', 'extent', '(nr_of_rings + 1)'], {}), '(0.0, extent, nr_of_rings + 1)\n', (11790, 11820), True, 'import numpy as np\n'), ((12061, 12102), 'numpy.linspace', 'np.linspace', (['(0.0)', 'extent', '(nr_of_rings + 1)'], {}), '(0.0, extent, nr_of_rings + 1)\n', (12072, 12102), True, 'import numpy as np\n'), ((15532, 15565), 'torch.sum', 'torch.sum', (['(roc * t_weights)'], {'dim': '(1)'}), '(roc * t_weights, dim=1)\n', (15541, 15565), False, 'import torch\n'), ((16693, 16722), 'torch.from_numpy', 'torch.from_numpy', (['localized_v'], {}), '(localized_v)\n', (16709, 16722), False, 'import torch\n'), ((17158, 17175), 'numpy.floor', 'np.floor', (['im_orig'], {}), '(im_orig)\n', (17166, 17175), True, 'import numpy as np\n'), ((17585, 17620), 'mermaid.smoother_factory.SmootherFactory', 'sf.SmootherFactory', (['sz[2:]', 'spacing'], {}), '(sz[2:], spacing)\n', (17603, 17620), True, 'import mermaid.smoother_factory as sf\n'), ((24729, 24751), 'torch.from_numpy', 'torch.from_numpy', (['id_c'], {}), '(id_c)\n', (24745, 24751), False, 'import torch\n'), ((24920, 24950), 'torch.from_numpy', 'torch.from_numpy', (['weights_orig'], {}), '(weights_orig)\n', (24936, 24950), False, 'import torch\n'), ((27300, 27309), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (27307, 27309), True, 'import matplotlib.pyplot as plt\n'), ((27326, 27372), 'matplotlib.pyplot.imshow', 'plt.imshow', (['ring_im[0, 0, ...]'], {'origin': '"""lower"""'}), "(ring_im[0, 0, ...], origin='lower')\n", (27336, 27372), True, 'import matplotlib.pyplot as plt\n'), ((27388, 27403), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (27396, 27403), True, 'import matplotlib.pyplot as plt\n'), ((29848, 29904), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(weights[0, cw, ...] ** 2)'], {'vmin': '(0.0)', 'vmax': '(1.0)'}), '(weights[0, cw, ...] ** 2, vmin=0.0, vmax=1.0)\n', (29858, 29904), True, 'import matplotlib.pyplot as plt\n'), ((29937, 29988), 'matplotlib.pyplot.imshow', 'plt.imshow', (['weights[0, cw, ...]'], {'vmin': '(0.0)', 'vmax': '(1.0)'}), '(weights[0, cw, ...], vmin=0.0, vmax=1.0)\n', (29947, 29988), True, 'import matplotlib.pyplot as plt\n'), ((44222, 44234), 'numpy.array', 'np.array', (['cw'], {}), '(cw)\n', (44230, 44234), True, 'import numpy as np\n'), ((46118, 46146), 'builtins.str', 'str', (['nr_of_pairs_to_generate'], {}), '(nr_of_pairs_to_generate)\n', (46121, 46146), False, 'from builtins import str\n'), ((3406, 3427), 'numpy.cos', 'np.cos', (['angles[afrom]'], {}), '(angles[afrom])\n', (3412, 3427), True, 'import numpy as np\n'), ((3506, 3525), 'numpy.cos', 'np.cos', (['angles[ato]'], {}), '(angles[ato])\n', (3512, 3525), True, 'import numpy as np\n'), ((3566, 3626), 'scipy.ndimage.binary_dilation', 'ndimage.binary_dilation', (['(input_im[:, 0, ...] == cur_ring_val)'], {}), '(input_im[:, 0, ...] == cur_ring_val)\n', (3589, 3626), True, 'import scipy.ndimage as ndimage\n'), ((3941, 3964), 'numpy.random.randint', 'np.random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (3958, 3964), True, 'import numpy as np\n'), ((15682, 15733), 'torch.transpose', 'torch.transpose', (['multi_smooth_v[:, :, n, ...]', '(0)', '(1)'], {}), '(multi_smooth_v[:, :, n, ...], 0, 1)\n', (15697, 15733), False, 'import torch\n'), ((15751, 15784), 'torch.sum', 'torch.sum', (['(roc * t_weights)'], {'dim': '(1)'}), '(roc * t_weights, dim=1)\n', (15760, 15784), False, 'import torch\n'), ((17308, 17332), 'numpy.random.random', 'np.random.random', (['sz[2:]'], {}), '(sz[2:])\n', (17324, 17332), True, 'import numpy as np\n'), ((20649, 20700), 'mermaid.smoother_factory.SmootherFactory', 'sf.SmootherFactory', (['weights_orig.shape[2:]', 'spacing'], {}), '(weights_orig.shape[2:], spacing)\n', (20667, 20700), True, 'import mermaid.smoother_factory as sf\n'), ((30022, 30050), 'builtins.str', 'str', (['multi_gaussian_stds[cw]'], {}), '(multi_gaussian_stds[cw])\n', (30025, 30050), False, 'from builtins import str\n'), ((44529, 44545), 'numpy.array', 'np.array', (['sz[2:]'], {}), '(sz[2:])\n', (44537, 44545), True, 'import numpy as np\n'), ((3354, 3375), 'numpy.sin', 'np.sin', (['angles[afrom]'], {}), '(angles[afrom])\n', (3360, 3375), True, 'import numpy as np\n'), ((3458, 3477), 'numpy.sin', 'np.sin', (['angles[ato]'], {}), '(angles[ato])\n', (3464, 3477), True, 'import numpy as np\n'), ((46101, 46111), 'builtins.str', 'str', (['(n + 1)'], {}), '(n + 1)\n', (46104, 46111), False, 'from builtins import str\n'), ((13898, 13935), 'torch.from_numpy', 'torch.from_numpy', (['multi_gaussian_stds'], {}), '(multi_gaussian_stds)\n', (13914, 13935), False, 'import torch\n'), ((3148, 3176), 'numpy.random.rand', 'np.random.rand', (['nr_of_angles'], {}), '(nr_of_angles)\n', (3162, 3176), True, 'import numpy as np\n'), ((5643, 5659), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5657, 5659), True, 'import numpy as np\n'), ((11944, 11977), 'numpy.random.random', 'np.random.random', (['(nr_of_rings + 1)'], {}), '(nr_of_rings + 1)\n', (11960, 11977), True, 'import numpy as np\n'), ((6823, 6847), 'torch.from_numpy', 'torch.from_numpy', (['m_orig'], {}), '(m_orig)\n', (6839, 6847), False, 'import torch\n'), ((17699, 17727), 'torch.from_numpy', 'torch.from_numpy', (['rand_noise'], {}), '(rand_noise)\n', (17715, 17727), False, 'import torch\n'), ((20881, 20911), 'torch.from_numpy', 'torch.from_numpy', (['weights_orig'], {}), '(weights_orig)\n', (20897, 20911), False, 'import torch\n')]
import os import numpy as np import sys import gc import torch from .tools import fix_seed from torch_geometric.utils import is_undirected fix_seed(1234) class AutoEDA(object): """ A tool box for Exploratory Data Analysis (EDA) Parameters: ---------- n_class: int number of classes ---------- """ def __init__(self, n_class): self.info = {'n_class': n_class} def get_info(self, data): self.get_feature_info(data['fea_table']) self.get_edge_info(data['edge_file']) self.set_priori_knowledges() self.get_label_weights(data, reweighting=True) return self.info def get_feature_info(self, df): """ Get information of the original node features: number of nodes, number of features, etc. Remove those features which have only one value. """ unique_counts = df.nunique() unique_counts = unique_counts[unique_counts == 1] df.drop(unique_counts.index, axis=1, inplace=True) self.info['num_nodes'] = df.shape[0] self.info['num_features'] = df.shape[1] - 1 print('Number of Nodes:', self.info['num_nodes']) print('Number of Original Features:', self.info['num_features']) def get_edge_info(self, df): """ Get information of the edges: number of edges, if weighted, if directed, Max / Min weight, etc. """ self.info['num_edges'] = df.shape[0] min_weight, max_weight = df['edge_weight'].min(), df['edge_weight'].max() if min_weight != max_weight: self.info['weighted'] = True else: self.info['weighted'] = False edge_index = df[['src_idx', 'dst_idx']].to_numpy() edge_index = sorted(edge_index, key=lambda d: d[0]) edge_index = torch.tensor(edge_index, dtype=torch.long).transpose(0, 1) self.info['directed'] = not is_undirected(edge_index, num_nodes=self.info['num_nodes']) print('Number of Edges:', self.info['num_edges']) print('Is Directed Graph:', self.info['directed']) print('Is Weighted Graph:',self.info['weighted']) print('Max Weight:', max_weight, 'Min Weight:', min_weight) def set_priori_knowledges(self): """ Set some hyper parameters to their initial value according to some priori knowledges. """ if self.info['num_features'] == 0: if self.info['directed']: self.info['dropedge_rate'] = 0.5 self.info['chosen_models'] = ['ResGCN', 'GraphConvNet', 'GraphSAGE'] self.info['ensemble_threshold'] = 0.01 else: self.info['dropedge_rate'] = 0 self.info['chosen_models'] = ['GraphConvNet','GIN','GraphSAGE'] self.info['ensemble_threshold'] = 0.01 else: if self.info['directed']: self.info['dropedge_rate'] = 0.5 self.info['chosen_models'] = ['GraphConvNet','GraphSAGE','ResGCN'] self.info['ensemble_threshold'] = 0.02 else: if self.info['num_edges'] / self.info['num_nodes']>= 10: self.info['dropedge_rate'] = 0.5 self.info['chosen_models'] = ['ARMA','GraphSAGE', 'IncepGCN'] self.info['ensemble_threshold'] = 0.02 else: self.info['dropedge_rate'] = 0.5 self.info['chosen_models'] = ['ARMA','IncepGCN','GraphConvNet','SG'] self.info['ensemble_threshold'] = 0.03 if self.info['num_edges'] / self.info['num_nodes'] >= 200: self.info['num_layers'] = 1 self.info['init_hidden_size'] = 5 elif self.info['num_edges'] / self.info['num_nodes'] >= 100: self.info['num_layers'] = 2 self.info['init_hidden_size'] = 5 else: self.info['num_layers'] = 2 self.info['init_hidden_size'] = 7 if self.info['num_edges'] / self.info['num_nodes'] >= 10: self.info['use_linear'] = True self.info['dropout_rate'] = 0.2 else: self.info['use_linear'] = False self.info['dropout_rate'] = 0.5 self.info['lr'] = 0.005 if self.info['num_features'] == 0: self.info['feature_type'] = ['svd'] # one_hot / svd / degree / node2vec / adj else: self.info['feature_type'] = ['original', 'svd'] self.info['normalize_features'] = 'None' def get_label_weights(self, data, reweighting=True): """ Compute the weights of labels as the weight when computing loss. """ if not reweighting: self.info['label_weights'] = None return groupby_data_orginal = data['train_label'].groupby('label').count() label_weights = groupby_data_orginal.iloc[:,0] if len(label_weights) < 10 or max(label_weights) < min(label_weights) * 10: self.info['label_weights'] = None return label_weights = 1 / np.sqrt(label_weights) self.info['label_weights'] = torch.tensor(label_weights.values,dtype=torch.float32) print('Label Weights:', self.info['label_weights'])
[ "torch.tensor", "numpy.sqrt", "torch_geometric.utils.is_undirected" ]
[((5173, 5228), 'torch.tensor', 'torch.tensor', (['label_weights.values'], {'dtype': 'torch.float32'}), '(label_weights.values, dtype=torch.float32)\n', (5185, 5228), False, 'import torch\n'), ((1909, 1968), 'torch_geometric.utils.is_undirected', 'is_undirected', (['edge_index'], {'num_nodes': "self.info['num_nodes']"}), "(edge_index, num_nodes=self.info['num_nodes'])\n", (1922, 1968), False, 'from torch_geometric.utils import is_undirected\n'), ((5113, 5135), 'numpy.sqrt', 'np.sqrt', (['label_weights'], {}), '(label_weights)\n', (5120, 5135), True, 'import numpy as np\n'), ((1813, 1855), 'torch.tensor', 'torch.tensor', (['edge_index'], {'dtype': 'torch.long'}), '(edge_index, dtype=torch.long)\n', (1825, 1855), False, 'import torch\n')]
""" @brief test log(time=2s) """ import unittest from logging import getLogger import numpy import pandas from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, GradientBoostingRegressor from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from pyquickhelper.pycode import ExtTestCase from mlprodict.onnx_conv import to_onnx from mlprodict.onnxrt import OnnxInference class TestOnnxrtPythonRuntimeMlTree(ExtTestCase): def setUp(self): logger = getLogger('skl2onnx') logger.disabled = True def test_onnxrt_python_DecisionTreeClassifier(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeClassifier() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=5) def test_onnxrt_python_DecisionTreeClassifier_plusten(self): iris = load_iris() X, y = iris.data, iris.target y += 10 X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeClassifier() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=5) def test_onnxrt_python_GradientBoostingClassifier2(self): iris = load_iris() X, y = iris.data, iris.target y[y == 2] = 1 X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = GradientBoostingClassifier() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=3) def test_onnxrt_python_GradientBoostingClassifier3(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = GradientBoostingClassifier() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=3) def test_onnxrt_python_DecisionTreeClassifier_mlabel(self): iris = load_iris() X, y_ = iris.data, iris.target y = numpy.zeros((y_.shape[0], 3), dtype=int) y[y_ == 0, 0] = 1 y[y_ == 1, 1] = 1 y[y_ == 2, 2] = 1 X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeClassifier() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) exp = numpy.array(clr.predict_proba(X_test)) exp = exp.reshape(max(exp.shape), -1) p = y['output_probability'] got = pandas.DataFrame(p.values, columns=p.columns) self.assertEqualArray(exp, got, decimal=5) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) def test_onnxrt_python_DecisionTreeRegressor(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeRegressor() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleRegressor", text) for i in range(0, 20): y = oinf.run({'X': X_test.astype(numpy.float32)[i: i + 1]}) self.assertEqual(list(sorted(y)), ['variable']) lexp = clr.predict(X_test[i: i + 1]) self.assertEqual(lexp.shape, y['variable'].shape) self.assertEqualArray(lexp, y['variable']) for i in range(0, 20): y = oinf.run({'X': X_test.astype(numpy.float32)[i: i + 2]}) self.assertEqual(list(sorted(y)), ['variable']) lexp = clr.predict(X_test[i: i + 2]) self.assertEqual(lexp.shape, y['variable'].shape) self.assertEqualArray(lexp, y['variable']) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), ['variable']) lexp = clr.predict(X_test) self.assertEqual(lexp.shape, y['variable'].shape) self.assertEqualArray(lexp, y['variable']) def test_onnxrt_python_DecisionTreeRegressor2(self): iris = load_iris() X, y = iris.data, iris.target y = numpy.vstack([y, y]).T X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeRegressor() clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleRegressor", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), ['variable']) lexp = clr.predict(X_test) self.assertEqual(lexp.shape, y['variable'].shape) self.assertEqualArray(lexp, y['variable']) def test_onnxrt_python_DecisionTreeRegressor64(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split( X, y, random_state=11) # pylint: disable=W0612 clr = DecisionTreeRegressor(min_samples_leaf=7) clr.fit(X_train, y_train) lexp = clr.predict(X_test) model_def64 = to_onnx(clr, X_train.astype(numpy.float64), rewrite_ops=True) smodel_def64 = str(model_def64) self.assertIn('TreeEnsembleRegressorDouble', smodel_def64) self.assertIn('double_data', smodel_def64) oinf64 = OnnxInference(model_def64) text = "\n".join(map(lambda x: str(x.ops_), oinf64.sequence_)) self.assertIn("TreeEnsembleRegressor", text) self.assertIn("TreeEnsembleRegressorDouble", text) self.assertNotIn('floats', smodel_def64) y64 = oinf64.run({'X': X_test.astype(numpy.float64)}) self.assertEqual(list(sorted(y64)), ['variable']) self.assertEqual(lexp.shape, y64['variable'].shape) self.assertEqualArray(lexp, y64['variable']) model_def32 = to_onnx(clr, X_train.astype(numpy.float32), rewrite_ops=True) oinf32 = OnnxInference(model_def32) text = "\n".join(map(lambda x: str(x.ops_), oinf32.sequence_)) self.assertIn("TreeEnsembleRegressor", text) self.assertNotIn("TreeEnsembleRegressorDouble", text) smodel_def32 = str(model_def32) self.assertNotIn('doubles', smodel_def32) self.assertNotIn('double_data', smodel_def32) self.assertIn('floats', smodel_def32) y32 = oinf32.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y32)), ['variable']) self.assertEqual(lexp.shape, y32['variable'].shape) self.assertEqualArray(lexp, y32['variable']) onx32 = model_def32.SerializeToString() onx64 = model_def64.SerializeToString() s32 = len(onx32) s64 = len(onx64) self.assertGreater(s64, s32 + 100) self.assertNotEqual(y32['variable'].dtype, y64['variable'].dtype) diff = numpy.max(numpy.abs(y32['variable'].astype(numpy.float64) - y64['variable'].astype(numpy.float64))) self.assertLesser(diff, 1e-5) def test_onnxrt_python_GradientBoostingRegressor64(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split( X, y, random_state=11) # pylint: disable=W0612 clr = GradientBoostingRegressor(n_estimators=20, random_state=11) clr.fit(X_train, y_train) lexp = clr.predict(X_test) model_def64 = to_onnx(clr, X_train.astype(numpy.float64), rewrite_ops=True) oinf64 = OnnxInference(model_def64) text = "\n".join(map(lambda x: str(x.ops_), oinf64.sequence_)) self.assertIn("TreeEnsembleRegressor", text) #self.assertIn("TreeEnsembleRegressorDouble", text) smodel_def64 = str(model_def64) self.assertIn('double_data', smodel_def64) self.assertNotIn('floats', smodel_def64) y64 = oinf64.run({'X': X_test.astype(numpy.float64)}) self.assertEqual(list(sorted(y64)), ['variable']) self.assertEqual(lexp.shape, y64['variable'].shape) self.assertEqualArray(lexp, y64['variable']) model_def32 = to_onnx(clr, X_train.astype(numpy.float32), rewrite_ops=True) oinf32 = OnnxInference(model_def32) text = "\n".join(map(lambda x: str(x.ops_), oinf32.sequence_)) self.assertIn("TreeEnsembleRegressor", text) self.assertNotIn("TreeEnsembleRegressorDouble", text) smodel_def32 = str(model_def32) self.assertNotIn('doubles', smodel_def32) self.assertNotIn('double_data', smodel_def32) self.assertIn('floats', smodel_def32) with self.subTest(rows=1): for irow in range(0, X_test.shape[0]): oinf32.sequence_[0].ops_.rt_.omp_tree_ = 10000 y32 = oinf32.run( {'X': X_test[irow:irow + 1].astype(numpy.float32)}) y32 = oinf32.run( {'X': X_test[irow:irow + 1].astype(numpy.float32)}) self.assertEqual(list(sorted(y32)), ['variable']) self.assertEqual(lexp[irow:irow + 1].shape, y32['variable'].shape) self.assertEqualArray(lexp[irow:irow + 1], y32['variable']) oinf32.sequence_[0].ops_.rt_.omp_tree_ = 10 y32 = oinf32.run( {'X': X_test[irow:irow + 1].astype(numpy.float32)}) y32 = oinf32.run( {'X': X_test[irow:irow + 1].astype(numpy.float32)}) self.assertEqual(list(sorted(y32)), ['variable']) self.assertEqual(lexp[irow:irow + 1].shape, y32['variable'].shape) self.assertEqualArray(lexp[irow:irow + 1], y32['variable']) with self.subTest(rows=X_test.shape[0]): oinf32.sequence_[0].ops_.rt_.omp_tree_ = 10000 y32 = oinf32.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y32)), ['variable']) self.assertEqual(lexp.shape, y32['variable'].shape) self.assertEqualArray(lexp, y32['variable']) oinf32.sequence_[0].ops_.rt_.omp_tree_ = 10 y32 = oinf32.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y32)), ['variable']) self.assertEqual(lexp.shape, y32['variable'].shape) self.assertEqualArray(lexp, y32['variable']) onx32 = model_def32.SerializeToString() onx64 = model_def64.SerializeToString() s32 = len(onx32) s64 = len(onx64) self.assertGreater(s64, s32 + 100) self.assertNotEqual(y32['variable'].dtype, y64['variable'].dtype) diff = numpy.max(numpy.abs(y32['variable'].astype(numpy.float64) - y64['variable'].astype(numpy.float64))) self.assertLesser(diff, 1e-5) def test_onnxrt_python_DecisionTree_depth2(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = DecisionTreeClassifier(max_depth=2) clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test.astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=5) def test_onnxrt_python_RandomForestClassifer5(self): iris = load_iris() X, y = iris.data, iris.target X_train, X_test, y_train, _ = train_test_split(X, y, random_state=11) clr = RandomForestClassifier( n_estimators=4, max_depth=2, random_state=11) clr.fit(X_train, y_train) model_def = to_onnx(clr, X_train.astype(numpy.float32)) oinf = OnnxInference(model_def) text = "\n".join(map(lambda x: str(x.ops_), oinf.sequence_)) self.assertIn("TreeEnsembleClassifier", text) y = oinf.run({'X': X_test[:5].astype(numpy.float32)}) self.assertEqual(list(sorted(y)), [ 'output_label', 'output_probability']) lexp = clr.predict(X_test[:5]) self.assertEqualArray(lexp, y['output_label']) exp = clr.predict_proba(X_test[:5]) got = pandas.DataFrame(list(y['output_probability'])).values self.assertEqualArray(exp, got, decimal=5) def test_openmp_compilation(self): from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_ import RuntimeTreeEnsembleRegressorFloat # pylint: disable=E0611 ru = RuntimeTreeEnsembleRegressorFloat() r = ru.runtime_options() self.assertEqual('OPENMP', r) nb = ru.omp_get_max_threads() self.assertGreater(nb, 0) from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_ import RuntimeTreeEnsembleClassifierFloat # pylint: disable=E0611 ru = RuntimeTreeEnsembleClassifierFloat() r = ru.runtime_options() self.assertEqual('OPENMP', r) nb2 = ru.omp_get_max_threads() self.assertEqual(nb2, nb) def test_openmp_compilation_p(self): from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import RuntimeTreeEnsembleRegressorPFloat # pylint: disable=E0611 ru = RuntimeTreeEnsembleRegressorPFloat(1, 1) r = ru.runtime_options() self.assertEqual('OPENMP', r) nb = ru.omp_get_max_threads() self.assertGreater(nb, 0) from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_p_ import RuntimeTreeEnsembleClassifierPFloat # pylint: disable=E0611 ru = RuntimeTreeEnsembleClassifierPFloat(1, 1) r = ru.runtime_options() self.assertEqual('OPENMP', r) nb2 = ru.omp_get_max_threads() self.assertEqual(nb2, nb) def test_cpp_average(self): from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_average # pylint: disable=E0611 confs = [[100, 100, True], [100, 100, False], [10, 10, True], [10, 10, False], [2, 2, True], [2, 2, False]] for conf in confs: with self.subTest(conf=tuple(conf)): for b in [False, True]: test_tree_regressor_multitarget_average( *(conf + [b, False])) for b in [False, True]: test_tree_regressor_multitarget_average( *(conf + [b, True])) def test_cpp_min(self): from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_min # pylint: disable=E0611 confs = [[100, 100, True], [100, 100, False], [10, 10, True], [10, 10, False], [2, 2, True], [2, 2, False]] for conf in reversed(confs): with self.subTest(conf=tuple(conf)): for b in [False, True]: test_tree_regressor_multitarget_min(*(conf + [b, False])) for b in [False, True]: test_tree_regressor_multitarget_min(*(conf + [b, True])) def test_cpp_max(self): from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_max # pylint: disable=E0611 confs = [[100, 100, True], [100, 100, False], [10, 10, True], [10, 10, False], [2, 2, True], [2, 2, False]] for conf in confs: with self.subTest(conf=tuple(conf)): for b in [False, True]: test_tree_regressor_multitarget_max(*(conf + [b, False])) for b in [False, True]: test_tree_regressor_multitarget_max(*(conf + [b, True])) if __name__ == "__main__": TestOnnxrtPythonRuntimeMlTree().test_onnxrt_python_GradientBoostingRegressor64() unittest.main()
[ "logging.getLogger", "sklearn.tree.DecisionTreeRegressor", "unittest.main", "sklearn.tree.DecisionTreeClassifier", "numpy.vstack", "pandas.DataFrame", "sklearn.ensemble.GradientBoostingRegressor", "mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_min", "sklearn....
[((19563, 19578), 'unittest.main', 'unittest.main', ([], {}), '()\n', (19576, 19578), False, 'import unittest\n'), ((600, 621), 'logging.getLogger', 'getLogger', (['"""skl2onnx"""'], {}), "('skl2onnx')\n", (609, 621), False, 'from logging import getLogger\n'), ((726, 737), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (735, 737), False, 'from sklearn.datasets import load_iris\n'), ((814, 853), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (830, 853), False, 'from sklearn.model_selection import train_test_split\n'), ((868, 892), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (890, 892), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((1007, 1031), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (1020, 1031), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((1653, 1664), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (1662, 1664), False, 'from sklearn.datasets import load_iris\n'), ((1757, 1796), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (1773, 1796), False, 'from sklearn.model_selection import train_test_split\n'), ((1811, 1835), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (1833, 1835), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((1950, 1974), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (1963, 1974), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((2593, 2604), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (2602, 2604), False, 'from sklearn.datasets import load_iris\n'), ((2703, 2742), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (2719, 2742), False, 'from sklearn.model_selection import train_test_split\n'), ((2757, 2785), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {}), '()\n', (2783, 2785), False, 'from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, GradientBoostingRegressor\n'), ((2900, 2924), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (2913, 2924), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((3543, 3554), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (3552, 3554), False, 'from sklearn.datasets import load_iris\n'), ((3631, 3670), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (3647, 3670), False, 'from sklearn.model_selection import train_test_split\n'), ((3685, 3713), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {}), '()\n', (3711, 3713), False, 'from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, GradientBoostingRegressor\n'), ((3828, 3852), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (3841, 3852), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((4473, 4484), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (4482, 4484), False, 'from sklearn.datasets import load_iris\n'), ((4536, 4576), 'numpy.zeros', 'numpy.zeros', (['(y_.shape[0], 3)'], {'dtype': 'int'}), '((y_.shape[0], 3), dtype=int)\n', (4547, 4576), False, 'import numpy\n'), ((4693, 4732), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (4709, 4732), False, 'from sklearn.model_selection import train_test_split\n'), ((4747, 4771), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (4769, 4771), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((4886, 4910), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (4899, 4910), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((5349, 5394), 'pandas.DataFrame', 'pandas.DataFrame', (['p.values'], {'columns': 'p.columns'}), '(p.values, columns=p.columns)\n', (5365, 5394), False, 'import pandas\n'), ((5608, 5619), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (5617, 5619), False, 'from sklearn.datasets import load_iris\n'), ((5696, 5735), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (5712, 5735), False, 'from sklearn.model_selection import train_test_split\n'), ((5750, 5773), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {}), '()\n', (5771, 5773), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((5888, 5912), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (5901, 5912), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((7027, 7038), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (7036, 7038), False, 'from sklearn.datasets import load_iris\n'), ((7150, 7189), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (7166, 7189), False, 'from sklearn.model_selection import train_test_split\n'), ((7204, 7227), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {}), '()\n', (7225, 7227), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((7342, 7366), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (7355, 7366), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((7821, 7832), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (7830, 7832), False, 'from sklearn.datasets import load_iris\n'), ((7909, 7948), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (7925, 7948), False, 'from sklearn.model_selection import train_test_split\n'), ((8001, 8042), 'sklearn.tree.DecisionTreeRegressor', 'DecisionTreeRegressor', ([], {'min_samples_leaf': '(7)'}), '(min_samples_leaf=7)\n', (8022, 8042), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((8402, 8428), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def64'], {}), '(model_def64)\n', (8415, 8428), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((9026, 9052), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def32'], {}), '(model_def32)\n', (9039, 9052), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((10192, 10203), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (10201, 10203), False, 'from sklearn.datasets import load_iris\n'), ((10280, 10319), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (10296, 10319), False, 'from sklearn.model_selection import train_test_split\n'), ((10372, 10431), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {'n_estimators': '(20)', 'random_state': '(11)'}), '(n_estimators=20, random_state=11)\n', (10397, 10431), False, 'from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, GradientBoostingRegressor\n'), ((10633, 10659), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def64'], {}), '(model_def64)\n', (10646, 10659), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((11349, 11375), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def32'], {}), '(model_def32)\n', (11362, 11375), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((14089, 14100), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (14098, 14100), False, 'from sklearn.datasets import load_iris\n'), ((14177, 14216), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (14193, 14216), False, 'from sklearn.model_selection import train_test_split\n'), ((14231, 14266), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'max_depth': '(2)'}), '(max_depth=2)\n', (14253, 14266), False, 'from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n'), ((14381, 14405), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (14394, 14405), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((15019, 15030), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (15028, 15030), False, 'from sklearn.datasets import load_iris\n'), ((15107, 15146), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'random_state': '(11)'}), '(X, y, random_state=11)\n', (15123, 15146), False, 'from sklearn.model_selection import train_test_split\n'), ((15161, 15229), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(4)', 'max_depth': '(2)', 'random_state': '(11)'}), '(n_estimators=4, max_depth=2, random_state=11)\n', (15183, 15229), False, 'from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, GradientBoostingRegressor\n'), ((15357, 15381), 'mlprodict.onnxrt.OnnxInference', 'OnnxInference', (['model_def'], {}), '(model_def)\n', (15370, 15381), False, 'from mlprodict.onnxrt import OnnxInference\n'), ((16119, 16154), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_.RuntimeTreeEnsembleRegressorFloat', 'RuntimeTreeEnsembleRegressorFloat', ([], {}), '()\n', (16152, 16154), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_ import RuntimeTreeEnsembleRegressorFloat\n'), ((16446, 16482), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_.RuntimeTreeEnsembleClassifierFloat', 'RuntimeTreeEnsembleClassifierFloat', ([], {}), '()\n', (16480, 16482), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_ import RuntimeTreeEnsembleClassifierFloat\n'), ((16817, 16857), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.RuntimeTreeEnsembleRegressorPFloat', 'RuntimeTreeEnsembleRegressorPFloat', (['(1)', '(1)'], {}), '(1, 1)\n', (16851, 16857), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import RuntimeTreeEnsembleRegressorPFloat\n'), ((17152, 17193), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_p_.RuntimeTreeEnsembleClassifierPFloat', 'RuntimeTreeEnsembleClassifierPFloat', (['(1)', '(1)'], {}), '(1, 1)\n', (17187, 17193), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_classifier_p_ import RuntimeTreeEnsembleClassifierPFloat\n'), ((7089, 7109), 'numpy.vstack', 'numpy.vstack', (['[y, y]'], {}), '([y, y])\n', (7101, 7109), False, 'import numpy\n'), ((17848, 17909), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_average', 'test_tree_regressor_multitarget_average', (['*(conf + [b, False])'], {}), '(*(conf + [b, False]))\n', (17887, 17909), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_average\n'), ((17995, 18055), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_average', 'test_tree_regressor_multitarget_average', (['*(conf + [b, True])'], {}), '(*(conf + [b, True]))\n', (18034, 18055), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_average\n'), ((18593, 18650), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_min', 'test_tree_regressor_multitarget_min', (['*(conf + [b, False])'], {}), '(*(conf + [b, False]))\n', (18628, 18650), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_min\n'), ((18711, 18767), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_min', 'test_tree_regressor_multitarget_min', (['*(conf + [b, True])'], {}), '(*(conf + [b, True]))\n', (18746, 18767), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_min\n'), ((19270, 19327), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_max', 'test_tree_regressor_multitarget_max', (['*(conf + [b, False])'], {}), '(*(conf + [b, False]))\n', (19305, 19327), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_max\n'), ((19388, 19444), 'mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_.test_tree_regressor_multitarget_max', 'test_tree_regressor_multitarget_max', (['*(conf + [b, True])'], {}), '(*(conf + [b, True]))\n', (19423, 19444), False, 'from mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_p_ import test_tree_regressor_multitarget_max\n')]
# 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. # Lint as: python3 """Compute the df/f given a f and a percentile tensor. Computes (f - percentile) / (smooth + percentile). """ import logging import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions import gin class ComputeDFByF(beam.core.DoFn): """Computes the df by f.""" def __init__(self, input_spec, percentile_spec, output_spec, percentile_index, smoothing): self._input_spec = input_spec self._percentile_spec = percentile_spec self._output_spec = output_spec self._percentile_index = percentile_index self._smoothing = smoothing def setup(self): """Sets up the beam bundle.""" # pylint: disable=g-import-not-at-top, import-outside-toplevel import tensorstore as ts self._ds_in = ts.open(self._input_spec).result() self._shape = self._ds_in.domain.shape self._ds_percentile = ts.open(self._percentile_spec).result() self._ds_out = ts.open(self._output_spec).result() self._dtype = self._ds_out.dtype.numpy_dtype def process(self, yz): """Computes the df/f at a given y and z.""" # pylint: disable=g-import-not-at-top, import-outside-toplevel import numpy as np y, z = yz # Process entire xt tiles at once. f = self._ds_in[:, y, z, :].read().result() b = self._ds_percentile[:, y, z, :, self._percentile_index].read().result() fnp = np.array(f) fnp = fnp.astype(self._dtype) bnp = np.array(b) bnp = bnp.astype(self._dtype) output = (fnp - bnp) / (self._smoothing + bnp) self._ds_out[:, y, z, :] = output yield None @gin.configurable("compute_dfbyf") def compute_dfbyf(pipeline_options=gin.REQUIRED, input_spec=gin.REQUIRED, percentile_spec=gin.REQUIRED, output_spec=gin.REQUIRED, percentile_index=gin.REQUIRED, smoothing=gin.REQUIRED): """Computes the df/f of a base and percentile T major XYZT tensors. Args: pipeline_options: dictionary of pipeline options input_spec: Tensorstore input spec. percentile_spec: Tensorstore percentile spec. output_spec: Tensorstore output spec. percentile_index: the index of the 5th dimention to use for divisor. smoothing: amount to add to divisor. """ # pylint: disable=g-import-not-at-top, import-outside-toplevel import tensorstore as ts pipeline_opt = PipelineOptions.from_dictionary(pipeline_options) logging.info(pipeline_opt.get_all_options()) ds = ts.open(input_spec).result() shape = ds.domain.shape yz = [] for y in range(shape[1]): for z in range(shape[2]): yz.append((y, z)) with beam.Pipeline(options=pipeline_opt) as p: ys = p | beam.Create(yz) result = ys | beam.ParDo(ComputeDFByF(input_spec, percentile_spec, output_spec, percentile_index, smoothing)) del result
[ "tensorstore.open", "apache_beam.options.pipeline_options.PipelineOptions.from_dictionary", "numpy.array", "gin.configurable", "apache_beam.Create", "apache_beam.Pipeline" ]
[((1969, 2002), 'gin.configurable', 'gin.configurable', (['"""compute_dfbyf"""'], {}), "('compute_dfbyf')\n", (1985, 2002), False, 'import gin\n'), ((2772, 2821), 'apache_beam.options.pipeline_options.PipelineOptions.from_dictionary', 'PipelineOptions.from_dictionary', (['pipeline_options'], {}), '(pipeline_options)\n', (2803, 2821), False, 'from apache_beam.options.pipeline_options import PipelineOptions\n'), ((1759, 1770), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (1767, 1770), True, 'import numpy as np\n'), ((1815, 1826), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (1823, 1826), True, 'import numpy as np\n'), ((3031, 3066), 'apache_beam.Pipeline', 'beam.Pipeline', ([], {'options': 'pipeline_opt'}), '(options=pipeline_opt)\n', (3044, 3066), True, 'import apache_beam as beam\n'), ((2876, 2895), 'tensorstore.open', 'ts.open', (['input_spec'], {}), '(input_spec)\n', (2883, 2895), True, 'import tensorstore as ts\n'), ((3086, 3101), 'apache_beam.Create', 'beam.Create', (['yz'], {}), '(yz)\n', (3097, 3101), True, 'import apache_beam as beam\n'), ((1156, 1181), 'tensorstore.open', 'ts.open', (['self._input_spec'], {}), '(self._input_spec)\n', (1163, 1181), True, 'import tensorstore as ts\n'), ((1260, 1290), 'tensorstore.open', 'ts.open', (['self._percentile_spec'], {}), '(self._percentile_spec)\n', (1267, 1290), True, 'import tensorstore as ts\n'), ((1319, 1345), 'tensorstore.open', 'ts.open', (['self._output_spec'], {}), '(self._output_spec)\n', (1326, 1345), True, 'import tensorstore as ts\n')]
import sqlite3 from argparse import ArgumentParser import numpy as np from openDAM.dataio.create_dam_db_from_csv import insert_in_table, create_tables PUN_ZONES = {"SICI": 17, "SVIZ": 6} MIN_RATIO = 0.1 PERIODS = range(9, 21) N_BLOCKS_PER_ZONE = 25 QUANTITY_RANGE = [1, 75] MEAN_PRICE = 50 STDEV_PRICE = 10 def populate_block_orders(connection, day_id): block_id = 0 for zone, zone_id in PUN_ZONES.iteritems(): print("Creating blocks for zone " + zone) data = [] profile_data = [] for block in range(1, N_BLOCKS_PER_ZONE + 1): block_id += 1 price = np.random.normal(MEAN_PRICE, STDEV_PRICE) data.append([day_id, block_id, zone_id, price, MIN_RATIO]) for period in range(1, 25): quantity = 0.0 if period in PERIODS: quantity = np.random.uniform(QUANTITY_RANGE[0], QUANTITY_RANGE[1]) profile_data.append([day_id, block_id, period, quantity]) insert_in_table(connection, "BLOCKS", data) insert_in_table(connection, "BLOCK_DATA", profile_data) conn.commit() print(block_id) if __name__ == "__main__": parser = ArgumentParser( description='Utility for Adding randomly generated blocks to a database. Block properties are defined at the top.') parser.add_argument("-p", "--path", help="Folder where data is located", required=True) parser.add_argument("-d", "--database", help="Name of the sqlite database file, under the folder of the --path argument.", required=True) parser.add_argument("--from_date", help="Date of first day to import, as YYYYMMDD, cast as an int.", required=True) parser.add_argument("--to_date", help="Date of last day to import, as YYYYMMDD, cast as an int.", required=True) parser.add_argument("--create_tables", help="True if block related tables must be created", default=False) parser.add_argument("--seed", help="Seed for random number generation", default=1984) args = parser.parse_args() conn = sqlite3.connect('%s/%s' % (args.path, args.database)) if args.create_tables: create_tables(conn, ["BLOCKS", "BLOCK_DATA"]) cursor = conn.cursor() cmd = "delete from BLOCKS" cursor.execute(cmd) cmd = "delete from BLOCK_DATA" cursor.execute(cmd) for date in range(int(args.from_date), int(args.to_date) + 1): np.random.seed(int(args.seed)) populate_block_orders(conn, date) conn.close()
[ "numpy.random.normal", "sqlite3.connect", "argparse.ArgumentParser", "numpy.random.uniform", "openDAM.dataio.create_dam_db_from_csv.insert_in_table", "openDAM.dataio.create_dam_db_from_csv.create_tables" ]
[((1211, 1351), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Utility for Adding randomly generated blocks to a database. Block properties are defined at the top."""'}), "(description=\n 'Utility for Adding randomly generated blocks to a database. Block properties are defined at the top.'\n )\n", (1225, 1351), False, 'from argparse import ArgumentParser\n'), ((2139, 2192), 'sqlite3.connect', 'sqlite3.connect', (["('%s/%s' % (args.path, args.database))"], {}), "('%s/%s' % (args.path, args.database))\n", (2154, 2192), False, 'import sqlite3\n'), ((1015, 1058), 'openDAM.dataio.create_dam_db_from_csv.insert_in_table', 'insert_in_table', (['connection', '"""BLOCKS"""', 'data'], {}), "(connection, 'BLOCKS', data)\n", (1030, 1058), False, 'from openDAM.dataio.create_dam_db_from_csv import insert_in_table, create_tables\n'), ((1067, 1122), 'openDAM.dataio.create_dam_db_from_csv.insert_in_table', 'insert_in_table', (['connection', '"""BLOCK_DATA"""', 'profile_data'], {}), "(connection, 'BLOCK_DATA', profile_data)\n", (1082, 1122), False, 'from openDAM.dataio.create_dam_db_from_csv import insert_in_table, create_tables\n'), ((2229, 2274), 'openDAM.dataio.create_dam_db_from_csv.create_tables', 'create_tables', (['conn', "['BLOCKS', 'BLOCK_DATA']"], {}), "(conn, ['BLOCKS', 'BLOCK_DATA'])\n", (2242, 2274), False, 'from openDAM.dataio.create_dam_db_from_csv import insert_in_table, create_tables\n'), ((622, 663), 'numpy.random.normal', 'np.random.normal', (['MEAN_PRICE', 'STDEV_PRICE'], {}), '(MEAN_PRICE, STDEV_PRICE)\n', (638, 663), True, 'import numpy as np\n'), ((876, 931), 'numpy.random.uniform', 'np.random.uniform', (['QUANTITY_RANGE[0]', 'QUANTITY_RANGE[1]'], {}), '(QUANTITY_RANGE[0], QUANTITY_RANGE[1])\n', (893, 931), True, 'import numpy as np\n')]
import numpy import matplotlib.pyplot as plt from sklearn.metrics import r2_score import pandas as pd #import numpy as np #import pandas as pd #from scipy import stats #import matplotlib.pyplot as plt def strtolist(s): l=s.split(",") outputlist=[] for item in l: outputlist=outputlist + [float(item)] return outputlist """ x = [4,5,6,7] y = [410,420,435,440] data={"poly":[x,y]} index=["x","y"] df=pd.DataFrame(data,index) print(df) df.to_excel("F:\\Excel2\\new.xlsx") 1,2,3,4,5, 1,4,2,4,4,5,2,5 1,2,2,4,4,4,5,5 4 duplicates 3,6,7,8 1,2,4,5 """ def readexcel(excel): df=pd.read_excel(excel) #print(df) polynomial=df["poly"] x=polynomial[0] y=polynomial[1] return x,y x,y=readexcel("F:\\Excel2\\poly.xlsx") print(type(x),y) x=strtolist(x) y=strtolist(y) print(numpy.linspace(1,101,11)) model = numpy.poly1d(numpy.polyfit(x, y, 2)) print(model) print(numpy.polyfit(x, y, 1)) correlation=r2_score(y, model(x)) print("Correlation",correlation) plt.scatter(x,y,color="Black") plt.plot(x,y,"b-",label="Original") plotx=[1,2,3,4,5] plt.plot(plotx, model(plotx),"r-",label="Predicted") plt.ylabel('Y') plt.xlabel('X') plt.legend() plt.show() xvalue=4 predict=model(xvalue) print(predict)
[ "matplotlib.pyplot.ylabel", "numpy.polyfit", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.linspace", "matplotlib.pyplot.scatter", "pandas.read_excel", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((1008, 1040), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""Black"""'}), "(x, y, color='Black')\n", (1019, 1040), True, 'import matplotlib.pyplot as plt\n'), ((1039, 1077), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""b-"""'], {'label': '"""Original"""'}), "(x, y, 'b-', label='Original')\n", (1047, 1077), True, 'import matplotlib.pyplot as plt\n'), ((1146, 1161), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (1156, 1161), True, 'import matplotlib.pyplot as plt\n'), ((1162, 1177), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (1172, 1177), True, 'import matplotlib.pyplot as plt\n'), ((1179, 1191), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1189, 1191), True, 'import matplotlib.pyplot as plt\n'), ((1192, 1202), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1200, 1202), True, 'import matplotlib.pyplot as plt\n'), ((618, 638), 'pandas.read_excel', 'pd.read_excel', (['excel'], {}), '(excel)\n', (631, 638), True, 'import pandas as pd\n'), ((827, 853), 'numpy.linspace', 'numpy.linspace', (['(1)', '(101)', '(11)'], {}), '(1, 101, 11)\n', (841, 853), False, 'import numpy\n'), ((874, 896), 'numpy.polyfit', 'numpy.polyfit', (['x', 'y', '(2)'], {}), '(x, y, 2)\n', (887, 896), False, 'import numpy\n'), ((917, 939), 'numpy.polyfit', 'numpy.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (930, 939), False, 'import numpy\n')]
from keras import backend as K import os # Parameters candle_lib = '/data/BIDS-HPC/public/candle/Candle/common' def initialize_parameters(): print('Initializing parameters...') # Obtain the path of the directory of this script file_path = os.path.dirname(os.path.realpath(__file__)) # Import the CANDLE library import sys sys.path.append(candle_lib) import candle_keras as candle # Instantiate the candle.Benchmark class mymodel_common = candle.Benchmark(file_path,os.getenv("DEFAULT_PARAMS_FILE"),'keras',prog='myprog',desc='My model') # Get a dictionary of the model hyperparamters gParameters = candle.initialize_parameters(mymodel_common) # Return the dictionary of the hyperparameters return(gParameters) def run(gParameters): print('Running model...') #### Begin model input ########################################################################################## def get_model(model_json_fname,modelwtsfname): # This is only for prediction if os.path.isfile(model_json_fname): # Model reconstruction from JSON file with open(model_json_fname, 'r') as f: model = model_from_json(f.read()) else: model = get_unet() #model.summary() # Load weights into the new model model.load_weights(modelwtsfname) return model def focal_loss(gamma=2., alpha=.25): def focal_loss_fixed(y_true, y_pred): pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred)) pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred)) return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1))-K.sum((1-alpha) * K.pow( pt_0, gamma) * K.log(1. - pt_0)) return focal_loss_fixed def jaccard_coef(y_true, y_pred): smooth = 1.0 intersection = K.sum(y_true * y_pred, axis=[-0, -1, 2]) sum_ = K.sum(y_true + y_pred, axis=[-0, -1, 2]) jac = (intersection + smooth) / (sum_ - intersection + smooth) return K.mean(jac) def jaccard_coef_int(y_true, y_pred): smooth = 1.0 y_pred_pos = K.round(K.clip(y_pred, 0, 1)) intersection = K.sum(y_true * y_pred_pos, axis=[-0, -1, 2]) sum_ = K.sum(y_true + y_pred_pos, axis=[-0, -1, 2]) jac = (intersection + smooth) / (sum_ - intersection + smooth) return K.mean(jac) def jaccard_coef_loss(y_true, y_pred): return -K.log(jaccard_coef(y_true, y_pred)) + binary_crossentropy(y_pred, y_true) def dice_coef_batch(y_true, y_pred): smooth = 1.0 intersection = K.sum(y_true * y_pred, axis=[-0, -1, 2]) sum_ = K.sum(y_true + y_pred, axis=[-0, -1, 2]) dice = ((2.0*intersection) + smooth) / (sum_ + intersection + smooth) return K.mean(dice) def dice_coef(y_true, y_pred): smooth = 1.0 y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) dice_smooth = ((2. * intersection) + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) return (dice_smooth) def dice_coef_loss(y_true, y_pred): return -dice_coef(y_true, y_pred) def dice_coef_batch_loss(y_true, y_pred): return -dice_coef_batch(y_true, y_pred) #Define the neural network def get_unet(): droprate = 0.25 filt_size = 32 inputs = Input((None, None, 1)) conv1 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(inputs) conv1 = Dropout(droprate)(conv1) conv1 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) filt_size = filt_size*2 conv2 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(pool1) conv2 = Dropout(droprate)(conv2) conv2 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) filt_size = filt_size*2 conv3 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(pool2) conv3 = Dropout(droprate)(conv3) conv3 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) filt_size = filt_size*2 conv4 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(pool3) conv4 = Dropout(droprate)(conv4) conv4 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(conv4) filt_size = filt_size*2 conv5 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(pool4) conv5 = Dropout(droprate)(conv5) conv5 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv5) filt_size = filt_size/2 up6 = concatenate([Conv2DTranspose(filt_size, (2, 2), strides=(2, 2), padding='same')(conv5), conv4], axis=3) conv6 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(up6) conv6 = Dropout(droprate)(conv6) conv6 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv6) filt_size = filt_size/2 up7 = concatenate([Conv2DTranspose(filt_size, (2, 2), strides=(2, 2), padding='same')(conv6), conv3], axis=3) conv7 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(up7) conv7 = Dropout(droprate)(conv7) conv7 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv7) filt_size = filt_size/2 up8 = concatenate([Conv2DTranspose(filt_size, (2, 2), strides=(2, 2), padding='same')(conv7), conv2], axis=3) conv8 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(up8) conv8 = Dropout(droprate)(conv8) conv8 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv8) filt_size = filt_size/2 up9 = concatenate([Conv2DTranspose(filt_size, (2, 2), strides=(2, 2), padding='same')(conv8), conv1], axis=3) conv9 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(up9) conv9 = Dropout(droprate)(conv9) conv9 = Conv2D(filt_size, (3, 3), activation='relu', padding='same')(conv9) conv10 = Conv2D(1, (1, 1), activation='sigmoid')(conv9) model = Model(inputs=[inputs], outputs=[conv10]) #model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef]) #model.compile(optimizer=Nadam(lr=1e-3), loss=dice_coef_loss, metrics=[dice_coef]) #model.compile(optimizer=Adadelta(), loss=dice_coef_loss, metrics=[dice_coef]) return model def save_model_to_json(model,model_json_fname): #model = unet.UResNet152(input_shape=(None, None, 3), classes=1,encoder_weights="imagenet11k") #model = get_unet() #model.summary() # serialize model to JSON model_json = model.to_json() with open(model_json_fname, "w") as json_file: json_file.write(model_json) def preprocess_data(do_prediction,inputnpyfname,targetnpyfname,expandChannel,backbone): # Preprocess the data (beyond what I already did before) print('-'*30) print('Loading and preprocessing data...') print('-'*30) # Load, normalize, and cast the data imgs_input = ( np.load(inputnpyfname).astype('float32') / (2**16-1) * (2**8-1) ).astype('uint8') print('Input images information:') print(imgs_input.shape) print(imgs_input.dtype) hist,bins = np.histogram(imgs_input) print(hist) print(bins) if not do_prediction: imgs_mask_train = np.load(targetnpyfname).astype('uint8') print('Input masks information:') print(imgs_mask_train.shape) print(imgs_mask_train.dtype) hist,bins = np.histogram(imgs_mask_train) print(hist) print(bins) # Make the grayscale images RGB since that's what the model expects apparently if expandChannel: imgs_input = np.stack((imgs_input,)*3, -1) else: imgs_input = np.expand_dims(imgs_input, 3) print('New shape of input images:') print(imgs_input.shape) if not do_prediction: imgs_mask_train = np.expand_dims(imgs_mask_train, 3) print('New shape of masks:') print(imgs_mask_train.shape) # Preprocess as per https://github.com/qubvel/segmentation_models preprocessing_fn = get_preprocessing(backbone) imgs_input = preprocessing_fn(imgs_input) # Return appropriate variables if not do_prediction: return(imgs_input,imgs_mask_train) else: return(imgs_input) # Import relevant modules and functions import sys sys.path.append(gParameters['segmentation_models_repo']) import numpy as np from keras.models import Model from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint,ReduceLROnPlateau,EarlyStopping,CSVLogger from keras.layers.normalization import BatchNormalization from keras.backend import binary_crossentropy import keras import random import tensorflow as tf from keras.models import model_from_json from segmentation_models import Unet from segmentation_models.backbones import get_preprocessing K.set_image_data_format('channels_last') # TF dimension ordering in this code # Basically constants expandChannel = True modelwtsfname = 'model_weights.h5' model_json_fname = 'model.json' csvfname = 'model.csv' do_prediction = gParameters['predict'] if not do_prediction: # Train... print('Training...') # Parameters inputnpyfname = gParameters['images'] labels = gParameters['labels'] initialize = gParameters['initialize'] backbone = gParameters['backbone'] encoder = gParameters['encoder'] lr = float(gParameters['lr']) batch_size = gParameters['batch_size'] obj_return = gParameters['obj_return'] epochs = gParameters['epochs'] # Preprocess the data imgs_train,imgs_mask_train = preprocess_data(do_prediction,inputnpyfname,labels,expandChannel,backbone) # Load, save, and compile the model model = Unet(backbone_name=backbone, encoder_weights=encoder) save_model_to_json(model,model_json_fname) model.compile(optimizer=Adam(lr=lr), loss='binary_crossentropy', metrics=['binary_crossentropy','mean_squared_error',dice_coef, dice_coef_batch, focal_loss()]) # Load previous weights for restarting, if desired and possible if os.path.isfile(initialize): print('-'*30) print('Loading previous weights ...') model.load_weights(initialize) # Set up the training callback functions model_checkpoint = ModelCheckpoint(modelwtsfname, monitor=obj_return, save_best_only=True) reduce_lr = ReduceLROnPlateau(monitor=obj_return, factor=0.1,patience=100, min_lr=0.001,verbose=1) model_es = EarlyStopping(monitor=obj_return, min_delta=0.00000001, patience=100, verbose=1, mode='auto') csv_logger = CSVLogger(csvfname, append=True) # Train the model history_callback = model.fit(imgs_train, imgs_mask_train, batch_size=batch_size, epochs=epochs, verbose=2, shuffle=True, validation_split=0.10, callbacks=[model_checkpoint, reduce_lr, model_es, csv_logger]) print("Minimum validation loss:") print(min(history_callback.history[obj_return])) else: # ...or predict print('Inferring...') # Parameters inputnpyfname = gParameters['images'] initialize = gParameters['initialize'] backbone = gParameters['backbone'] # lr = float(gParameters['lr']) # this isn't needed but we're keeping it for the U-Net, where it is "needed" # Preprocess the data imgs_infer = preprocess_data(do_prediction,inputnpyfname,'',expandChannel,backbone) # Load the model #model = get_model(model_json_fname,initialize) model = get_model(os.path.dirname(initialize)+'/'+model_json_fname,initialize) # Run inference imgs_test_predict = model.predict(imgs_infer, batch_size=1, verbose=1) # Save the predicted masks np.save('mask_predictions.npy', np.squeeze(np.round(imgs_test_predict).astype('uint8'))) history_callback = None #### End model input ############################################################################################ return(history_callback) def main(): print('Running main program...') gParameters = initialize_parameters() run(gParameters) if __name__ == '__main__': main() try: K.clear_session() except AttributeError: pass
[ "keras.layers.Conv2D", "tensorflow.equal", "candle_keras.initialize_parameters", "keras.backend.sum", "keras.backend.flatten", "segmentation_models.backbones.get_preprocessing", "tensorflow.ones_like", "sys.path.append", "numpy.histogram", "keras.backend.clip", "keras.backend.pow", "numpy.stac...
[((354, 381), 'sys.path.append', 'sys.path.append', (['candle_lib'], {}), '(candle_lib)\n', (369, 381), False, 'import sys\n'), ((652, 696), 'candle_keras.initialize_parameters', 'candle.initialize_parameters', (['mymodel_common'], {}), '(mymodel_common)\n', (680, 696), True, 'import candle_keras as candle\n'), ((9176, 9232), 'sys.path.append', 'sys.path.append', (["gParameters['segmentation_models_repo']"], {}), "(gParameters['segmentation_models_repo'])\n", (9191, 9232), False, 'import sys\n'), ((9844, 9884), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_last"""'], {}), "('channels_last')\n", (9867, 9884), True, 'from keras import backend as K\n'), ((274, 300), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (290, 300), False, 'import os\n'), ((510, 542), 'os.getenv', 'os.getenv', (['"""DEFAULT_PARAMS_FILE"""'], {}), "('DEFAULT_PARAMS_FILE')\n", (519, 542), False, 'import os\n'), ((1054, 1086), 'os.path.isfile', 'os.path.isfile', (['model_json_fname'], {}), '(model_json_fname)\n', (1068, 1086), False, 'import os\n'), ((1938, 1978), 'keras.backend.sum', 'K.sum', (['(y_true * y_pred)'], {'axis': '[-0, -1, 2]'}), '(y_true * y_pred, axis=[-0, -1, 2])\n', (1943, 1978), True, 'from keras import backend as K\n'), ((1994, 2034), 'keras.backend.sum', 'K.sum', (['(y_true + y_pred)'], {'axis': '[-0, -1, 2]'}), '(y_true + y_pred, axis=[-0, -1, 2])\n', (1999, 2034), True, 'from keras import backend as K\n'), ((2131, 2142), 'keras.backend.mean', 'K.mean', (['jac'], {}), '(jac)\n', (2137, 2142), True, 'from keras import backend as K\n'), ((2290, 2334), 'keras.backend.sum', 'K.sum', (['(y_true * y_pred_pos)'], {'axis': '[-0, -1, 2]'}), '(y_true * y_pred_pos, axis=[-0, -1, 2])\n', (2295, 2334), True, 'from keras import backend as K\n'), ((2350, 2394), 'keras.backend.sum', 'K.sum', (['(y_true + y_pred_pos)'], {'axis': '[-0, -1, 2]'}), '(y_true + y_pred_pos, axis=[-0, -1, 2])\n', (2355, 2394), True, 'from keras import backend as K\n'), ((2491, 2502), 'keras.backend.mean', 'K.mean', (['jac'], {}), '(jac)\n', (2497, 2502), True, 'from keras import backend as K\n'), ((2731, 2771), 'keras.backend.sum', 'K.sum', (['(y_true * y_pred)'], {'axis': '[-0, -1, 2]'}), '(y_true * y_pred, axis=[-0, -1, 2])\n', (2736, 2771), True, 'from keras import backend as K\n'), ((2787, 2827), 'keras.backend.sum', 'K.sum', (['(y_true + y_pred)'], {'axis': '[-0, -1, 2]'}), '(y_true + y_pred, axis=[-0, -1, 2])\n', (2792, 2827), True, 'from keras import backend as K\n'), ((2931, 2943), 'keras.backend.mean', 'K.mean', (['dice'], {}), '(dice)\n', (2937, 2943), True, 'from keras import backend as K\n'), ((3024, 3041), 'keras.backend.flatten', 'K.flatten', (['y_true'], {}), '(y_true)\n', (3033, 3041), True, 'from keras import backend as K\n'), ((3061, 3078), 'keras.backend.flatten', 'K.flatten', (['y_pred'], {}), '(y_pred)\n', (3070, 3078), True, 'from keras import backend as K\n'), ((3102, 3128), 'keras.backend.sum', 'K.sum', (['(y_true_f * y_pred_f)'], {}), '(y_true_f * y_pred_f)\n', (3107, 3128), True, 'from keras import backend as K\n'), ((3564, 3586), 'keras.layers.Input', 'Input', (['(None, None, 1)'], {}), '((None, None, 1))\n', (3569, 3586), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6579, 6619), 'keras.models.Model', 'Model', ([], {'inputs': '[inputs]', 'outputs': '[conv10]'}), '(inputs=[inputs], outputs=[conv10])\n', (6584, 6619), False, 'from keras.models import Model\n'), ((7870, 7894), 'numpy.histogram', 'np.histogram', (['imgs_input'], {}), '(imgs_input)\n', (7882, 7894), True, 'import numpy as np\n'), ((8868, 8895), 'segmentation_models.backbones.get_preprocessing', 'get_preprocessing', (['backbone'], {}), '(backbone)\n', (8885, 8895), False, 'from segmentation_models.backbones import get_preprocessing\n'), ((10808, 10861), 'segmentation_models.Unet', 'Unet', ([], {'backbone_name': 'backbone', 'encoder_weights': 'encoder'}), '(backbone_name=backbone, encoder_weights=encoder)\n', (10812, 10861), False, 'from segmentation_models import Unet\n'), ((11164, 11190), 'os.path.isfile', 'os.path.isfile', (['initialize'], {}), '(initialize)\n', (11178, 11190), False, 'import os\n'), ((11387, 11458), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['modelwtsfname'], {'monitor': 'obj_return', 'save_best_only': '(True)'}), '(modelwtsfname, monitor=obj_return, save_best_only=True)\n', (11402, 11458), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((11479, 11572), 'keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': 'obj_return', 'factor': '(0.1)', 'patience': '(100)', 'min_lr': '(0.001)', 'verbose': '(1)'}), '(monitor=obj_return, factor=0.1, patience=100, min_lr=\n 0.001, verbose=1)\n', (11496, 11572), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((11585, 11677), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': 'obj_return', 'min_delta': '(1e-08)', 'patience': '(100)', 'verbose': '(1)', 'mode': '"""auto"""'}), "(monitor=obj_return, min_delta=1e-08, patience=100, verbose=1,\n mode='auto')\n", (11598, 11677), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((11700, 11732), 'keras.callbacks.CSVLogger', 'CSVLogger', (['csvfname'], {'append': '(True)'}), '(csvfname, append=True)\n', (11709, 11732), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, CSVLogger\n'), ((13297, 13314), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (13312, 13314), True, 'from keras import backend as K\n'), ((2240, 2260), 'keras.backend.clip', 'K.clip', (['y_pred', '(0)', '(1)'], {}), '(y_pred, 0, 1)\n', (2246, 2260), True, 'from keras import backend as K\n'), ((2605, 2640), 'keras.backend.binary_crossentropy', 'binary_crossentropy', (['y_pred', 'y_true'], {}), '(y_pred, y_true)\n', (2624, 2640), False, 'from keras.backend import binary_crossentropy\n'), ((3603, 3663), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (3609, 3663), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((3688, 3705), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (3695, 3705), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((3730, 3790), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (3736, 3790), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((3814, 3844), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (3826, 3844), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((3905, 3965), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (3911, 3965), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((3989, 4006), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (3996, 4006), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4031, 4091), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4037, 4091), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4115, 4145), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4127, 4145), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4206, 4266), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4212, 4266), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4290, 4307), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (4297, 4307), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4332, 4392), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4338, 4392), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4416, 4446), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4428, 4446), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4507, 4567), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4513, 4567), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4591, 4608), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (4598, 4608), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4633, 4693), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4639, 4693), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4717, 4747), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (4729, 4747), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4812, 4872), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4818, 4872), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4896, 4913), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (4903, 4913), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((4937, 4997), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (4943, 4997), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5181, 5241), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (5187, 5241), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5263, 5280), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (5270, 5280), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5304, 5364), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (5310, 5364), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5548, 5608), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (5554, 5608), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5630, 5647), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (5637, 5647), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5671, 5731), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (5677, 5731), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5919, 5979), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (5925, 5979), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6001, 6018), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (6008, 6018), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6042, 6102), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (6048, 6102), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6285, 6345), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (6291, 6345), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6367, 6384), 'keras.layers.Dropout', 'Dropout', (['droprate'], {}), '(droprate)\n', (6374, 6384), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6408, 6468), 'keras.layers.Conv2D', 'Conv2D', (['filt_size', '(3, 3)'], {'activation': '"""relu"""', 'padding': '"""same"""'}), "(filt_size, (3, 3), activation='relu', padding='same')\n", (6414, 6468), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6507, 6546), 'keras.layers.Conv2D', 'Conv2D', (['(1)', '(1, 1)'], {'activation': '"""sigmoid"""'}), "(1, (1, 1), activation='sigmoid')\n", (6513, 6546), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((8187, 8216), 'numpy.histogram', 'np.histogram', (['imgs_mask_train'], {}), '(imgs_mask_train)\n', (8199, 8216), True, 'import numpy as np\n'), ((8414, 8445), 'numpy.stack', 'np.stack', (['((imgs_input,) * 3)', '(-1)'], {}), '((imgs_input,) * 3, -1)\n', (8422, 8445), True, 'import numpy as np\n'), ((8482, 8511), 'numpy.expand_dims', 'np.expand_dims', (['imgs_input', '(3)'], {}), '(imgs_input, 3)\n', (8496, 8511), True, 'import numpy as np\n'), ((8647, 8681), 'numpy.expand_dims', 'np.expand_dims', (['imgs_mask_train', '(3)'], {}), '(imgs_mask_train, 3)\n', (8661, 8681), True, 'import numpy as np\n'), ((1557, 1576), 'tensorflow.equal', 'tf.equal', (['y_true', '(1)'], {}), '(y_true, 1)\n', (1565, 1576), True, 'import tensorflow as tf\n'), ((1586, 1606), 'tensorflow.ones_like', 'tf.ones_like', (['y_pred'], {}), '(y_pred)\n', (1598, 1606), True, 'import tensorflow as tf\n'), ((1636, 1655), 'tensorflow.equal', 'tf.equal', (['y_true', '(0)'], {}), '(y_true, 0)\n', (1644, 1655), True, 'import tensorflow as tf\n'), ((1665, 1686), 'tensorflow.zeros_like', 'tf.zeros_like', (['y_pred'], {}), '(y_pred)\n', (1678, 1686), True, 'import tensorflow as tf\n'), ((10945, 10956), 'keras.optimizers.Adam', 'Adam', ([], {'lr': 'lr'}), '(lr=lr)\n', (10949, 10956), False, 'from keras.optimizers import Adam\n'), ((3185, 3200), 'keras.backend.sum', 'K.sum', (['y_true_f'], {}), '(y_true_f)\n', (3190, 3200), True, 'from keras import backend as K\n'), ((3203, 3218), 'keras.backend.sum', 'K.sum', (['y_pred_f'], {}), '(y_pred_f)\n', (3208, 3218), True, 'from keras import backend as K\n'), ((5074, 5140), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['filt_size', '(2, 2)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(filt_size, (2, 2), strides=(2, 2), padding='same')\n", (5089, 5140), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5441, 5507), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['filt_size', '(2, 2)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(filt_size, (2, 2), strides=(2, 2), padding='same')\n", (5456, 5507), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((5812, 5878), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['filt_size', '(2, 2)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(filt_size, (2, 2), strides=(2, 2), padding='same')\n", (5827, 5878), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((6178, 6244), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['filt_size', '(2, 2)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(filt_size, (2, 2), strides=(2, 2), padding='same')\n", (6193, 6244), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\n'), ((7995, 8018), 'numpy.load', 'np.load', (['targetnpyfname'], {}), '(targetnpyfname)\n', (8002, 8018), True, 'import numpy as np\n'), ((12634, 12661), 'os.path.dirname', 'os.path.dirname', (['initialize'], {}), '(initialize)\n', (12649, 12661), False, 'import os\n'), ((1801, 1818), 'keras.backend.log', 'K.log', (['(1.0 - pt_0)'], {}), '(1.0 - pt_0)\n', (1806, 1818), True, 'from keras import backend as K\n'), ((12893, 12920), 'numpy.round', 'np.round', (['imgs_test_predict'], {}), '(imgs_test_predict)\n', (12901, 12920), True, 'import numpy as np\n'), ((1748, 1759), 'keras.backend.log', 'K.log', (['pt_1'], {}), '(pt_1)\n', (1753, 1759), True, 'from keras import backend as K\n'), ((1779, 1797), 'keras.backend.pow', 'K.pow', (['pt_0', 'gamma'], {}), '(pt_0, gamma)\n', (1784, 1797), True, 'from keras import backend as K\n'), ((1722, 1746), 'keras.backend.pow', 'K.pow', (['(1.0 - pt_1)', 'gamma'], {}), '(1.0 - pt_1, gamma)\n', (1727, 1746), True, 'from keras import backend as K\n'), ((7661, 7683), 'numpy.load', 'np.load', (['inputnpyfname'], {}), '(inputnpyfname)\n', (7668, 7683), True, 'import numpy as np\n')]
import os import re import nibabel as nib import numpy as np from glob import glob from sys import argv dirname=argv[1] print(dirname) ### COLLECT ALL MNCs all_fls = [] for dirs, things, fls in os.walk(dirname): if len(fls) > 0: for fl in fls: all_fls.append(os.path.join(dirs,fl)) all_mncs = [x for x in all_fls if '.mnc' in x] print('%s .mnc and .mnc.gz files found'%(len(all_mncs))) ### SEARCH TO SEE IF NIFTI VERSIONS ALREADY EXIST already_done = [] for mnc in all_mncs: print(mnc) flnm = re.sub('.mnc.gz', '', re.sub('.mnc', '', mnc)) print(flnm) ni = glob('%s.ni*'%flnm) if len(ni) > 0: already_done.append(mnc) print('%s mncs already have a nifti version. Skipping these files...'%(len(already_done))) [all_mncs.remove(x) for x in already_done] print('the following files will be converted:') [print(x) for x in all_mncs] ### TRANSFORM FILES for mnc in all_mncs: flnm = re.sub('.mnc', '', re.sub('.mnc.gz', '', mnc)) if mnc[-1] == 'z': new_nm = '%s.nii.gz'%flnm else: new_nm = '%s.nii.gz'%flnm print(new_nm) img = nib.load(mnc) data = img.get_data() affine =img.affine if len(data.shape) == 4 : out = np.zeros( [ data.shape[1], data.shape[2], data.shape[3], data.shape[0] ] ) for t in range(data.shape[0]) : out[:,:,:,t] = data[t,:,:,:] else : out = data nifti = nib.Nifti1Image(out, affine) nifti.to_filename(new_nm) print('converted %s to %s'%(mnc,new_nm)) #if ans: # os.remove(mnc)
[ "nibabel.load", "os.walk", "os.path.join", "numpy.zeros", "nibabel.Nifti1Image", "re.sub", "glob.glob" ]
[((196, 212), 'os.walk', 'os.walk', (['dirname'], {}), '(dirname)\n', (203, 212), False, 'import os\n'), ((602, 623), 'glob.glob', 'glob', (["('%s.ni*' % flnm)"], {}), "('%s.ni*' % flnm)\n", (606, 623), False, 'from glob import glob\n'), ((1114, 1127), 'nibabel.load', 'nib.load', (['mnc'], {}), '(mnc)\n', (1122, 1127), True, 'import nibabel as nib\n'), ((1413, 1441), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['out', 'affine'], {}), '(out, affine)\n', (1428, 1441), True, 'import nibabel as nib\n'), ((552, 575), 're.sub', 're.sub', (['""".mnc"""', '""""""', 'mnc'], {}), "('.mnc', '', mnc)\n", (558, 575), False, 'import re\n'), ((957, 983), 're.sub', 're.sub', (['""".mnc.gz"""', '""""""', 'mnc'], {}), "('.mnc.gz', '', mnc)\n", (963, 983), False, 'import re\n'), ((1221, 1291), 'numpy.zeros', 'np.zeros', (['[data.shape[1], data.shape[2], data.shape[3], data.shape[0]]'], {}), '([data.shape[1], data.shape[2], data.shape[3], data.shape[0]])\n', (1229, 1291), True, 'import numpy as np\n'), ((285, 307), 'os.path.join', 'os.path.join', (['dirs', 'fl'], {}), '(dirs, fl)\n', (297, 307), False, 'import os\n')]
import cv2 import numpy as np image = cv2.imread('calvinHobbes.jpeg') height, width = image.shape[:2] quarter_height, quarter_width = height/4, width/4 T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]]) img_translation = cv2.warpAffine(image, T, (width, height)) cv2.imshow("Originalimage", image) cv2.imshow('Translation', img_translation) cv2.imwrite('Translation.jpg', img_translation) cv2.waitKey() cv2.destroyAllWindows() # cv2.imshow("Nearest Neighbour", scaled) # cv2.waitKey(0) # cv2.destroyAllWindows() # cv2.imshow("Bilinear", scaled) # cv2.waitKey(0) # cv2.destroyAllWindows() # cv2.imshow("Bicubic", scaled) # cv2.waitKey(0) # cv2.destroyAllWindows()
[ "cv2.imwrite", "cv2.warpAffine", "cv2.imshow", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.imread", "numpy.float32" ]
[((41, 72), 'cv2.imread', 'cv2.imread', (['"""calvinHobbes.jpeg"""'], {}), "('calvinHobbes.jpeg')\n", (51, 72), False, 'import cv2\n'), ((164, 223), 'numpy.float32', 'np.float32', (['[[1, 0, quarter_width], [0, 1, quarter_height]]'], {}), '([[1, 0, quarter_width], [0, 1, quarter_height]])\n', (174, 223), True, 'import numpy as np\n'), ((243, 284), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'T', '(width, height)'], {}), '(image, T, (width, height))\n', (257, 284), False, 'import cv2\n'), ((287, 321), 'cv2.imshow', 'cv2.imshow', (['"""Originalimage"""', 'image'], {}), "('Originalimage', image)\n", (297, 321), False, 'import cv2\n'), ((323, 365), 'cv2.imshow', 'cv2.imshow', (['"""Translation"""', 'img_translation'], {}), "('Translation', img_translation)\n", (333, 365), False, 'import cv2\n'), ((366, 413), 'cv2.imwrite', 'cv2.imwrite', (['"""Translation.jpg"""', 'img_translation'], {}), "('Translation.jpg', img_translation)\n", (377, 413), False, 'import cv2\n'), ((415, 428), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (426, 428), False, 'import cv2\n'), ((431, 454), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (452, 454), False, 'import cv2\n')]
from fastai.basic_train import load_learner import pandas as pd from pydub import AudioSegment from librosa import get_duration from pathlib import Path from numpy import floor from audio.data import AudioConfig, SpectrogramConfig, AudioList import os import shutil import tempfile def load_model(mPath, mName="stg2-rn18.pkl"): return load_learner(mPath, mName) def get_wave_file(wav_file): ''' Function to load a wav file ''' return AudioSegment.from_wav(wav_file) def export_wave_file(audio, begin, end, dest): ''' Function to extract a smaller wav file based start and end duration information ''' sub_audio = audio[begin * 1000:end * 1000] sub_audio.export(dest, format="wav") def extract_segments(audioPath, sampleDict, destnPath, suffix): ''' Function to exctact segments given a audio path folder and proposal segments ''' # Listing the local audio files local_audio_files = str(audioPath) + '/' for wav_file in sampleDict.keys(): audio_file = get_wave_file(local_audio_files + wav_file) for begin_time, end_time in sampleDict[wav_file]: output_file_name = wav_file.lower().replace( '.wav', '') + '_' + str(begin_time) + '_' + str( end_time) + suffix + '.wav' output_file_path = destnPath + output_file_name export_wave_file(audio_file, begin_time, end_time, output_file_path) class FastAIModel(): def __init__(self, model_path, model_name="stg2-rn18.pkl", threshold=0.5, min_num_positive_calls_threshold=3): self.model = load_model(model_path, model_name) self.threshold = threshold self.min_num_positive_calls_threshold = min_num_positive_calls_threshold def predict(self, wav_file_path): ''' Function which generates local predictions using wavefile ''' # Creates local directory to save 2 second clops # local_dir = "./fastai_dir/" local_dir = tempfile.mkdtemp()+"/" if os.path.exists(local_dir): shutil.rmtree(local_dir, ignore_errors=False, onerror=None) os.makedirs(local_dir) else: os.makedirs(local_dir) # infer clip length max_length = get_duration(filename=wav_file_path) print(os.path.basename(wav_file_path)) print("Length of Audio Clip:{0}".format(max_length)) #max_length = 60 # Generating 2 sec proposal with 1 sec hop length twoSecList = [] for i in range(int(floor(max_length)-1)): twoSecList.append([i, i+2]) # Creating a proposal dictionary two_sec_dict = {} two_sec_dict[Path(wav_file_path).name] = twoSecList # Creating 2 sec segments from the defined wavefile using proposals built above. # "use_a_real_wavname.wav" will generate -> "use_a_real_wavname_1_3.wav", "use_a_real_wavname_2_4.wav" etc. files in fastai_dir folder extract_segments( str(Path(wav_file_path).parent), two_sec_dict, local_dir, "" ) # Definining Audio config needed to create on the fly mel spectograms config = AudioConfig(standardize=False, sg_cfg=SpectrogramConfig( f_min=0.0, # Minimum frequency to Display f_max=10000, # Maximum Frequency to Display hop_length=256, n_fft=2560, # Number of Samples for Fourier n_mels=256, # Mel bins pad=0, to_db_scale=True, # Converting to DB sclae top_db=100, # Top decible sound win_length=None, n_mfcc=20) ) config.duration = 4000 # 4 sec padding or snip config.resample_to = 20000 # Every sample at 20000 frequency config.downmix=True # Creating a Audio DataLoader test_data_folder = Path(local_dir) tfms = None test = AudioList.from_folder( test_data_folder, config=config).split_none().label_empty() testdb = test.transform(tfms).databunch(bs=32) # Scoring each 2 sec clip predictions = [] pathList = list(pd.Series(test_data_folder.ls()).astype('str')) for item in testdb.x: predictions.append(self.model.predict(item)[2][1]) # clean folder shutil.rmtree(local_dir) # Aggregating predictions # Creating a DataFrame prediction = pd.DataFrame({'FilePath': pathList, 'confidence': predictions}) # Converting prediction to float prediction['confidence'] = prediction.confidence.astype(float) # Extracting Starting time from file name prediction['start_time_s'] = prediction.FilePath.apply(lambda x: int(x.split('_')[-2])) # Sorting the file based on start_time_s prediction = prediction.sort_values( ['start_time_s']).reset_index(drop=True) # Rolling Window (to average at per second level) submission = pd.DataFrame( { 'wav_filename': Path(wav_file_path).name, 'duration_s': 1.0, 'confidence': list(prediction.rolling(2)['confidence'].mean().values) } ).reset_index().rename(columns={'index': 'start_time_s'}) # Updating first row submission.loc[0, 'confidence'] = prediction.confidence[0] # Adding lastrow lastLine = pd.DataFrame({ 'wav_filename': Path(wav_file_path).name, 'start_time_s': [submission.start_time_s.max()+1], 'duration_s': 1.0, 'confidence': [prediction.confidence[prediction.shape[0]-1]] }) submission = submission.append(lastLine, ignore_index=True) submission = submission[['wav_filename', 'start_time_s', 'duration_s', 'confidence']] # initialize output JSON result_json = {} result_json = dict( submission=submission, local_predictions=list((submission['confidence'] > self.threshold).astype(int)), local_confidences=list(submission['confidence']) ) result_json['global_prediction'] = int(sum(result_json["local_predictions"]) > self.min_num_positive_calls_threshold) result_json['global_confidence'] = submission.loc[(submission['confidence'] > self.threshold), 'confidence'].mean()*100 if pd.isnull(result_json["global_confidence"]): result_json["global_confidence"] = 0 return result_json
[ "os.path.exists", "pandas.isnull", "os.makedirs", "pathlib.Path", "audio.data.SpectrogramConfig", "numpy.floor", "audio.data.AudioList.from_folder", "fastai.basic_train.load_learner", "librosa.get_duration", "tempfile.mkdtemp", "os.path.basename", "shutil.rmtree", "pandas.DataFrame", "pydu...
[((341, 367), 'fastai.basic_train.load_learner', 'load_learner', (['mPath', 'mName'], {}), '(mPath, mName)\n', (353, 367), False, 'from fastai.basic_train import load_learner\n'), ((458, 489), 'pydub.AudioSegment.from_wav', 'AudioSegment.from_wav', (['wav_file'], {}), '(wav_file)\n', (479, 489), False, 'from pydub import AudioSegment\n'), ((2062, 2087), 'os.path.exists', 'os.path.exists', (['local_dir'], {}), '(local_dir)\n', (2076, 2087), False, 'import os\n'), ((2295, 2331), 'librosa.get_duration', 'get_duration', ([], {'filename': 'wav_file_path'}), '(filename=wav_file_path)\n', (2307, 2331), False, 'from librosa import get_duration\n'), ((4199, 4214), 'pathlib.Path', 'Path', (['local_dir'], {}), '(local_dir)\n', (4203, 4214), False, 'from pathlib import Path\n'), ((4657, 4681), 'shutil.rmtree', 'shutil.rmtree', (['local_dir'], {}), '(local_dir)\n', (4670, 4681), False, 'import shutil\n'), ((4770, 4833), 'pandas.DataFrame', 'pd.DataFrame', (["{'FilePath': pathList, 'confidence': predictions}"], {}), "({'FilePath': pathList, 'confidence': predictions})\n", (4782, 4833), True, 'import pandas as pd\n'), ((6740, 6783), 'pandas.isnull', 'pd.isnull', (["result_json['global_confidence']"], {}), "(result_json['global_confidence'])\n", (6749, 6783), True, 'import pandas as pd\n'), ((2028, 2046), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (2044, 2046), False, 'import tempfile\n'), ((2101, 2160), 'shutil.rmtree', 'shutil.rmtree', (['local_dir'], {'ignore_errors': '(False)', 'onerror': 'None'}), '(local_dir, ignore_errors=False, onerror=None)\n', (2114, 2160), False, 'import shutil\n'), ((2173, 2195), 'os.makedirs', 'os.makedirs', (['local_dir'], {}), '(local_dir)\n', (2184, 2195), False, 'import os\n'), ((2222, 2244), 'os.makedirs', 'os.makedirs', (['local_dir'], {}), '(local_dir)\n', (2233, 2244), False, 'import os\n'), ((2346, 2377), 'os.path.basename', 'os.path.basename', (['wav_file_path'], {}), '(wav_file_path)\n', (2362, 2377), False, 'import os\n'), ((2726, 2745), 'pathlib.Path', 'Path', (['wav_file_path'], {}), '(wav_file_path)\n', (2730, 2745), False, 'from pathlib import Path\n'), ((3314, 3469), 'audio.data.SpectrogramConfig', 'SpectrogramConfig', ([], {'f_min': '(0.0)', 'f_max': '(10000)', 'hop_length': '(256)', 'n_fft': '(2560)', 'n_mels': '(256)', 'pad': '(0)', 'to_db_scale': '(True)', 'top_db': '(100)', 'win_length': 'None', 'n_mfcc': '(20)'}), '(f_min=0.0, f_max=10000, hop_length=256, n_fft=2560,\n n_mels=256, pad=0, to_db_scale=True, top_db=100, win_length=None, n_mfcc=20\n )\n', (3331, 3469), False, 'from audio.data import AudioConfig, SpectrogramConfig, AudioList\n'), ((2574, 2591), 'numpy.floor', 'floor', (['max_length'], {}), '(max_length)\n', (2579, 2591), False, 'from numpy import floor\n'), ((3040, 3059), 'pathlib.Path', 'Path', (['wav_file_path'], {}), '(wav_file_path)\n', (3044, 3059), False, 'from pathlib import Path\n'), ((5818, 5837), 'pathlib.Path', 'Path', (['wav_file_path'], {}), '(wav_file_path)\n', (5822, 5837), False, 'from pathlib import Path\n'), ((4250, 4304), 'audio.data.AudioList.from_folder', 'AudioList.from_folder', (['test_data_folder'], {'config': 'config'}), '(test_data_folder, config=config)\n', (4271, 4304), False, 'from audio.data import AudioConfig, SpectrogramConfig, AudioList\n'), ((5390, 5409), 'pathlib.Path', 'Path', (['wav_file_path'], {}), '(wav_file_path)\n', (5394, 5409), False, 'from pathlib import Path\n')]
import numpy as np import pandas as pd benign = np.load('NPY/benign_data_no_preprocessing_128.npy', encoding = 'latin1') # MODEL 1 malware = np.load('NPY/malware_data_no_preprocessing_128.npy', encoding = 'latin1') from sklearn.model_selection import train_test_split A_benign,B_benign = train_test_split(benign,test_size=0.2,random_state=5) A_malware,B_malware = train_test_split(malware,test_size=0.2,random_state=5) training_data = [] cnt_ben=0 cnt_mal=0 for i in A_benign: cnt_ben+=1 training_data.append(i) for i in A_malware: cnt_mal+=1 training_data.append(i) print(cnt_ben) print(cnt_mal) print(len(training_data)) cnt_ben=0 cnt_mal=0 test_data = [] for i in B_benign: cnt_ben+=1 test_data.append(i) for i in B_malware: cnt_mal+=1 test_data.append(i) print(cnt_ben) print(cnt_mal) print(len(test_data)) import numpy as np from keras.layers import * from keras.models import Model from keras.models import Input from keras import optimizers from keras.callbacks import ReduceLROnPlateau from keras.callbacks import ModelCheckpoint from keras.layers.normalization import BatchNormalization from keras.layers import Dropout import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator from sklearn.metrics import cohen_kappa_score from keras import regularizers import pandas as pd import matplotlib.pyplot as plt X_train = np.array([i[0] for i in training_data]) y_train = np.array([i[1] for i in training_data]) print(X_train[0].shape) X_test = np.array([i[0] for i in test_data]) y_test = np.array([i[1] for i in test_data]) print(y_test) import numpy as np from keras.layers import * from keras.models import Model from keras.models import Input from keras import optimizers from keras.callbacks import ReduceLROnPlateau from keras.callbacks import ModelCheckpoint from keras.layers.normalization import BatchNormalization from keras.layers import Dropout import matplotlib.pyplot as plt from keras.layers import GlobalAveragePooling2D from keras.preprocessing.image import ImageDataGenerator from sklearn.metrics import cohen_kappa_score from keras.layers import Concatenate from keras.layers import add from keras import regularizers from sklearn.metrics import confusion_matrix import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import OneHotEncoder from keras.applications import xception from keras.applications import densenet import os # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense from os import listdir,makedirs from os.path import join,exists,expanduser X_model = xception.Xception(weights = 'imagenet', include_top = False, input_shape = (128,128,3)) #X_model = densenet.DenseNet169(weights = 'imagenet', include_top = False, input_shape = (320,320,3)) for layer in X_model.layers[:-15]: layer.trainable = False x = X_model.output x = Flatten()(x) x = Dense(output_dim = 100, activation = 'relu', init = 'glorot_uniform',kernel_regularizer=regularizers.l2(0.001))(x) x = Dropout(0.1)(x) x = Dense(output_dim = 50, activation = 'tanh', init = 'glorot_uniform' ,kernel_regularizer=regularizers.l2(0.01))(x) x = Dropout(0.12)(x) output = Dense(output_dim = 1, activation = 'sigmoid', init = 'lecun_uniform', kernel_regularizer=regularizers.l2(0.0001))(x) model = Model(inputs = X_model.input , outputs = output) model.load_weights('output2.hdf5') adam = optimizers.Adam(lr=1e-3,beta_1=0.9,beta_2=0.999) # sgd = optimizers.SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer = adam, loss = 'binary_crossentropy', metrics = ['accuracy']) # checkpoint = ModelCheckpoint('output2.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode='max') # reducelr = ReduceLROnPlateau(monitor='val_loss', factor=0.8,minimum =0, patience=3, verbose= 1, mode = 'auto') # history = model.fit(x=X_train,y=y_train, validation_data=(X_test, y_test),epochs=200,batch_size=32,callbacks = [reducelr,checkpoint], verbose=2) y_pred = model.predict(X_test) from sklearn.metrics import accuracy_score score = accuracy_score(y_test,y_pred) print(score)
[ "keras.optimizers.Adam", "keras.layers.Flatten", "sklearn.model_selection.train_test_split", "keras.applications.xception.Xception", "numpy.array", "keras.models.Model", "keras.regularizers.l2", "numpy.load", "keras.layers.Dropout", "sklearn.metrics.accuracy_score" ]
[((49, 119), 'numpy.load', 'np.load', (['"""NPY/benign_data_no_preprocessing_128.npy"""'], {'encoding': '"""latin1"""'}), "('NPY/benign_data_no_preprocessing_128.npy', encoding='latin1')\n", (56, 119), True, 'import numpy as np\n'), ((143, 214), 'numpy.load', 'np.load', (['"""NPY/malware_data_no_preprocessing_128.npy"""'], {'encoding': '"""latin1"""'}), "('NPY/malware_data_no_preprocessing_128.npy', encoding='latin1')\n", (150, 214), True, 'import numpy as np\n'), ((291, 346), 'sklearn.model_selection.train_test_split', 'train_test_split', (['benign'], {'test_size': '(0.2)', 'random_state': '(5)'}), '(benign, test_size=0.2, random_state=5)\n', (307, 346), False, 'from sklearn.model_selection import train_test_split\n'), ((367, 423), 'sklearn.model_selection.train_test_split', 'train_test_split', (['malware'], {'test_size': '(0.2)', 'random_state': '(5)'}), '(malware, test_size=0.2, random_state=5)\n', (383, 423), False, 'from sklearn.model_selection import train_test_split\n'), ((1401, 1440), 'numpy.array', 'np.array', (['[i[0] for i in training_data]'], {}), '([i[0] for i in training_data])\n', (1409, 1440), True, 'import numpy as np\n'), ((1451, 1490), 'numpy.array', 'np.array', (['[i[1] for i in training_data]'], {}), '([i[1] for i in training_data])\n', (1459, 1490), True, 'import numpy as np\n'), ((1524, 1559), 'numpy.array', 'np.array', (['[i[0] for i in test_data]'], {}), '([i[0] for i in test_data])\n', (1532, 1559), True, 'import numpy as np\n'), ((1569, 1604), 'numpy.array', 'np.array', (['[i[1] for i in test_data]'], {}), '([i[1] for i in test_data])\n', (1577, 1604), True, 'import numpy as np\n'), ((2762, 2850), 'keras.applications.xception.Xception', 'xception.Xception', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'input_shape': '(128, 128, 3)'}), "(weights='imagenet', include_top=False, input_shape=(128, \n 128, 3))\n", (2779, 2850), False, 'from keras.applications import xception\n'), ((3472, 3515), 'keras.models.Model', 'Model', ([], {'inputs': 'X_model.input', 'outputs': 'output'}), '(inputs=X_model.input, outputs=output)\n', (3477, 3515), False, 'from keras.models import Model\n'), ((3565, 3616), 'keras.optimizers.Adam', 'optimizers.Adam', ([], {'lr': '(0.001)', 'beta_1': '(0.9)', 'beta_2': '(0.999)'}), '(lr=0.001, beta_1=0.9, beta_2=0.999)\n', (3580, 3616), False, 'from keras import optimizers\n'), ((4228, 4258), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (4242, 4258), False, 'from sklearn.metrics import accuracy_score\n'), ((3042, 3051), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3049, 3051), False, 'from keras.layers import Flatten\n'), ((3180, 3192), 'keras.layers.Dropout', 'Dropout', (['(0.1)'], {}), '(0.1)\n', (3187, 3192), False, 'from keras.layers import Dropout\n'), ((3320, 3333), 'keras.layers.Dropout', 'Dropout', (['(0.12)'], {}), '(0.12)\n', (3327, 3333), False, 'from keras.layers import Dropout\n'), ((3149, 3171), 'keras.regularizers.l2', 'regularizers.l2', (['(0.001)'], {}), '(0.001)\n', (3164, 3171), False, 'from keras import regularizers\n'), ((3290, 3311), 'keras.regularizers.l2', 'regularizers.l2', (['(0.01)'], {}), '(0.01)\n', (3305, 3311), False, 'from keras import regularizers\n'), ((3435, 3458), 'keras.regularizers.l2', 'regularizers.l2', (['(0.0001)'], {}), '(0.0001)\n', (3450, 3458), False, 'from keras import regularizers\n')]
""" author: <NAME> date : 03.12.2020 ---------- TO DO : """ import torch import torch.nn as nn import torch.optim as optim import numpy as np #import pandas as pd import skimage import time import logging import os import json from datetime import timedelta from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score from sklearn.manifold import TSNE from src.utils.print_utils import print_progessbar class BinaryClassifier: """ Define a Binary Classifier model able to return the tSNE representation of feature map prior to the MLP. """ def __init__(self, net, n_epoch=150, batch_size=32, lr=1e-3, lr_scheduler=optim.lr_scheduler.ExponentialLR, lr_scheduler_kwargs=dict(gamma=0.95), loss_fn=nn.CrossEntropyLoss, loss_fn_kwargs=dict(reduction='mean'), weight_decay=1e-6, num_workers=0, device='cuda', print_progress=False): """ Build a BinaryClassifer model. ---------- INPUT |---- net (nn.Module) the network to train. It should be a Encoder architecture returning a 2 neurons outputs. | To get the tSNE representation, the network should have a boolean attribute 'return_bottleneck' | that can be set to True to recover the bottleneck feature map (after average pooling before the MLP). |---- n_epoch (int) the number of epoch for the training. |---- batch_size (int) the batch size to use for loading the data. |---- lr (float) the learning rate. |---- lr_scheduler (torch.optim.lr_scheduler) the learning rate evolution scheme to use. |---- lr_scheduler_kwargs (dict) the keyword arguments to be passed to the lr_scheduler. |---- loss_fn (nn.Module) the loss function to use. Should take prediction and mask as forward input. |---- loss_fn_kwargs (dict) the keyword arguments to pass to the loss function constructor. |---- weight_decay (float) the L2-regularization strenght. |---- num_workers (int) the number of workers to use for data loading. |---- device (str) the device to use. |---- print_progress (bool) whether to print progress bar for batch processing. OUTPUT |---- ContextRestoration () the model for the Context restoration task. """ self.net = net # training parameters self.n_epoch = n_epoch self.batch_size = batch_size self.lr = lr self.lr_scheduler = lr_scheduler self.lr_scheduler_kwargs = lr_scheduler_kwargs self.loss_fn = loss_fn self.loss_fn_kwargs = loss_fn_kwargs self.weight_decay = weight_decay self.num_workers = num_workers self.device = device self.print_progress = print_progress # Results self.outputs = { 'train':{ 'time': None, 'evolution': None }, 'eval':{ 'time': None, 'auc': None, 'acc': None, 'recall': None, 'precision': None, 'f1': None, 'pred': None, 'repr': None } } def train(self, dataset, valid_dataset=None, checkpoint_path=None): """ Train the passed network on the given dataset for the Context retoration task. ---------- INPUT |---- dataset (torch.utils.data.Dataset) the dataset to use for training. It should output the image, | the binary label, and the sample index. |---- valid_dataset (torch.utils.data.Dataset) the dataset to use for validation at each epoch. It should | output the image, the binary label, and the sample index. |---- checkpoint_path (str) the filename for a possible checkpoint to start the training from. If None, the | network's weights are not saved regularily during training. OUTPUT |---- None. """ logger = logging.getLogger() # make dataloader train_loader = torch.utils.data.DataLoader(dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, pin_memory=False, worker_init_fn=lambda _: np.random.seed()) # put net on device self.net = self.net.to(self.device) # define optimizer optimizer = optim.Adam(self.net.parameters(), lr=self.lr, weight_decay=self.weight_decay) # define lr scheduler scheduler = self.lr_scheduler(optimizer, **self.lr_scheduler_kwargs) # define the loss function loss_fn = self.loss_fn(**self.loss_fn_kwargs) # load checkpoint if any try: checkpoint = torch.load(checkpoint_path, map_location=self.device) n_epoch_finished = checkpoint['n_epoch_finished'] self.net.load_state_dict(checkpoint['net_state']) optimizer.load_state_dict(checkpoint['optimizer_state']) scheduler.load_state_dict(checkpoint['lr_state']) epoch_loss_list = checkpoint['loss_evolution'] logger.info(f'Checkpoint loaded with {n_epoch_finished} epoch finished.') except FileNotFoundError: logger.info('No Checkpoint found. Training from beginning.') n_epoch_finished = 0 epoch_loss_list = [] # Start Training logger.info('Start training the Binary Classification task.') start_time = time.time() n_batch = len(train_loader) for epoch in range(n_epoch_finished, self.n_epoch): self.net.train() epoch_loss = 0.0 epoch_start_time = time.time() for b, data in enumerate(train_loader): # get data : target is original image, input is the corrupted image input, label, _ = data # put data on device input = input.to(self.device).float().requires_grad_(True) label = label.to(self.device).long()#.requires_grad_(True) # zero the networks' gradients optimizer.zero_grad() # optimize the weights with backpropagation on the batch pred = self.net(input) pred = nn.functional.softmax(pred, dim=1) loss = loss_fn(pred, label) loss.backward() optimizer.step() epoch_loss += loss.item() # print progress if self.print_progress: print_progessbar(b, n_batch, Name='\t\tTrain Batch', Size=50, erase=True) auc = None if valid_dataset: auc, acc, recall, precision, f1 = self.evaluate(valid_dataset, save_tsne=False, return_scores=True) valid_summary = f'| AUC {auc:.3%} | Accuracy {acc:.3%} | Recall {recall:.3%} | Precision {precision:.3%} | F1 {f1:.3%} ' else: valid_summary = '' # Print epoch statistics logger.info(f'\t| Epoch : {epoch + 1:03}/{self.n_epoch:03} ' f'| Train time: {timedelta(seconds=int(time.time() - epoch_start_time))} ' f'| Train Loss: {epoch_loss / n_batch:.6f} ' f'{valid_summary}' f'| lr: {scheduler.get_last_lr()[0]:.7f} |') # Store epoch loss epoch_loss_list.append([epoch+1, epoch_loss/n_batch, auc]) # update lr scheduler.step() # Save Checkpoint every epochs if (epoch+1)%1 == 0 and checkpoint_path: checkpoint = {'n_epoch_finished': epoch+1, 'net_state': self.net.state_dict(), 'optimizer_state': optimizer.state_dict(), 'lr_state': scheduler.state_dict(), 'loss_evolution': epoch_loss_list} torch.save(checkpoint, checkpoint_path) logger.info('\tCheckpoint saved.') # End training self.outputs['train']['time'] = time.time() - start_time self.outputs['train']['evolution'] = {'col_name': ['Epoch', 'loss', 'Valid_AUC'], 'data': epoch_loss_list} logger.info(f"Finished training inpainter Binary Classifier in {timedelta(seconds=int(self.outputs['train']['time']))}") def evaluate(self, dataset, save_tsne=False, return_scores=False): """ Evaluate the passed network on the given dataset for the Context retoration task. ---------- INPUT |---- dataset (torch.utils.data.Dataset) the dataset to use for evaluation. It should output the original image, | and the sample index. |---- save_tsne (bool) whether to compute and store in self.outputs the tsne representation of the feature map | after the average pooling layer and before the MLP |---- return_scores (bool) whether to return the measured ROC AUC, accuracy, recall, precision and f1-score. OUTPUT |---- (auc) (float) the ROC AUC on the dataset. |---- (acc) (float) the accuracy on the dataset. |---- (recall) (float) the recall on the dataset. |---- (precision) (float) the precision on the dataset. |---- (f1) (float) the f1-score on the dataset. """ logger = logging.getLogger() # make loader loader = torch.utils.data.DataLoader(dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, worker_init_fn=lambda _: np.random.seed()) # put net on device self.net = self.net.to(self.device) # Evaluate start_time = time.time() idx_repr = [] # placeholder for bottleneck representation idx_label_pred = [] # placeholder for label & prediction n_batch = len(loader) self.net.eval() with torch.no_grad(): for b, data in enumerate(loader): # get data : load in standard way (no patch swaped image) input, label, idx = data input = input.to(self.device).float() label = label.to(self.device).float() idx = idx.to(self.device) if save_tsne: # get representation self.net.return_bottleneck = True pred, repr = self.net(input) pred = nn.functional.softmax(pred, dim=1) # down sample representation for reduced memory impact repr = nn.AdaptiveAvgPool2d((4,4))(repr) # add ravelled representations to placeholder idx_repr += list(zip(idx.cpu().data.tolist(), repr.view(repr.shape[0], -1).cpu().data.tolist())) idx_label_pred += list(zip(idx.cpu().data.tolist(), label.cpu().data.tolist(), pred.argmax(dim=1).cpu().data.tolist(), pred[:,1].cpu().data.tolist())) # pred score is softmax activation of class 1 else: pred = self.net(input) pred = nn.functional.softmax(pred, dim=1) idx_label_pred += list(zip(idx.cpu().data.tolist(), label.cpu().data.tolist(), pred.argmax(dim=1).cpu().data.tolist(), pred[:,1].cpu().data.tolist())) # print_progress if self.print_progress: print_progessbar(b, n_batch, Name='\t\tEvaluation Batch', Size=50, erase=True) # reset the network attriubtes if save_tsne: self.net.return_bottleneck = False # compute tSNE for representation if save_tsne: idx, repr = zip(*idx_repr) repr = np.array(repr) logger.info('Computing the t-SNE representation.') repr_2D = TSNE(n_components=2).fit_transform(repr) self.outputs['eval']['repr'] = list(zip(idx, repr_2D.tolist())) logger.info('Succesfully computed the t-SNE representation.') # Compute Accuracy _, label, pred, pred_score = zip(*idx_label_pred) label, pred, pred_score = np.array(label), np.array(pred), np.array(pred_score) auc = roc_auc_score(label, pred_score) acc = accuracy_score(label, pred) recall = recall_score(label, pred) precision = precision_score(label, pred) f1 = f1_score(label, pred) self.outputs['eval']['auc'] = auc self.outputs['eval']['acc'] = acc self.outputs['eval']['recall'] = recall self.outputs['eval']['precision'] = precision self.outputs['eval']['f1'] = f1 self.outputs['eval']['pred'] = idx_label_pred # finish evluation self.outputs['eval']['time'] = time.time() - start_time if return_scores: return auc, acc, recall, precision, f1 def get_state_dict(self): """ Return the model weights as State dictionnary. ---------- INPUT |---- None OUTPUT |---- stat_dict (dict) the model's weights. """ return self.net.state_dict() def save_model(self, export_fn): """ Save the model. ---------- INPUT |---- export_fn (str) the export path. OUTPUT |---- None """ torch.save(self.net, export_fn) def save_model_state_dict(self, export_fn): """ Save the model. ---------- INPUT |---- export_fn (str) the export path. OUTPUT |---- None """ torch.save(self.net.state_dict(), export_fn) def load_model(self, import_fn, map_location='cpu'): """ Load a model from the given path. ---------- INPUT |---- import_fn (str) path where to get the model. |---- map_location (str) device on which to load the model. OUTPUT |---- None """ loaded_state_dict = torch.load(import_fn, map_location=map_location) self.net.load_state_dict(loaded_state_dict) def save_outputs(self, export_fn): """ Save the training stats in JSON. ---------- INPUT |---- export_fn (str) path where to get the results. OUTPUT |---- None """ with open(export_fn, 'w') as fn: json.dump(self.outputs, fn) class MultiClassifier: """ Define a Multi-Label Classifier model able to return the tSNE representation of feature map prior to the MLP. """ def __init__(self, net, n_epoch=150, batch_size=32, lr=1e-3, lr_scheduler=optim.lr_scheduler.ExponentialLR, lr_scheduler_kwargs=dict(gamma=0.95), loss_fn=nn.BCEWithLogitsLoss, loss_fn_kwargs=dict(reduction='mean'), weight_decay=1e-6, score_average='macro', num_workers=0, device='cuda', print_progress=False): """ Build a MultiClassifer model. ---------- INPUT |---- net (nn.Module) the network to train. It should be a Encoder architecture returning a 2 neurons outputs. | To get the tSNE representation, the network should have a boolean attribute 'return_bottleneck' | that can be set to True to recover the bottleneck feature map (after average pooling before the MLP). |---- n_epoch (int) the number of epoch for the training. |---- batch_size (int) the batch size to use for loading the data. |---- lr (float) the learning rate. |---- lr_scheduler (torch.optim.lr_scheduler) the learning rate evolution scheme to use. |---- lr_scheduler_kwargs (dict) the keyword arguments to be passed to the lr_scheduler. |---- loss_fn (nn.Module) the loss function to use. Should take prediction and mask as forward input. |---- loss_fn_kwargs (dict) the keyword arguments to pass to the loss function constructor. |---- weight_decay (float) the L2-regularization strenght. |---- num_workers (int) the number of workers to use for data loading. |---- device (str) the device to use. |---- print_progress (bool) whether to print progress bar for batch processing. OUTPUT |---- MultiClassifer () the model for the Context restoration task. """ self.net = net # training parameters self.n_epoch = n_epoch self.batch_size = batch_size self.lr = lr self.lr_scheduler = lr_scheduler self.lr_scheduler_kwargs = lr_scheduler_kwargs self.loss_fn = loss_fn self.loss_fn_kwargs = loss_fn_kwargs self.weight_decay = weight_decay self.score_average = score_average self.num_workers = num_workers self.device = device self.print_progress = print_progress # Results self.outputs = { 'train':{ 'time': None, 'evolution': None }, 'eval':{ 'time': None, 'auc': None, 'acc': None, 'subset_acc': None, 'recall': None, 'precision': None, 'f1': None, 'pred': None, 'repr': None } } def train(self, dataset, valid_dataset=None, checkpoint_path=None): """ Train the passed network on the given dataset for the Multi classification task. ---------- INPUT |---- dataset (torch.utils.data.Dataset) the dataset to use for training. It should output the image, | the multi label, and the sample index. |---- valid_dataset (torch.utils.data.Dataset) the dataset to use for validation at each epoch. It should | output the image, the binary label, and the sample index. |---- checkpoint_path (str) the filename for a possible checkpoint to start the training from. If None, the | network's weights are not saved regularily during training. OUTPUT |---- None. """ logger = logging.getLogger() # make dataloader train_loader = torch.utils.data.DataLoader(dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers, pin_memory=False, worker_init_fn=lambda _: np.random.seed()) # put net on device self.net = self.net.to(self.device) # define optimizer optimizer = optim.Adam(self.net.parameters(), lr=self.lr, weight_decay=self.weight_decay) # define lr scheduler scheduler = self.lr_scheduler(optimizer, **self.lr_scheduler_kwargs) # define the loss function loss_fn = self.loss_fn(**self.loss_fn_kwargs) # load checkpoint if any try: checkpoint = torch.load(checkpoint_path, map_location=self.device) n_epoch_finished = checkpoint['n_epoch_finished'] self.net.load_state_dict(checkpoint['net_state']) optimizer.load_state_dict(checkpoint['optimizer_state']) scheduler.load_state_dict(checkpoint['lr_state']) epoch_loss_list = checkpoint['loss_evolution'] logger.info(f'Checkpoint loaded with {n_epoch_finished} epoch finished.') except FileNotFoundError: logger.info('No Checkpoint found. Training from beginning.') n_epoch_finished = 0 epoch_loss_list = [] # Start Training logger.info('Start training the Multi Classification task.') start_time = time.time() n_batch = len(train_loader) for epoch in range(n_epoch_finished, self.n_epoch): self.net.train() epoch_loss = 0.0 epoch_start_time = time.time() for b, data in enumerate(train_loader): # get data : target is original image, input is the corrupted image input, label, _ = data # put data on device input = input.to(self.device).float().requires_grad_(True) label = label.to(self.device).float()#long()#.requires_grad_(True) # zero the networks' gradients optimizer.zero_grad() # optimize the weights with backpropagation on the batch pred = self.net(input) pred = torch.sigmoid(input) loss = loss_fn(pred, label) loss.backward() optimizer.step() epoch_loss += loss.item() # print progress if self.print_progress: print_progessbar(b, n_batch, Name='\t\tTrain Batch', Size=50, erase=True) if valid_dataset: auc, acc, sub_acc, recall, precision, f1 = self.evaluate(valid_dataset, save_tsne=False, return_scores=True) valid_summary = f'| AUC {auc:.3%} | Accuracy {acc:.3%} | Subset-Accuracy {sub_acc:.3%} | Recall {recall:.3%} | Precision {precision:.3%} | F1 {f1:.3%} ' else: valid_summary = '' # Print epoch statistics logger.info(f'\t| Epoch : {epoch + 1:03}/{self.n_epoch:03} ' f'| Train time: {timedelta(seconds=int(time.time() - epoch_start_time))} ' f'| Train Loss: {epoch_loss / n_batch:.6f} ' f'{valid_summary}' f'| lr: {scheduler.get_last_lr()[0]:.7f} |') # Store epoch loss epoch_loss_list.append([epoch+1, epoch_loss/n_batch, auc]) # update lr scheduler.step() # Save Checkpoint every epochs if (epoch+1)%1 == 0 and checkpoint_path: checkpoint = {'n_epoch_finished': epoch+1, 'net_state': self.net.state_dict(), 'optimizer_state': optimizer.state_dict(), 'lr_state': scheduler.state_dict(), 'loss_evolution': epoch_loss_list} torch.save(checkpoint, checkpoint_path) logger.info('\tCheckpoint saved.') # End training self.outputs['train']['time'] = time.time() - start_time self.outputs['train']['evolution'] = {'col_name': ['Epoch', 'loss', 'Valid_AUC'], 'data': epoch_loss_list} logger.info(f"Finished training inpainter Binary Classifier in {timedelta(seconds=int(self.outputs['train']['time']))}") def evaluate(self, dataset, save_tsne=False, return_scores=False): """ Evaluate the passed network on the given dataset for the Context retoration task. ---------- INPUT |---- dataset (torch.utils.data.Dataset) the dataset to use for evaluation. It should output the original image, | and the sample index. |---- save_tsne (bool) whether to compute and store in self.outputs the tsne representation of the feature map | after the average pooling layer and before the MLP |---- return_scores (bool) whether to return the measured ROC AUC, accuracy, recall, precision and f1-score. OUTPUT |---- (auc) (float) the ROC AUC on the dataset. |---- (acc) (float) the accuracy on the dataset. |---- (recall) (float) the recall on the dataset. |---- (precision) (float) the precision on the dataset. |---- (f1) (float) the f1-score on the dataset. """ logger = logging.getLogger() # make loader loader = torch.utils.data.DataLoader(dataset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers, worker_init_fn=lambda _: np.random.seed()) # put net on device self.net = self.net.to(self.device) # Evaluate start_time = time.time() idx_repr = [] # placeholder for bottleneck representation idx_label_pred = [] # placeholder for label & prediction n_batch = len(loader) self.net.eval() with torch.no_grad(): for b, data in enumerate(loader): # get data : load in standard way (no patch swaped image) input, label, idx = data input = input.to(self.device).float() label = label.to(self.device).float() idx = idx.to(self.device) if save_tsne: # get representation self.net.return_bottleneck = True pred_score, repr = self.net(input) pred_score = torch.sigmoid(pred_score) pred = torch.where(pred_score > 0.5, torch.ones_like(pred_score, device=self.device), torch.zeros_like(pred_score, device=self.device)) # down sample representation for reduced memory impact #repr = nn.AdaptiveAvgPool2d((4,4))(repr) # add ravelled representations to placeholder idx_repr += list(zip(idx.cpu().data.tolist(), repr.view(repr.shape[0], -1).cpu().data.tolist())) idx_label_pred += list(zip(idx.cpu().data.tolist(), label.cpu().data.tolist(), pred.cpu().data.tolist(), pred_score.cpu().data.tolist())) # pred score is softmax activation of class 1 else: pred_score = self.net(input) pred_score = torch.sigmoid(pred_score) # B x N_class pred = torch.where(pred_score > 0.5, torch.ones_like(pred_score, device=self.device), torch.zeros_like(pred_score, device=self.device)) idx_label_pred += list(zip(idx.cpu().data.tolist(), label.cpu().data.tolist(), pred.cpu().data.tolist(), pred_score.cpu().data.tolist())) # print_progress if self.print_progress: print_progessbar(b, n_batch, Name='\t\tEvaluation Batch', Size=50, erase=True) # reset the network attriubtes if save_tsne: self.net.return_bottleneck = False # compute tSNE for representation if save_tsne: idx, repr = zip(*idx_repr) repr = np.array(repr) logger.info('Computing the t-SNE representation.') repr_2D = TSNE(n_components=2).fit_transform(repr) self.outputs['eval']['repr'] = list(zip(idx, repr_2D.tolist())) logger.info('Succesfully computed the t-SNE representation.') # Compute Accuracy _, label, pred, pred_score = zip(*idx_label_pred) label, pred, pred_score = np.array(label), np.array(pred), np.array(pred_score) auc = roc_auc_score(label, pred_score, average=self.score_average) acc = accuracy_score(label.ravel(), pred.ravel()) sub_acc = accuracy_score(label, pred) recall = recall_score(label, pred, average=self.score_average) precision = precision_score(label, pred, average=self.score_average) f1 = f1_score(label, pred, average=self.score_average) self.outputs['eval']['auc'] = auc self.outputs['eval']['acc'] = acc self.outputs['eval']['subset_acc'] = sub_acc self.outputs['eval']['recall'] = recall self.outputs['eval']['precision'] = precision self.outputs['eval']['f1'] = f1 self.outputs['eval']['pred'] = idx_label_pred # finish evluation self.outputs['eval']['time'] = time.time() - start_time if return_scores: return auc, acc, sub_acc, recall, precision, f1 def get_state_dict(self): """ Return the model weights as State dictionnary. ---------- INPUT |---- None OUTPUT |---- stat_dict (dict) the model's weights. """ return self.net.state_dict() def save_model(self, export_fn): """ Save the model. ---------- INPUT |---- export_fn (str) the export path. OUTPUT |---- None """ torch.save(self.net, export_fn) def save_model_state_dict(self, export_fn): """ Save the model. ---------- INPUT |---- export_fn (str) the export path. OUTPUT |---- None """ torch.save(self.net.state_dict(), export_fn) def load_model(self, import_fn, map_location='cpu'): """ Load a model from the given path. ---------- INPUT |---- import_fn (str) path where to get the model. |---- map_location (str) device on which to load the model. OUTPUT |---- None """ loaded_state_dict = torch.load(import_fn, map_location=map_location) self.net.load_state_dict(loaded_state_dict) def save_outputs(self, export_fn): """ Save the training stats in JSON. ---------- INPUT |---- export_fn (str) path where to get the results. OUTPUT |---- None """ with open(export_fn, 'w') as fn: json.dump(self.outputs, fn)
[ "logging.getLogger", "sklearn.metrics.roc_auc_score", "sklearn.metrics.recall_score", "sklearn.metrics.precision_score", "numpy.array", "torch.nn.functional.softmax", "sklearn.manifold.TSNE", "numpy.random.seed", "torch.nn.AdaptiveAvgPool2d", "torch.zeros_like", "torch.ones_like", "torch.save"...
[((4152, 4171), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (4169, 4171), False, 'import logging\n'), ((5701, 5712), 'time.time', 'time.time', ([], {}), '()\n', (5710, 5712), False, 'import time\n'), ((9717, 9736), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (9734, 9736), False, 'import logging\n'), ((10087, 10098), 'time.time', 'time.time', ([], {}), '()\n', (10096, 10098), False, 'import time\n'), ((12589, 12621), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['label', 'pred_score'], {}), '(label, pred_score)\n', (12602, 12621), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((12636, 12663), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['label', 'pred'], {}), '(label, pred)\n', (12650, 12663), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((12681, 12706), 'sklearn.metrics.recall_score', 'recall_score', (['label', 'pred'], {}), '(label, pred)\n', (12693, 12706), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((12727, 12755), 'sklearn.metrics.precision_score', 'precision_score', (['label', 'pred'], {}), '(label, pred)\n', (12742, 12755), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((12769, 12790), 'sklearn.metrics.f1_score', 'f1_score', (['label', 'pred'], {}), '(label, pred)\n', (12777, 12790), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((13731, 13762), 'torch.save', 'torch.save', (['self.net', 'export_fn'], {}), '(self.net, export_fn)\n', (13741, 13762), False, 'import torch\n'), ((14393, 14441), 'torch.load', 'torch.load', (['import_fn'], {'map_location': 'map_location'}), '(import_fn, map_location=map_location)\n', (14403, 14441), False, 'import torch\n'), ((18625, 18644), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (18642, 18644), False, 'import logging\n'), ((20173, 20184), 'time.time', 'time.time', ([], {}), '()\n', (20182, 20184), False, 'import time\n'), ((24201, 24220), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (24218, 24220), False, 'import logging\n'), ((24571, 24582), 'time.time', 'time.time', ([], {}), '()\n', (24580, 24582), False, 'import time\n'), ((27380, 27440), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['label', 'pred_score'], {'average': 'self.score_average'}), '(label, pred_score, average=self.score_average)\n', (27393, 27440), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((27517, 27544), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['label', 'pred'], {}), '(label, pred)\n', (27531, 27544), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((27562, 27615), 'sklearn.metrics.recall_score', 'recall_score', (['label', 'pred'], {'average': 'self.score_average'}), '(label, pred, average=self.score_average)\n', (27574, 27615), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((27636, 27692), 'sklearn.metrics.precision_score', 'precision_score', (['label', 'pred'], {'average': 'self.score_average'}), '(label, pred, average=self.score_average)\n', (27651, 27692), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((27706, 27755), 'sklearn.metrics.f1_score', 'f1_score', (['label', 'pred'], {'average': 'self.score_average'}), '(label, pred, average=self.score_average)\n', (27714, 27755), False, 'from sklearn.metrics import roc_auc_score, accuracy_score, recall_score, precision_score, f1_score\n'), ((28758, 28789), 'torch.save', 'torch.save', (['self.net', 'export_fn'], {}), '(self.net, export_fn)\n', (28768, 28789), False, 'import torch\n'), ((29420, 29468), 'torch.load', 'torch.load', (['import_fn'], {'map_location': 'map_location'}), '(import_fn, map_location=map_location)\n', (29430, 29468), False, 'import torch\n'), ((4957, 5010), 'torch.load', 'torch.load', (['checkpoint_path'], {'map_location': 'self.device'}), '(checkpoint_path, map_location=self.device)\n', (4967, 5010), False, 'import torch\n'), ((5899, 5910), 'time.time', 'time.time', ([], {}), '()\n', (5908, 5910), False, 'import time\n'), ((8350, 8361), 'time.time', 'time.time', ([], {}), '()\n', (8359, 8361), False, 'import time\n'), ((10297, 10312), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10310, 10312), False, 'import torch\n'), ((12110, 12124), 'numpy.array', 'np.array', (['repr'], {}), '(repr)\n', (12118, 12124), True, 'import numpy as np\n'), ((12521, 12536), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (12529, 12536), True, 'import numpy as np\n'), ((12538, 12552), 'numpy.array', 'np.array', (['pred'], {}), '(pred)\n', (12546, 12552), True, 'import numpy as np\n'), ((12554, 12574), 'numpy.array', 'np.array', (['pred_score'], {}), '(pred_score)\n', (12562, 12574), True, 'import numpy as np\n'), ((13138, 13149), 'time.time', 'time.time', ([], {}), '()\n', (13147, 13149), False, 'import time\n'), ((14788, 14815), 'json.dump', 'json.dump', (['self.outputs', 'fn'], {}), '(self.outputs, fn)\n', (14797, 14815), False, 'import json\n'), ((19430, 19483), 'torch.load', 'torch.load', (['checkpoint_path'], {'map_location': 'self.device'}), '(checkpoint_path, map_location=self.device)\n', (19440, 19483), False, 'import torch\n'), ((20371, 20382), 'time.time', 'time.time', ([], {}), '()\n', (20380, 20382), False, 'import time\n'), ((22834, 22845), 'time.time', 'time.time', ([], {}), '()\n', (22843, 22845), False, 'import time\n'), ((24781, 24796), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (24794, 24796), False, 'import torch\n'), ((26901, 26915), 'numpy.array', 'np.array', (['repr'], {}), '(repr)\n', (26909, 26915), True, 'import numpy as np\n'), ((27312, 27327), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (27320, 27327), True, 'import numpy as np\n'), ((27329, 27343), 'numpy.array', 'np.array', (['pred'], {}), '(pred)\n', (27337, 27343), True, 'import numpy as np\n'), ((27345, 27365), 'numpy.array', 'np.array', (['pred_score'], {}), '(pred_score)\n', (27353, 27365), True, 'import numpy as np\n'), ((28156, 28167), 'time.time', 'time.time', ([], {}), '()\n', (28165, 28167), False, 'import time\n'), ((29815, 29842), 'json.dump', 'json.dump', (['self.outputs', 'fn'], {}), '(self.outputs, fn)\n', (29824, 29842), False, 'import json\n'), ((6494, 6528), 'torch.nn.functional.softmax', 'nn.functional.softmax', (['pred'], {'dim': '(1)'}), '(pred, dim=1)\n', (6515, 6528), True, 'import torch.nn as nn\n'), ((8195, 8234), 'torch.save', 'torch.save', (['checkpoint', 'checkpoint_path'], {}), '(checkpoint, checkpoint_path)\n', (8205, 8234), False, 'import torch\n'), ((20974, 20994), 'torch.sigmoid', 'torch.sigmoid', (['input'], {}), '(input)\n', (20987, 20994), False, 'import torch\n'), ((22679, 22718), 'torch.save', 'torch.save', (['checkpoint', 'checkpoint_path'], {}), '(checkpoint, checkpoint_path)\n', (22689, 22718), False, 'import torch\n'), ((4475, 4491), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (4489, 4491), True, 'import numpy as np\n'), ((6774, 6847), 'src.utils.print_utils.print_progessbar', 'print_progessbar', (['b', 'n_batch'], {'Name': '"""\t\tTrain Batch"""', 'Size': '(50)', 'erase': '(True)'}), "(b, n_batch, Name='\\t\\tTrain Batch', Size=50, erase=True)\n", (6790, 6847), False, 'from src.utils.print_utils import print_progessbar\n'), ((9956, 9972), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (9970, 9972), True, 'import numpy as np\n'), ((10826, 10860), 'torch.nn.functional.softmax', 'nn.functional.softmax', (['pred'], {'dim': '(1)'}), '(pred, dim=1)\n', (10847, 10860), True, 'import torch.nn as nn\n'), ((11489, 11523), 'torch.nn.functional.softmax', 'nn.functional.softmax', (['pred'], {'dim': '(1)'}), '(pred, dim=1)\n', (11510, 11523), True, 'import torch.nn as nn\n'), ((11788, 11866), 'src.utils.print_utils.print_progessbar', 'print_progessbar', (['b', 'n_batch'], {'Name': '"""\t\tEvaluation Batch"""', 'Size': '(50)', 'erase': '(True)'}), "(b, n_batch, Name='\\t\\tEvaluation Batch', Size=50, erase=True)\n", (11804, 11866), False, 'from src.utils.print_utils import print_progessbar\n'), ((12210, 12230), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (12214, 12230), False, 'from sklearn.manifold import TSNE\n'), ((18948, 18964), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (18962, 18964), True, 'import numpy as np\n'), ((21240, 21313), 'src.utils.print_utils.print_progessbar', 'print_progessbar', (['b', 'n_batch'], {'Name': '"""\t\tTrain Batch"""', 'Size': '(50)', 'erase': '(True)'}), "(b, n_batch, Name='\\t\\tTrain Batch', Size=50, erase=True)\n", (21256, 21313), False, 'from src.utils.print_utils import print_progessbar\n'), ((24440, 24456), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (24454, 24456), True, 'import numpy as np\n'), ((25322, 25347), 'torch.sigmoid', 'torch.sigmoid', (['pred_score'], {}), '(pred_score)\n', (25335, 25347), False, 'import torch\n'), ((26132, 26157), 'torch.sigmoid', 'torch.sigmoid', (['pred_score'], {}), '(pred_score)\n', (26145, 26157), False, 'import torch\n'), ((26579, 26657), 'src.utils.print_utils.print_progessbar', 'print_progessbar', (['b', 'n_batch'], {'Name': '"""\t\tEvaluation Batch"""', 'Size': '(50)', 'erase': '(True)'}), "(b, n_batch, Name='\\t\\tEvaluation Batch', Size=50, erase=True)\n", (26595, 26657), False, 'from src.utils.print_utils import print_progessbar\n'), ((27001, 27021), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)'}), '(n_components=2)\n', (27005, 27021), False, 'from sklearn.manifold import TSNE\n'), ((10963, 10991), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(4, 4)'], {}), '((4, 4))\n', (10983, 10991), True, 'import torch.nn as nn\n'), ((25405, 25452), 'torch.ones_like', 'torch.ones_like', (['pred_score'], {'device': 'self.device'}), '(pred_score, device=self.device)\n', (25420, 25452), False, 'import torch\n'), ((25454, 25502), 'torch.zeros_like', 'torch.zeros_like', (['pred_score'], {'device': 'self.device'}), '(pred_score, device=self.device)\n', (25470, 25502), False, 'import torch\n'), ((26229, 26276), 'torch.ones_like', 'torch.ones_like', (['pred_score'], {'device': 'self.device'}), '(pred_score, device=self.device)\n', (26244, 26276), False, 'import torch\n'), ((26278, 26326), 'torch.zeros_like', 'torch.zeros_like', (['pred_score'], {'device': 'self.device'}), '(pred_score, device=self.device)\n', (26294, 26326), False, 'import torch\n'), ((7382, 7393), 'time.time', 'time.time', ([], {}), '()\n', (7391, 7393), False, 'import time\n'), ((21866, 21877), 'time.time', 'time.time', ([], {}), '()\n', (21875, 21877), False, 'import time\n')]
import random import numpy as np from tqdm.auto import tqdm from .hashing import pre_hash class StrategyHandler: def __init__(self, interactions, vissimhandler, hybrid_scorer, clustId2artIndexes, cluster_by_idx, artistId2artworkIndexes, artist_by_idx, user_as_items, threshold=0.7, confidence_margin=0.18, max_profile_size=None, ): self.interactions = interactions self.vissimhandler = vissimhandler self.hybrid_scorer = hybrid_scorer self.clustId2artIndexes = clustId2artIndexes self.cluster_by_idx = cluster_by_idx self.artistId2artworkIndexes = artistId2artworkIndexes self.artist_by_idx = artist_by_idx self.user_as_items = user_as_items self.threshold = threshold self.confidence_margin = confidence_margin self.max_profile_size = max_profile_size def __sample_artwork_index(self, idx, n_clusters=100): if random.random() <= self.threshold: if self.artist_by_idx[idx] == -1 or random.random() <= 0.5: j = random.choice(self.clustId2artIndexes[self.cluster_by_idx[idx]]) else: j = random.choice(self.artistId2artworkIndexes[self.artist_by_idx[idx]]) else: c = random.randint(0, n_clusters-1) j = random.choice(self.clustId2artIndexes[c]) return j def __sample_artwork_index_smart(self, artists_list, clusters_list, profile_set, n_clusters=100): while True: if random.random() <= self.threshold: if random.random() <= 0.5: a = random.choice(artists_list) i = random.choice(self.artistId2artworkIndexes[a]) else: c = random.choice(clusters_list) i = random.choice(self.clustId2artIndexes[c]) else: c = random.randint(0, n_clusters-1) i = random.choice(self.clustId2artIndexes[c]) if i not in profile_set: return i def __sample_artwork_index_naive(self, profile_set): while True: ni = random.randint(0, len(self.cluster_by_idx) - 1) if ni not in profile_set: return ni def strategy_1(self, samples_per_user, hashes_container): # Initialization interactions = self.interactions.copy() samples = [] for ui, group in tqdm(interactions.groupby("user_id"), desc="Strategy 1"): # Get profile artworks full_profile = np.hstack(group["item_id"].values).tolist() full_profile_set = set(full_profile) n = samples_per_user while n > 0: # Sample positive and negative items pi_index = random.randrange(len(full_profile)) pi = full_profile[pi_index] # Get profile if self.max_profile_size: # "pi_index + 1" to include pi in profile profile = full_profile[max(0, pi_index - self.max_profile_size + 1):pi_index + 1] else: profile = list(full_profile) while True: ni = self.__sample_artwork_index(pi) if ni not in full_profile_set: break # Compare visual similarity if self.vissimhandler.same(pi, ni): continue # Get score from hybrid scorer spi = self.hybrid_scorer.get_score(ui, profile, pi) sni = self.hybrid_scorer.get_score(ui, profile, ni) # Skip if hybrid scorer says so if spi <= sni: continue # If conditions are met, hash and enroll triple if self.user_as_items: triple = (profile, pi, ni) else: triple = (ui, pi, ni) if not hashes_container.enroll(pre_hash(triple, contains_iter=self.user_as_items)): continue # If not seen, store sample samples.append((profile, pi, ni, ui)) n -= 1 return samples def strategy_2(self, samples_per_item, hashes_container): # Initialization samples = [] if not self.user_as_items: assert samples_per_item == 0, "Trying to use fake strategy when real users are required" for pi, _ in enumerate(tqdm(self.artist_by_idx, desc="Strategy 2")): profile = (pi,) n = samples_per_item while n > 0: # Sample negative item while True: ni = self.__sample_artwork_index(pi) if ni != pi: break # Compare visual similarity if self.vissimhandler.same(pi, ni): continue # If conditions are met, hash and enroll triple triple = (profile, pi, ni) if not hashes_container.enroll(pre_hash(triple)): continue # If not seen, store sample samples.append((*triple, -1)) n -= 1 return samples def strategy_3(self, n_samples_per_user, hashes_container): # Initialization interactions = self.interactions.copy() samples = [] for ui, group in tqdm(interactions.groupby("user_id"), desc="Strategy 3"): full_profile = np.hstack(group["item_id"].values).tolist() artists_list = self.artist_by_idx[full_profile] clusters_list = self.cluster_by_idx[full_profile] user_margin = self.confidence_margin / len(full_profile) n = n_samples_per_user while n > 0: # Get profile if self.max_profile_size: # Use the latest items only profile = full_profile[-self.max_profile_size:] else: profile = list(full_profile) # Sample positive and negative items pi = self.__sample_artwork_index_smart(artists_list, clusters_list, set(profile)) ni = self.__sample_artwork_index_smart(artists_list, clusters_list, set(profile)) # Skip if sample items are the same if pi == ni: continue # Compare visual similarity if self.vissimhandler.same(pi, ni): continue # Get score from hybrid scorer and sort accordingly spi = self.hybrid_scorer.get_score(ui, profile, pi) sni = self.hybrid_scorer.get_score(ui, profile, ni) if spi < sni: spi, sni = sni, spi pi, ni = ni, pi # Skip if margin is not met if spi < sni + user_margin: continue # If conditions are met, hash and enroll triple if self.user_as_items: triple = (profile, pi, ni) else: triple = (ui, pi, ni) if not hashes_container.enroll(pre_hash(triple, contains_iter=self.user_as_items)): continue # If not seen, store sample samples.append((profile, pi, ni, ui)) n -= 1 return samples def strategy_4(self, samples_per_item, hashes_container): # Initialization samples = [] if not self.user_as_items: assert samples_per_item == 0, "Trying to use fake strategy when real users are required" for profile_item, _ in enumerate(tqdm(self.artist_by_idx, desc="Strategy 4")): profile = (profile_item,) n = samples_per_item while n > 0: # Sample positive item while True: pi = self.__sample_artwork_index(profile_item) if pi != profile_item: break # Sample negative item while True: ni = self.__sample_artwork_index(profile_item) if ni != profile_item: break # Skip if sample items are the same if pi == ni: continue # Compare visual similarity if self.vissimhandler.same(pi, ni): continue # Get score from hybrid scorer and sort accordingly spi = self.hybrid_scorer.simfunc(profile_item, pi) sni = self.hybrid_scorer.simfunc(profile_item, ni) if spi < sni: spi, sni = sni, spi pi, ni = ni, pi # Skip if margin is not met if spi < sni + self.confidence_margin: continue # If conditions are met, hash and enroll triple triple = (profile, pi, ni) if not hashes_container.enroll(pre_hash(triple)): continue # If not seen, store sample samples.append((*triple, -1)) n -= 1 return samples def naive_strategy_1(self, samples_per_user, hashes_container): # Initialization interactions = self.interactions.copy() samples = [] for ui, group in tqdm(interactions.groupby("user_id"), desc="Naive strategy 1"): # Get profile artworks full_profile = np.hstack(group["item_id"].values).tolist() full_profile_set = set(full_profile) n = samples_per_user while n > 0: # Sample positive and negative items pi_index = random.randrange(len(full_profile)) pi = full_profile[pi_index] # Get profile if self.max_profile_size: # "pi_index + 1" to include pi in profile profile = full_profile[max(0, pi_index - self.max_profile_size + 1):pi_index + 1] else: profile = list(full_profile) # (While loop is in the sampling method) ni = self.__sample_artwork_index_naive(full_profile_set) # If conditions are met, hash and enroll triple if self.user_as_items: triple = (profile, pi, ni) else: triple = (ui, pi, ni) if not hashes_container.enroll(pre_hash(triple, contains_iter=self.user_as_items)): continue # If not seen, store sample samples.append((profile, pi, ni, ui)) n -= 1 return samples
[ "random.choice", "numpy.hstack", "tqdm.auto.tqdm", "random.random", "random.randint" ]
[((1035, 1050), 'random.random', 'random.random', ([], {}), '()\n', (1048, 1050), False, 'import random\n'), ((1370, 1403), 'random.randint', 'random.randint', (['(0)', '(n_clusters - 1)'], {}), '(0, n_clusters - 1)\n', (1384, 1403), False, 'import random\n'), ((1419, 1460), 'random.choice', 'random.choice', (['self.clustId2artIndexes[c]'], {}), '(self.clustId2artIndexes[c])\n', (1432, 1460), False, 'import random\n'), ((4697, 4740), 'tqdm.auto.tqdm', 'tqdm', (['self.artist_by_idx'], {'desc': '"""Strategy 2"""'}), "(self.artist_by_idx, desc='Strategy 2')\n", (4701, 4740), False, 'from tqdm.auto import tqdm\n'), ((8059, 8102), 'tqdm.auto.tqdm', 'tqdm', (['self.artist_by_idx'], {'desc': '"""Strategy 4"""'}), "(self.artist_by_idx, desc='Strategy 4')\n", (8063, 8102), False, 'from tqdm.auto import tqdm\n'), ((1164, 1228), 'random.choice', 'random.choice', (['self.clustId2artIndexes[self.cluster_by_idx[idx]]'], {}), '(self.clustId2artIndexes[self.cluster_by_idx[idx]])\n', (1177, 1228), False, 'import random\n'), ((1269, 1337), 'random.choice', 'random.choice', (['self.artistId2artworkIndexes[self.artist_by_idx[idx]]'], {}), '(self.artistId2artworkIndexes[self.artist_by_idx[idx]])\n', (1282, 1337), False, 'import random\n'), ((1621, 1636), 'random.random', 'random.random', ([], {}), '()\n', (1634, 1636), False, 'import random\n'), ((2009, 2042), 'random.randint', 'random.randint', (['(0)', '(n_clusters - 1)'], {}), '(0, n_clusters - 1)\n', (2023, 2042), False, 'import random\n'), ((2062, 2103), 'random.choice', 'random.choice', (['self.clustId2artIndexes[c]'], {}), '(self.clustId2artIndexes[c])\n', (2075, 2103), False, 'import random\n'), ((1119, 1134), 'random.random', 'random.random', ([], {}), '()\n', (1132, 1134), False, 'import random\n'), ((1676, 1691), 'random.random', 'random.random', ([], {}), '()\n', (1689, 1691), False, 'import random\n'), ((1725, 1752), 'random.choice', 'random.choice', (['artists_list'], {}), '(artists_list)\n', (1738, 1752), False, 'import random\n'), ((1778, 1824), 'random.choice', 'random.choice', (['self.artistId2artworkIndexes[a]'], {}), '(self.artistId2artworkIndexes[a])\n', (1791, 1824), False, 'import random\n'), ((1873, 1901), 'random.choice', 'random.choice', (['clusters_list'], {}), '(clusters_list)\n', (1886, 1901), False, 'import random\n'), ((1927, 1968), 'random.choice', 'random.choice', (['self.clustId2artIndexes[c]'], {}), '(self.clustId2artIndexes[c])\n', (1940, 1968), False, 'import random\n'), ((2691, 2725), 'numpy.hstack', 'np.hstack', (["group['item_id'].values"], {}), "(group['item_id'].values)\n", (2700, 2725), True, 'import numpy as np\n'), ((5774, 5808), 'numpy.hstack', 'np.hstack', (["group['item_id'].values"], {}), "(group['item_id'].values)\n", (5783, 5808), True, 'import numpy as np\n'), ((9982, 10016), 'numpy.hstack', 'np.hstack', (["group['item_id'].values"], {}), "(group['item_id'].values)\n", (9991, 10016), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import numpy as np from mla.ensemble import DecisionTreeRegressor class BoostingTree(object): def __init__(self, base_model=DecisionTreeRegressor, model_params=(2,)): self._base_model = base_model self._model_params = model_params self._trained_models = None def train_fit(self, X, y, max_iters=5): self._trained_models = [] residual = y for it in range(max_iters): model = self._base_model(*self._model_params) model.train_fit(X, residual) self._trained_models.append(model) pred = model.predict(X) residual -= pred print("residual: ", residual) def predict(self, X): y = np.zeros(np.shape(X)[0]) for model in self._trained_models: y += model.predict(X) return y
[ "numpy.shape" ]
[((785, 796), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (793, 796), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt header = ["epoch_id","eigenvector_ABS"] eigerr = np.array( [[32,0.052066717168937], [48,0.030700074707731], [64,0.022813341170428], [80,0.016773069896906], [96,0.015850476370356], [112,0.023858656532983], [128,0.032345770944394], [144,0.040679204151823], [160,0.048477275222999], [176,0.056219202897372], [192,0.062635218621664], [208,0.068135724700112], [224,0.073183325685921], [240,0.077679463649992]] ) # Get ylim fig, ax = plt.subplots(1, 1, figsize=(5,4)) ax.set_xlabel('Problem size') ax.set_ylabel('Absolute Error') plt.axvline(x=32, c='black', linestyle='--') plt.axvline(x=128, c='black', linestyle='--') plt.xticks(eigerr[::2,0]) ax.plot(eigerr[:,0], eigerr[:,1], linestyle='-', marker='o', color = "#8A4F7D") ymin, ymax = ax.get_ylim() plt.savefig('test-varying-sizes-app-e.eps', format='eps', dpi=200) plt.close() fig, ax = plt.subplots(1, 1, figsize=(5,4)) ax.set_xlabel('Problem size') ax.set_ylabel('Absolute Error') plt.axvline(x=32, c='black', linestyle='--') plt.axvline(x=128, c='black', linestyle='--') plt.xticks(eigerr[::2,0]) ax.fill_betweenx([0,ymax], 32, 128, alpha=0.1, facecolor='#F7EF81') ax.plot(eigerr[:,0], eigerr[:,1], linestyle='-', marker='o', color = "#8A4F7D") ax.set_ylim(0, ymax) plt.savefig('test-varying-sizes-app-e.eps', format='eps', dpi=200)
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.xticks", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.subplots", "matplotlib.pyplot.axvline" ]
[((101, 494), 'numpy.array', 'np.array', (['[[32, 0.052066717168937], [48, 0.030700074707731], [64, 0.022813341170428],\n [80, 0.016773069896906], [96, 0.015850476370356], [112, \n 0.023858656532983], [128, 0.032345770944394], [144, 0.040679204151823],\n [160, 0.048477275222999], [176, 0.056219202897372], [192, \n 0.062635218621664], [208, 0.068135724700112], [224, 0.073183325685921],\n [240, 0.077679463649992]]'], {}), '([[32, 0.052066717168937], [48, 0.030700074707731], [64, \n 0.022813341170428], [80, 0.016773069896906], [96, 0.015850476370356], [\n 112, 0.023858656532983], [128, 0.032345770944394], [144, \n 0.040679204151823], [160, 0.048477275222999], [176, 0.056219202897372],\n [192, 0.062635218621664], [208, 0.068135724700112], [224, \n 0.073183325685921], [240, 0.077679463649992]])\n', (109, 494), True, 'import numpy as np\n'), ((482, 516), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(5, 4)'}), '(1, 1, figsize=(5, 4))\n', (494, 516), True, 'import matplotlib.pyplot as plt\n'), ((578, 622), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(32)', 'c': '"""black"""', 'linestyle': '"""--"""'}), "(x=32, c='black', linestyle='--')\n", (589, 622), True, 'import matplotlib.pyplot as plt\n'), ((623, 668), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(128)', 'c': '"""black"""', 'linestyle': '"""--"""'}), "(x=128, c='black', linestyle='--')\n", (634, 668), True, 'import matplotlib.pyplot as plt\n'), ((669, 695), 'matplotlib.pyplot.xticks', 'plt.xticks', (['eigerr[::2, 0]'], {}), '(eigerr[::2, 0])\n', (679, 695), True, 'import matplotlib.pyplot as plt\n'), ((802, 868), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""test-varying-sizes-app-e.eps"""'], {'format': '"""eps"""', 'dpi': '(200)'}), "('test-varying-sizes-app-e.eps', format='eps', dpi=200)\n", (813, 868), True, 'import matplotlib.pyplot as plt\n'), ((869, 880), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (878, 880), True, 'import matplotlib.pyplot as plt\n'), ((891, 925), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(5, 4)'}), '(1, 1, figsize=(5, 4))\n', (903, 925), True, 'import matplotlib.pyplot as plt\n'), ((987, 1031), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(32)', 'c': '"""black"""', 'linestyle': '"""--"""'}), "(x=32, c='black', linestyle='--')\n", (998, 1031), True, 'import matplotlib.pyplot as plt\n'), ((1032, 1077), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(128)', 'c': '"""black"""', 'linestyle': '"""--"""'}), "(x=128, c='black', linestyle='--')\n", (1043, 1077), True, 'import matplotlib.pyplot as plt\n'), ((1078, 1104), 'matplotlib.pyplot.xticks', 'plt.xticks', (['eigerr[::2, 0]'], {}), '(eigerr[::2, 0])\n', (1088, 1104), True, 'import matplotlib.pyplot as plt\n'), ((1274, 1340), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""test-varying-sizes-app-e.eps"""'], {'format': '"""eps"""', 'dpi': '(200)'}), "('test-varying-sizes-app-e.eps', format='eps', dpi=200)\n", (1285, 1340), True, 'import matplotlib.pyplot as plt\n')]
""" Utitlity functions that will be used by the sequence data generators IGNORE_FOR_SPHINX_DOCS: List of functions: getChromPositions - returns two column dataframe of chromosome positions spanning the entire chromosome at a) regular intervals or b) random locations getPeakPositions - returns two column dataframe of chromosome positions getInputTasks - when input data is fed as a path to a directory, that contains files (single task) or sub directories (multi tasl) that follow a strict naming convention, this function returns a nested python dictionary of tasks, specifying the 'signal' and/or 'control' bigWigs, 'peaks' file, 'task_id' & 'strand roundToMultiple - Return the largest multiple of y < x one_hot_encode - returns a 3-dimension numpy array of one hot encoding of a list of DNA sequences reverse_complement_of_sequences - returns the reverse complement of a list of sequences reverse_complement_of_profiles - returns the reverse complement of the assay signal License: MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. IGNORE_FOR_SPHINX_DOCS """ import glob import logging import numpy as np import os import pandas as pd from collections import OrderedDict from mseqgen.exceptionhandler import NoTracebackException def getChromPositions(chroms, chrom_sizes, flank, mode='sequential', num_positions=-1, step=50): """ Chromosome positions spanning the entire chromosome at a) regular intervals or b) random locations Args: chroms (list): The list of required chromosomes chrom_sizes (pandas.Dataframe): dataframe of chromosome sizes with 'chrom' and 'size' columns flank (int): Buffer size before & after the position to ensure we dont fetch values at index < 0 & > chrom size mode (str): mode of returned position 'sequential' (from the beginning) or 'random' num_positions (int): number of chromosome positions to return on each chromosome, use -1 to return positions across the entrire chromosome for all given chromosomes in `chroms`. mode='random' cannot be used with num_positions=-1 step (int): the interval between consecutive chromosome positions in 'sequential' mode Returns: pandas.DataFrame: two column dataframe of chromosome positions (chrom, pos) """ if mode == 'random' and num_positions == -1: raise NoTracebackException( "Incompatible parameter pairing: 'mode' = random, " "'num_positions' = -1") # check if chrom_sizes has a column called 'chrom' if 'chrom' not in chrom_sizes.columns: logging.error("Expected column 'chrom' not found in chrom_sizes") return None chrom_sizes = chrom_sizes.set_index('chrom') # initialize an empty dataframe with 'chrom' and 'pos' columns positions = pd.DataFrame(columns=['chrom', 'pos']) # for each chromosome in the list for i in range(len(chroms)): chrom_size = chrom_sizes.at[chroms[i], 'size'] # keep start & end within bounds start = flank end = chrom_size - flank + 1 if mode == 'random': # randomly sample positions pos_array = np.random.randint(start, end, num_positions) if mode == 'sequential': _end = end if num_positions != -1: # change the last positon based on the number of # required positions _end = start + step * num_positions # if the newly computed 'end' goes beyond the # chromosome end (we could throw an error here) if _end > end: _end = end # positions at regular intervals pos_array = list(range(start, _end, step)) # construct a dataframe for this chromosome chrom_df = pd.DataFrame({'chrom': [chroms[i]] * len(pos_array), 'pos': pos_array}) # concatenate to existing df positions = pd.concat([positions, chrom_df]) return positions def getPeakPositions(tasks, chroms, chrom_sizes, flank, drop_duplicates=False): """ Peak positions for all the tasks filtered based on required chromosomes and other qc filters. Since 'task' here refers one strand of input/output, if the data is stranded the peaks will be duplicated for the plus and minus strand. Args: tasks (dict): A python dictionary containing the task information. Each task in tasks should have the key 'peaks' that has the path to he peaks file chroms (list): The list of required test chromosomes chrom_sizes (pandas.Dataframe): dataframe of chromosome sizes with 'chrom' and 'size' columns flank (int): Buffer size before & after the position to ensure we dont fetch values at index < 0 & > chrom size drop_duplicates (boolean): True if duplicates should be dropped from returned dataframe. Returns: pandas.DataFrame: two column dataframe of peak positions (chrom, pos) """ # necessary for dataframe apply operation below --->>> chrom_size_dict = dict(chrom_sizes.to_records(index=False)) # initialize an empty dataframe allPeaks = pd.DataFrame() for task in tasks: peaks_df = pd.read_csv(tasks[task]['peaks'], sep='\t', header=None, names=['chrom', 'st', 'end', 'name', 'score', 'strand', 'signal', 'p', 'q', 'summit']) # keep only those rows corresponding to the required # chromosomes peaks_df = peaks_df[peaks_df['chrom'].isin(chroms)] # create new column for peak pos peaks_df['pos'] = peaks_df['st'] + peaks_df['summit'] # compute left flank coordinates of the input sequences # (including the allowed jitter) peaks_df['flank_left'] = (peaks_df['pos'] - flank).astype(int) # compute right flank coordinates of the input sequences # (including the allowed jitter) peaks_df['flank_right'] = (peaks_df['pos'] + flank).astype(int) # filter out rows where the left flank coordinate is < 0 peaks_df = peaks_df[peaks_df['flank_left'] >= 0] # --->>> create a new column for chrom size peaks_df["chrom_size"] = peaks_df['chrom'].apply( lambda chrom: chrom_size_dict[chrom]) # filter out rows where the right flank coordinate goes beyond # chromosome size peaks_df = peaks_df[peaks_df['flank_right'] <= peaks_df['chrom_size']] # sort based on chromosome number and right flank coordinate peaks_df = peaks_df.sort_values(['chrom', 'flank_right']).reset_index( drop=True) # append to all peaks data frame allPeaks = allPeaks.append(peaks_df[['chrom', 'pos']]) allPeaks = allPeaks.reset_index(drop=True) # drop the duplicate rows, i.e. the peaks that get duplicated # for the plus and minus strand tasks if drop_duplicates: allPeaks = allPeaks.drop_duplicates(ignore_index=True) return allPeaks def roundToMultiple(x, y): """Return the largest multiple of y < x Args: x (int): the number to round y (int): the multiplier Returns: int: largest multiple of y <= x """ r = (x + int(y / 2)) & ~(y - 1) if r > x: r = r - y return r def round_to_multiple(x, y, smallest=False): """ Return the largest multiple of y <= x or smallest multiple of y >= x Args: x (int): the number to round up to y (int): the multiplier smallest (boolean): set to True to return smallest multiple of y >= x Returns: int: if 'smallest' is False then largest multiple of y <= x, else smallest multiple of y >= x """ # remainder val = x % y # x is a multiple of y if val == 0: return x if smallest: # subtract remainder and the multiplier return (x - val) + y else: # subtract remainder return (x - val) def fix_sequence_length(sequence, length): """ Function to check if length of sequence matches specified length and then return a sequence that's either padded or truncated to match the given length Args: sequence (str): the input sequence length (int): expected length Returns: str: string of length 'length' """ # check if the sequence is smaller than expected length if len(sequence) < length: # pad the sequence with 'N's sequence += 'N' * (length - len(sequence)) # check if the sequence is larger than expected length elif len(sequence) > length: # truncate to expected length sequence = sequence[:length] return sequence def one_hot_encode(sequences, seq_length): """ One hot encoding of a list of DNA sequences Args: sequences (list): python list of strings of equal length seq_length (int): expected length of each sequence in the list Returns: numpy.ndarray: 3-dimension numpy array with shape (len(sequences), len(list_item), 4) """ if len(sequences) == 0: logging.error("'sequences' is empty") return None # First, let's make sure all sequences are of equal length sequences = list(map( fix_sequence_length, sequences, [seq_length] * len(sequences))) # Step 1. convert sequence list into a single string _sequences = ''.join(sequences) # Step 2. translate the alphabet to a string of digits transtab = str.maketrans('ACGTNYRMSWK', '01234444444') sequences_trans = _sequences.translate(transtab) # Step 3. convert to list of ints int_sequences = list(map(int, sequences_trans)) # Step 4. one hot encode using int_sequences to index # into an 'encoder' array encoder = np.vstack([np.eye(4), np.zeros(4)]) X = encoder[int_sequences] # Step 5. reshape return X.reshape(len(sequences), len(sequences[0]), 4) def reverse_complement_of_sequences(sequences): """ Reverse complement of DNA sequences Args: sequences (list): python list of strings of DNA sequence of arbitraty length Returns: list: python list of strings """ if len(sequences) == 0: logging.error("'sequences' is empty") # reverse complement translation table rev_comp_tab = str.maketrans("ACTG", "TGAC") # translate and reverse ([::-1] <= [start:end:step]) return [seq.translate(rev_comp_tab)[::-1] for seq in sequences] def reverse_complement_of_profiles(profiles, stranded=True): r""" Reverse complement of an genomics assay signal profile Args: profiles (numpy.ndarray): 3-dimensional numpy array, a batch of multitask profiles of shape (#examples, seq_len, #assays) if unstranded and (#examples, seq_len, #assays*2) if stranded. In the stranded case the assumption is: the postive & negative strands occur in pairs on axis=2(i.e. 3rd dimension) e.g. 0th & 1st index, 2nd & 3rd... Returns: numpy.ndarray: 3-dimensional numpy array IGNORE_FOR_SPHINX_DOCS: CONVERT (Stranded profile) ______ | | | | _______| |___________________________________________ acgggttttccaaagggtttttaaaacccggttgtgtgtccacacacagtgtgtcaca ---------------------------------------------------------- ---------------------------------------------------------- ʇƃɔɔɔɐɐɐɐƃƃʇʇʇɔɔɔɐɐɐɐɐʇʇʇʇƃƃƃɔɔɐɐɔɐɔɐɔɐƃƃʇƃʇƃʇƃʇɔɐɔɐɔɐƃʇƃʇ ____________________________________________ ________ \ / \ / \/ TO /\ / \ ________/ \____________________________________________ tgtgacacactgtgtgtggacacacaaccgggttttaaaaaccctttggaaaacccgt ---------------------------------------------------------- ---------------------------------------------------------- ɐɔɐɔʇƃʇƃʇƃɐɔɐɔɐɔɐɔɔʇƃʇƃʇƃʇʇƃƃɔɔɔɐɐɐɐʇʇʇʇʇƃƃƃɐɐɐɔɔʇʇʇʇƃƃƃɔɐ ___________________________________________ _______ | | | | |______| OR CONVERT (unstranded profile) ______ | | | | _______| |___________________________________________ acgggttttccaaagggtttttaaaacccggttgtgtgtccacacacagtgtgtcaca TO ______ | | | | ___________________________________________| |_______ tgtgacacactgtgtgtggacacacaaccgggttttaaaaaccctttggaaaacccgt IGNORE_FOR_SPHINX_DOCS """ # check if profiles is 3-dimensional if profiles.ndim != 3: logging.error("'profiles' should be a 3-dimensional array. " "Found {}".format(profiles.ndim)) # check if the 3rd dimension is an even number if profiles are stranded if stranded and (profiles.shape[2] % 2) != 0: logging.error("3rd dimension of stranded 'profiles' should be even. " "Found {}".format(profiles.shape)) if stranded: # get reshaped version of profiles array # axis = 2 becomes #assays tmp_prof = profiles.reshape( (profiles.shape[0], profiles.shape[1], -1, 2)) # get reverse complement by flipping along axis 1 & 3 # axis 1 is the sequence length axis & axis 3 is the # +/- strand axis after reshaping rev_comp_profile = np.flip(tmp_prof, axis=(1, 3)) # reshape back to match shape of the input return rev_comp_profile.reshape(profiles.shape) else: return np.flip(profiles, axis=1)
[ "numpy.flip", "numpy.eye", "pandas.read_csv", "mseqgen.exceptionhandler.NoTracebackException", "numpy.random.randint", "numpy.zeros", "pandas.concat", "pandas.DataFrame", "logging.error" ]
[((4452, 4490), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['chrom', 'pos']"}), "(columns=['chrom', 'pos'])\n", (4464, 4490), True, 'import pandas as pd\n'), ((7118, 7132), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7130, 7132), True, 'import pandas as pd\n'), ((3999, 4097), 'mseqgen.exceptionhandler.NoTracebackException', 'NoTracebackException', (['"""Incompatible parameter pairing: \'mode\' = random, \'num_positions\' = -1"""'], {}), '(\n "Incompatible parameter pairing: \'mode\' = random, \'num_positions\' = -1")\n', (4019, 4097), False, 'from mseqgen.exceptionhandler import NoTracebackException\n'), ((4228, 4293), 'logging.error', 'logging.error', (['"""Expected column \'chrom\' not found in chrom_sizes"""'], {}), '("Expected column \'chrom\' not found in chrom_sizes")\n', (4241, 4293), False, 'import logging\n'), ((5693, 5725), 'pandas.concat', 'pd.concat', (['[positions, chrom_df]'], {}), '([positions, chrom_df])\n', (5702, 5725), True, 'import pandas as pd\n'), ((7179, 7326), 'pandas.read_csv', 'pd.read_csv', (["tasks[task]['peaks']"], {'sep': '"""\t"""', 'header': 'None', 'names': "['chrom', 'st', 'end', 'name', 'score', 'strand', 'signal', 'p', 'q', 'summit']"}), "(tasks[task]['peaks'], sep='\\t', header=None, names=['chrom',\n 'st', 'end', 'name', 'score', 'strand', 'signal', 'p', 'q', 'summit'])\n", (7190, 7326), True, 'import pandas as pd\n'), ((11430, 11467), 'logging.error', 'logging.error', (['"""\'sequences\' is empty"""'], {}), '("\'sequences\' is empty")\n', (11443, 11467), False, 'import logging\n'), ((12646, 12683), 'logging.error', 'logging.error', (['"""\'sequences\' is empty"""'], {}), '("\'sequences\' is empty")\n', (12659, 12683), False, 'import logging\n'), ((16852, 16882), 'numpy.flip', 'np.flip', (['tmp_prof'], {'axis': '(1, 3)'}), '(tmp_prof, axis=(1, 3))\n', (16859, 16882), True, 'import numpy as np\n'), ((17034, 17059), 'numpy.flip', 'np.flip', (['profiles'], {'axis': '(1)'}), '(profiles, axis=1)\n', (17041, 17059), True, 'import numpy as np\n'), ((4837, 4881), 'numpy.random.randint', 'np.random.randint', (['start', 'end', 'num_positions'], {}), '(start, end, num_positions)\n', (4854, 4881), True, 'import numpy as np\n'), ((12142, 12151), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (12148, 12151), True, 'import numpy as np\n'), ((12153, 12164), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (12161, 12164), True, 'import numpy as np\n')]
from __future__ import unicode_literals, absolute_import, division from GCR import GCRQuery from astropy.io import fits import numpy as np import sys import pickle import GCRCatalogs import os from .base import BaseValidationTest, TestResult from .plotting import plt __all__ = ['RedSequence'] rs_path = '/global/projecta/projectdirs/lsst/groups/CS/descqa/data/redsequence/{}_rs_{}.fits' class RedSequence(BaseValidationTest): def __init__(self, **kwargs): #pylint: disable=W0231 self.kwargs = kwargs self.bands = ['g', 'r', 'i', 'z'] self.n_bands = len(self.bands) self.validation_catalog = kwargs.get('validation_catalog', 'des_y1') self.rs_z = fits.open(rs_path.format(self.validation_catalog, 'z'))[0].data[:-1] self.rs_mean = fits.open(rs_path.format(self.validation_catalog, 'c'))[0].data[:-1] self.rs_sigma = fits.open(rs_path.format(self.validation_catalog, 's'))[0].data[...,:-1] self.z_bins = np.linspace(*kwargs.get('z_bins', (0.0, 1.0, 31))) self.c_bins = np.linspace(*kwargs.get('c_bins', (-0.5, 2.0, 101))) self.dz = self.z_bins[1:] - self.z_bins[:-1] self.dc = self.c_bins[1:] - self.c_bins[:-1] self.n_z_bins = len(self.z_bins)-1 self.n_c_bins = len(self.c_bins)-1 self.z_mean = (self.z_bins[1:] + self.z_bins[:-1]) / 2 self.c_mean = (self.c_bins[1:] + self.c_bins[:-1]) / 2 possible_mag_fields = ('mag_true_{}_lsst', 'mag_true_{}_des', 'mag_true_{}_sdss', ) self.possible_mag_fields = [[f.format(self.bands[i]) for f in possible_mag_fields] for i in range(len(self.bands))] self.possible_absmag_fields = ('Mag_true_r_lsst_z0', 'Mag_true_r_lsst_z01' 'Mag_true_r_des_z0', 'Mag_true_r_des_z01', 'Mag_true_r_sdss_z0', 'Mag_true_r_sdss_z01', ) def prepare_galaxy_catalog(self, gc): quantities_needed = {'redshift_true', 'is_central', 'halo_mass', 'halo_id', 'galaxy_id'} if gc.has_quantities(['truth/RHALO', 'truth/R200']): gc.add_quantity_modifier('r_host', 'truth/RHALO', overwrite=True) gc.add_quantity_modifier('r_vir', 'truth/R200', overwrite=True) quantities_needed.add('r_host') quantities_needed.add('r_vir') mag_fields = [] for i in range(len(self.bands)): mag_fields.append(gc.first_available(*self.possible_mag_fields[i])) quantities_needed.add(mag_fields[i]) absolute_magnitude_field = gc.first_available(*self.possible_absmag_fields) quantities_needed.add(absolute_magnitude_field) if ((not np.all(gc.has_quantities(mag_fields))) and gc.has_quantities(quantities_needed)): return return absolute_magnitude_field, mag_fields, quantities_needed def run_on_single_catalog(self, catalog_instance, catalog_name, output_dir): prepared = self.prepare_galaxy_catalog(catalog_instance) if prepared is None: return TestResult(skipped=True) try: redmapper = GCRCatalogs.load_catalog(catalog_name+'_redmapper') except: return TestResult(skipped=True) print(redmapper) redmapper = redmapper.get_quantities(['galaxy_id']) absolute_magnitude_field, mag_fields, quantities_needed = prepared bins = (self.z_bins, self.c_bins) hist_cen = np.zeros((self.n_z_bins, self.n_c_bins, self.n_bands-1)) hist_sat = np.zeros_like(hist_cen) hist_mem_cen = np.zeros_like(hist_cen) hist_mem_sat = np.zeros_like(hist_cen) cen_query = GCRQuery('is_central & (halo_mass > 5e13) & ({} < -19)'.format(absolute_magnitude_field)) sat_query = GCRQuery('(~is_central) & (halo_mass > 5e13) & ({} < -19)'.format(absolute_magnitude_field)) if 'r_host' in quantities_needed and 'r_vir' in quantities_needed: sat_query &= GCRQuery('r_host < r_vir') for data in catalog_instance.get_quantities(quantities_needed, return_iterator=True): cen_mask = cen_query.mask(data) sat_mask = sat_query.mask(data) mem_mask = np.in1d(data['galaxy_id'], redmapper['galaxy_id']) print(catalog_instance) print(data['galaxy_id']) print(redmapper['galaxy_id']) print(mem_mask.any()) for i in range(self.n_bands-1): color = data[mag_fields[i]] - data[mag_fields[i+1]] hdata = np.stack([data['redshift_true'], color]).T hist_cen[:,:,i] += np.histogramdd(hdata[cen_mask], bins)[0] hist_sat[:,:,i] += np.histogramdd(hdata[sat_mask], bins)[0] hist_mem_cen[:,:,i] += np.histogramdd(hdata[mem_mask & cen_mask], bins)[0] hist_mem_sat[:,:,i] += np.histogramdd(hdata[mem_mask & sat_mask], bins)[0] data = cen_mask = sat_mask = mem_mask = None rs_mean, rs_scat, red_frac_sat, red_frac_cen = self.compute_summary_statistics(hist_sat, hist_cen, hist_mem_sat, hist_mem_cen) fn = os.path.join(output_dir, 'summary.pkl') red_seq = {'rs_mean':rs_mean, 'rs_scat':rs_scat, 'red_frac_sat':red_frac_sat, 'red_frac_cen':red_frac_cen, 'hist_cen':hist_cen, 'hist_sat':hist_sat, 'hist_mem_cen':hist_mem_cen, 'hist_mem_sat':hist_mem_sat } with open(fn, 'wb') as fp: pickle.dump(red_seq, fp) self.make_plot(red_seq, catalog_name, os.path.join(output_dir, 'red_sequence.png')) return TestResult(inspect_only=True) def compute_summary_statistics(self, hist_sat, hist_cen, hist_mem_sat, hist_mem_cen): """ Calculate mean, and scatter of red sequence and red fraction. """ tot_sat = np.sum(hist_sat, axis=(1,2)) tot_cen = np.sum(hist_cen, axis=(1,2)) tot_sat_mem = np.sum(hist_mem_sat, axis=(1,2)) tot_cen_mem = np.sum(hist_mem_cen, axis=(1,2)) rs_mean = np.sum(self.c_mean.reshape(1,-1,1) * (hist_mem_sat + hist_mem_cen) * self.dc.reshape(1,-1,1), axis=1) / np.sum((hist_mem_sat + hist_mem_cen) * self.dc.reshape(1,-1,1), axis=1) rs_scat = np.sqrt(np.sum((self.c_mean.reshape(1,-1,1) - rs_mean.reshape(-1,1,self.n_bands-1)) ** 2 * (hist_mem_sat + hist_mem_cen) * self.dc.reshape(1,-1,1), axis=1) / np.sum((hist_mem_sat + hist_mem_cen) * self.dc.reshape(1,-1,1), axis=1)) red_frac_sat = 1 - np.sum((hist_sat - hist_mem_sat)/tot_sat.reshape(-1,1,1), axis=(1,2)) red_frac_cen = 1 - np.sum((hist_cen - hist_mem_cen)/tot_cen.reshape(-1,1,1), axis=(1,2)) return rs_mean, rs_scat, red_frac_sat, red_frac_cen def make_plot(self, red_seq, name, save_to): fig, ax = plt.subplots(2, self.n_bands-1, sharex=True, sharey=False, figsize=(12,10), dpi=100) for i in range(self.n_bands-1): ax[0,i].plot(self.z_mean, red_seq['rs_mean'][:,i]) ax[0,i].plot(self.rs_z, self.rs_mean[:,i], label=self.validation_catalog) ax[1,i].plot(self.z_mean, red_seq['rs_scat'][:,i]) ax[1,i].plot(self.rs_z, self.rs_sigma[i,i,:], label=self.validation_catalog) ax[0,i].set_ylabel(r'$\bar{%s-%s}$'% (self.bands[i], self.bands[i+1])) ax[1,i].set_ylabel(r'$\sigma(%s-%s)$'% (self.bands[i], self.bands[i+1])) ax[1,i].set_xlabel(r'$z$') ax[0,i].legend(loc='lower right', frameon=False, fontsize='medium') ax = fig.add_subplot(111, frameon=False) ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off') ax.grid(False) ax.set_title(name) fig.tight_layout() fig.savefig(save_to) plt.close(fig)
[ "pickle.dump", "numpy.histogramdd", "numpy.in1d", "os.path.join", "GCR.GCRQuery", "numpy.sum", "numpy.zeros", "numpy.stack", "GCRCatalogs.load_catalog", "numpy.zeros_like" ]
[((3813, 3871), 'numpy.zeros', 'np.zeros', (['(self.n_z_bins, self.n_c_bins, self.n_bands - 1)'], {}), '((self.n_z_bins, self.n_c_bins, self.n_bands - 1))\n', (3821, 3871), True, 'import numpy as np\n'), ((3889, 3912), 'numpy.zeros_like', 'np.zeros_like', (['hist_cen'], {}), '(hist_cen)\n', (3902, 3912), True, 'import numpy as np\n'), ((3936, 3959), 'numpy.zeros_like', 'np.zeros_like', (['hist_cen'], {}), '(hist_cen)\n', (3949, 3959), True, 'import numpy as np\n'), ((3983, 4006), 'numpy.zeros_like', 'np.zeros_like', (['hist_cen'], {}), '(hist_cen)\n', (3996, 4006), True, 'import numpy as np\n'), ((5606, 5645), 'os.path.join', 'os.path.join', (['output_dir', '"""summary.pkl"""'], {}), "(output_dir, 'summary.pkl')\n", (5618, 5645), False, 'import os\n'), ((6434, 6463), 'numpy.sum', 'np.sum', (['hist_sat'], {'axis': '(1, 2)'}), '(hist_sat, axis=(1, 2))\n', (6440, 6463), True, 'import numpy as np\n'), ((6481, 6510), 'numpy.sum', 'np.sum', (['hist_cen'], {'axis': '(1, 2)'}), '(hist_cen, axis=(1, 2))\n', (6487, 6510), True, 'import numpy as np\n'), ((6532, 6565), 'numpy.sum', 'np.sum', (['hist_mem_sat'], {'axis': '(1, 2)'}), '(hist_mem_sat, axis=(1, 2))\n', (6538, 6565), True, 'import numpy as np\n'), ((6587, 6620), 'numpy.sum', 'np.sum', (['hist_mem_cen'], {'axis': '(1, 2)'}), '(hist_mem_cen, axis=(1, 2))\n', (6593, 6620), True, 'import numpy as np\n'), ((3476, 3529), 'GCRCatalogs.load_catalog', 'GCRCatalogs.load_catalog', (["(catalog_name + '_redmapper')"], {}), "(catalog_name + '_redmapper')\n", (3500, 3529), False, 'import GCRCatalogs\n'), ((4349, 4375), 'GCR.GCRQuery', 'GCRQuery', (['"""r_host < r_vir"""'], {}), "('r_host < r_vir')\n", (4357, 4375), False, 'from GCR import GCRQuery\n'), ((4583, 4633), 'numpy.in1d', 'np.in1d', (["data['galaxy_id']", "redmapper['galaxy_id']"], {}), "(data['galaxy_id'], redmapper['galaxy_id'])\n", (4590, 4633), True, 'import numpy as np\n'), ((6052, 6076), 'pickle.dump', 'pickle.dump', (['red_seq', 'fp'], {}), '(red_seq, fp)\n', (6063, 6076), False, 'import pickle\n'), ((6133, 6177), 'os.path.join', 'os.path.join', (['output_dir', '"""red_sequence.png"""'], {}), "(output_dir, 'red_sequence.png')\n", (6145, 6177), False, 'import os\n'), ((4921, 4961), 'numpy.stack', 'np.stack', (["[data['redshift_true'], color]"], {}), "([data['redshift_true'], color])\n", (4929, 4961), True, 'import numpy as np\n'), ((5011, 5048), 'numpy.histogramdd', 'np.histogramdd', (['hdata[cen_mask]', 'bins'], {}), '(hdata[cen_mask], bins)\n', (5025, 5048), True, 'import numpy as np\n'), ((5087, 5124), 'numpy.histogramdd', 'np.histogramdd', (['hdata[sat_mask]', 'bins'], {}), '(hdata[sat_mask], bins)\n', (5101, 5124), True, 'import numpy as np\n'), ((5167, 5215), 'numpy.histogramdd', 'np.histogramdd', (['hdata[mem_mask & cen_mask]', 'bins'], {}), '(hdata[mem_mask & cen_mask], bins)\n', (5181, 5215), True, 'import numpy as np\n'), ((5258, 5306), 'numpy.histogramdd', 'np.histogramdd', (['hdata[mem_mask & sat_mask]', 'bins'], {}), '(hdata[mem_mask & sat_mask], bins)\n', (5272, 5306), True, 'import numpy as np\n')]
""" Calculate num history for chopped valid/test data... """ import argparse from distutils.util import strtobool import numpy as np import torch from pathlib import Path # from l5kit.dataset import AgentDataset # from torch.utils.data import DataLoader # from torch.utils.data.dataset import Subset # # from l5kit.data import LocalDataManager, ChunkedDataset import sys import os from tqdm import tqdm sys.path.append(os.pardir) sys.path.append(os.path.join(os.pardir, os.pardir)) from lib.functions.nll import pytorch_neg_multi_log_likelihood_batch # from lib.dataset.faster_agent_dataset import FasterAgentDataset # from lib.evaluation.mask import load_mask_chopped # from modeling.load_flag import Flags # from lib.rasterization.rasterizer_builder import build_custom_rasterizer # from lib.utils.yaml_utils import save_yaml, load_yaml def parse(): parser = argparse.ArgumentParser(description='') parser.add_argument('--pred_npz_path', '-p', default='results/tmp/eval_ema/pred.npz', help='pred.npz filepath') parser.add_argument('--debug', '-d', type=strtobool, default='false', help='Debug mode') parser.add_argument('--device', type=str, default='cuda:0', help='Device') args = parser.parse_args() return args if __name__ == '__main__': args = parse() debug = args.debug device = args.device # --- Load n_availability --- processed_dir = Path("../../input/processed_data") npz_path = processed_dir / f"n_history.npz" print(f"Load from {npz_path}") n_his = np.load(npz_path) n_his_avail_valid = n_his["n_his_avail_valid"] n_his_avail_test = n_his["n_his_avail_test"] # --- Load pred --- preds = np.load(args.pred_npz_path) coords = preds["coords"] confs = preds["confs"] targets = preds["targets"] target_availabilities = preds["target_availabilities"] # Evaluate loss errors = pytorch_neg_multi_log_likelihood_batch( torch.as_tensor(targets, device=device), torch.as_tensor(coords, device=device), torch.as_tensor(confs, device=device), torch.as_tensor(target_availabilities, device=device), reduction="none") print("errors", errors.shape, torch.mean(errors)) n_his_avail_valid = torch.as_tensor(n_his_avail_valid.astype(np.int64), device=device) for i in range(1, 11): this_error = errors[n_his_avail_valid == i] mean_error = torch.mean(this_error) print(f"i=={i:4.0f}: {mean_error:10.4f}, {len(this_error)}") for i in [20, 50, 100]: this_error = errors[n_his_avail_valid >= i] mean_error = torch.mean(this_error) print(f"i>={i:4.0f}: {mean_error:10.4f}, {len(this_error)}") import IPython; IPython.embed()
[ "torch.as_tensor", "argparse.ArgumentParser", "pathlib.Path", "torch.mean", "os.path.join", "IPython.embed", "numpy.load", "sys.path.append" ]
[((406, 432), 'sys.path.append', 'sys.path.append', (['os.pardir'], {}), '(os.pardir)\n', (421, 432), False, 'import sys\n'), ((449, 483), 'os.path.join', 'os.path.join', (['os.pardir', 'os.pardir'], {}), '(os.pardir, os.pardir)\n', (461, 483), False, 'import os\n'), ((870, 909), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '""""""'}), "(description='')\n", (893, 909), False, 'import argparse\n'), ((1468, 1502), 'pathlib.Path', 'Path', (['"""../../input/processed_data"""'], {}), "('../../input/processed_data')\n", (1472, 1502), False, 'from pathlib import Path\n'), ((1598, 1615), 'numpy.load', 'np.load', (['npz_path'], {}), '(npz_path)\n', (1605, 1615), True, 'import numpy as np\n'), ((1753, 1780), 'numpy.load', 'np.load', (['args.pred_npz_path'], {}), '(args.pred_npz_path)\n', (1760, 1780), True, 'import numpy as np\n'), ((2786, 2801), 'IPython.embed', 'IPython.embed', ([], {}), '()\n', (2799, 2801), False, 'import IPython\n'), ((2009, 2048), 'torch.as_tensor', 'torch.as_tensor', (['targets'], {'device': 'device'}), '(targets, device=device)\n', (2024, 2048), False, 'import torch\n'), ((2058, 2096), 'torch.as_tensor', 'torch.as_tensor', (['coords'], {'device': 'device'}), '(coords, device=device)\n', (2073, 2096), False, 'import torch\n'), ((2106, 2143), 'torch.as_tensor', 'torch.as_tensor', (['confs'], {'device': 'device'}), '(confs, device=device)\n', (2121, 2143), False, 'import torch\n'), ((2153, 2206), 'torch.as_tensor', 'torch.as_tensor', (['target_availabilities'], {'device': 'device'}), '(target_availabilities, device=device)\n', (2168, 2206), False, 'import torch\n'), ((2268, 2286), 'torch.mean', 'torch.mean', (['errors'], {}), '(errors)\n', (2278, 2286), False, 'import torch\n'), ((2480, 2502), 'torch.mean', 'torch.mean', (['this_error'], {}), '(this_error)\n', (2490, 2502), False, 'import torch\n'), ((2674, 2696), 'torch.mean', 'torch.mean', (['this_error'], {}), '(this_error)\n', (2684, 2696), False, 'import torch\n')]
import os import numpy as np import astrodash directoryPath = '/Users/dmuthukrishna/Documents/OzDES_data/ATEL_9742_Run26' atel9742 = [ ('DES16E1ciy_E1_combined_161101_v10_b00.dat', 0.174), ('DES16S1cps_S1_combined_161101_v10_b00.dat', 0.274), ('DES16E2crb_E2_combined_161102_v10_b00.dat', 0.229), ('DES16E2clk_E2_combined_161102_v10_b00.dat', 0.367), ('DES16E2cqq_E2_combined_161102_v10_b00.dat', 0.426), ('DES16X2ceg_X2_combined_161103_v10_b00.dat', 0.335), ('DES16X2bkr_X2_combined_161103_v10_b00.dat', 0.159), ('DES16X2crr_X2_combined_161103_v10_b00.dat', 0.312), ('DES16X2cpn_X2_combined_161103_v10_b00.dat', 0.28), ('DES16X2bvf_X2_combined_161103_v10_b00.dat', 0.135), ('DES16C1cbg_C1_combined_161103_v10_b00.dat', 0.111), ('DES16C2cbv_C2_combined_161103_v10_b00.dat', 0.109), ('DES16C1bnt_C1_combined_161103_v10_b00.dat', 0.351), ('DES16C3at_C3_combined_161031_v10_b00.dat', 0.217), ('DES16X3cpl_X3_combined_161031_v10_b00.dat', 0.205), ('DES16E2cjg_E2_combined_161102_v10_b00.dat', 0.48), ('DES16X2crt_X2_combined_161103_v10_b00.dat', 0.57)] filenames = [os.path.join(directoryPath, i[0]) for i in atel9742] knownRedshifts = [i[1] for i in atel9742] classification = astrodash.Classify(filenames, knownRedshifts) bestFits, bestTypes = classification.list_best_matches(n=1) print(bestFits) np.savetxt('Run26_fits.txt', bestFits, fmt='%s') # classification.plot_with_gui(indexToPlot=1)
[ "astrodash.Classify", "os.path.join", "numpy.savetxt" ]
[((1246, 1291), 'astrodash.Classify', 'astrodash.Classify', (['filenames', 'knownRedshifts'], {}), '(filenames, knownRedshifts)\n', (1264, 1291), False, 'import astrodash\n'), ((1368, 1416), 'numpy.savetxt', 'np.savetxt', (['"""Run26_fits.txt"""', 'bestFits'], {'fmt': '"""%s"""'}), "('Run26_fits.txt', bestFits, fmt='%s')\n", (1378, 1416), True, 'import numpy as np\n'), ((1133, 1166), 'os.path.join', 'os.path.join', (['directoryPath', 'i[0]'], {}), '(directoryPath, i[0])\n', (1145, 1166), False, 'import os\n')]
import numpy as np import sys import os from netCDF4 import Dataset zlev = 14 HALO = 2 TOP = "/data_ballantine02/miyoshi-t/honda/SCALE-LETKF/AIP_D4_VERIFY/DEBUG20200827/20200827090000" quick = False #quick = True def read_cz( fn="" ): nc = Dataset( fn, "r", format="NETCDF4" ) var = nc.variables["CZ"][HALO+zlev] nc.close() return( var ) def read_nc3d( fn="", nvar="QR" ): nc = Dataset( fn, "r", format="NETCDF4" ) var = nc.variables[nvar][:] #var = nc.variables[nvar][:] #[HALO:-HALO:2,HALO:-HALO:2,zmax] nc.close() return( var[HALO:-HALO:2,HALO:-HALO:2,zlev] ) def main( m=1 ): mm = str(m).zfill(4) if m == 0: mm = "mean" fn = os.path.join( TOP, "anal_sno_np00001/{0:}/anal.pe000000.nc".format( mm ) ) print( fn ) cz = read_cz( fn=fn ) qr = read_nc3d( fn=fn, nvar="QR" ) qs = read_nc3d( fn=fn, nvar="QS" ) qg = read_nc3d( fn=fn, nvar="QG" ) rho = read_nc3d( fn=fn, nvar="DENS" ) dbz = q2dbz( qr, qs, qg, rho ) print( cz ) levs = np.arange( 5, 60, 5 ) import matplotlib.pyplot as plt fig, (ax1) = plt.subplots(1, 1, figsize=(6,6) ) fig.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.93, ) ax1.set_aspect('equal') cmap = plt.cm.get_cmap("jet") SHADE = ax1.contourf( dbz, levels=levs, cmap=cmap, extend='max' ) pos = ax1.get_position() cb_h = pos.height ax_cb = fig.add_axes( [pos.x1+0.005, pos.y0, 0.01, cb_h] ) cb = plt.colorbar( SHADE, cax=ax_cb, ) tit = "Reflectivity (dBZ), mem:{0:}, Z={1:.1f}km".format( mm, cz/1000.0 ) fig.suptitle( tit, fontsize=14 ) ofig = "{0:}".format( mm ) if quick: plt.show() else: odir = "png/2d_map_all" os.makedirs( odir, exist_ok=True) plt.savefig( os.path.join(odir, ofig), bbox_inches="tight", pad_inches = 0.1) plt.clf() plt.close('all') def q2dbz( qr, qs, qg, rho ): qrp = qr qsp = qs qgp = qg zr = 2.53e4 * np.power( rho*qrp*1.e3, 1.84 ) zs = 3.48e3 * np.power( rho*qsp*1.e3, 1.66 ) zg = 5.54e3 * np.power( rho*qgp*1.e3, 1.7 ) ref = zr + zs + zg return( np.where( ref > 0.0, 10*np.log10( zr + zs + zg ), 0.0 ) ) for m in range( 51 ): main( m=m )
[ "numpy.log10", "os.makedirs", "numpy.power", "netCDF4.Dataset", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.clf", "os.path.join", "matplotlib.pyplot.close", "matplotlib.pyplot.cm.get_cmap", "matplotlib.pyplot.subplots", "numpy.arange", "matplotlib.pyplot.show" ]
[((249, 283), 'netCDF4.Dataset', 'Dataset', (['fn', '"""r"""'], {'format': '"""NETCDF4"""'}), "(fn, 'r', format='NETCDF4')\n", (256, 283), False, 'from netCDF4 import Dataset\n'), ((405, 439), 'netCDF4.Dataset', 'Dataset', (['fn', '"""r"""'], {'format': '"""NETCDF4"""'}), "(fn, 'r', format='NETCDF4')\n", (412, 439), False, 'from netCDF4 import Dataset\n'), ((1041, 1060), 'numpy.arange', 'np.arange', (['(5)', '(60)', '(5)'], {}), '(5, 60, 5)\n', (1050, 1060), True, 'import numpy as np\n'), ((1118, 1152), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(6, 6)'}), '(1, 1, figsize=(6, 6))\n', (1130, 1152), True, 'import matplotlib.pyplot as plt\n'), ((1266, 1288), 'matplotlib.pyplot.cm.get_cmap', 'plt.cm.get_cmap', (['"""jet"""'], {}), "('jet')\n", (1281, 1288), True, 'import matplotlib.pyplot as plt\n'), ((1509, 1539), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['SHADE'], {'cax': 'ax_cb'}), '(SHADE, cax=ax_cb)\n', (1521, 1539), True, 'import matplotlib.pyplot as plt\n'), ((1714, 1724), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1722, 1724), True, 'import matplotlib.pyplot as plt\n'), ((1773, 1805), 'os.makedirs', 'os.makedirs', (['odir'], {'exist_ok': '(True)'}), '(odir, exist_ok=True)\n', (1784, 1805), False, 'import os\n'), ((1919, 1928), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1926, 1928), True, 'import matplotlib.pyplot as plt\n'), ((1936, 1952), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (1945, 1952), True, 'import matplotlib.pyplot as plt\n'), ((2043, 2077), 'numpy.power', 'np.power', (['(rho * qrp * 1000.0)', '(1.84)'], {}), '(rho * qrp * 1000.0, 1.84)\n', (2051, 2077), True, 'import numpy as np\n'), ((2092, 2126), 'numpy.power', 'np.power', (['(rho * qsp * 1000.0)', '(1.66)'], {}), '(rho * qsp * 1000.0, 1.66)\n', (2100, 2126), True, 'import numpy as np\n'), ((2141, 2174), 'numpy.power', 'np.power', (['(rho * qgp * 1000.0)', '(1.7)'], {}), '(rho * qgp * 1000.0, 1.7)\n', (2149, 2174), True, 'import numpy as np\n'), ((1827, 1851), 'os.path.join', 'os.path.join', (['odir', 'ofig'], {}), '(odir, ofig)\n', (1839, 1851), False, 'import os\n'), ((2232, 2254), 'numpy.log10', 'np.log10', (['(zr + zs + zg)'], {}), '(zr + zs + zg)\n', (2240, 2254), True, 'import numpy as np\n')]
try: import numpy as _np from math import sqrt as _sqrt, pi as _pi, exp as _exp from typing import Union, Dict, List from univariate._base import Infinite except Exception as e: print(f"some modules are missing {e}") class Logistic(Infinite): """ This class contains methods concerning Logistic Distirbution [#]_. .. math:: \\text{Logistic}(x;\\mu,s) = \\frac{\\exp{(-(x-\\mu)/s)}} {s(1+\\exp(-(x-\\mu)/s)^2)} Args: location(float): location parameter (:math:`\\mu`) scale(float): scale parameter (:math:`s`) x > 0 x(float): random variable Reference: .. [#] Wikipedia contributors. (2020, December 12). Logistic distribution. https://en.wikipedia.org/w/index.php?title=Logistic_distribution&oldid=993793195 """ def __init__(self, location: float, scale: float): if scale < 0: raise ValueError('scale should be greater than 0.') self.scale = scale self.location = location def pdf(self, x: Union[List[float], _np.ndarray, float]) -> Union[float, _np.ndarray]: """ Args: x (Union[List[float], numpy.ndarray, float]): random variable(s) Returns: Union[float, numpy.ndarray]: evaluation of pdf at x """ mu = self.location s = self.scale if isinstance(x, (_np.ndarray, List)): if not type(x) is _np.ndarray: x = _np.array(x) return _np.exp(-(x - mu) / s) / (s * (1 + _np.exp(-(x - mu) / s))**2) return _exp(-(x - mu) / s) / (s * (1 + _exp(-(x - mu) / s))**2) def cdf(self, x: Union[List[float], _np.ndarray, float]) -> Union[float, _np.ndarray]: """ Args: x (Union[List[float], numpy.ndarray, float]): data point(s) of interest Returns: Union[float, numpy.ndarray]: evaluation of cdf at x """ mu = self.location s = self.scale if isinstance(x, (_np.ndarray, List)): x = _np.array(x) return 1 / (1 + _np.exp(-(x - mu) / s)) return 1 / (1 + _exp(-(x - mu) / s)) def mean(self) -> float: """ Returns: Mean of the Logistic distribution. """ return self.location def median(self) -> float: """ Returns: Median of the Logistic distribution. """ return self.location def mode(self) -> float: """ Returns: Mode of the Logistic distribution. """ return self.location def var(self) -> float: """ Returns: Variance of the Logistic distribution. """ return pow(self.scale, 2) * pow(_pi, 2)/3 def std(self) -> float: """ Returns: Standard deviation of the Logistic distribution. """ return _sqrt(self.var()) def skewness(self) -> float: """ Returns: Skewness of the Logistic distribution. """ return 0.0 def kurtosis(self) -> float: """ Returns: Kurtosis of the Logistic distribution. """ return 6 / 5 def entropy(self) -> float: """ Returns: differential entropy of the Logistic distribution. Reference: <NAME>. & <NAME>.(2009). Maximum entropy autoregressive conditional heteroskedasticity model. Elsivier. link: http://wise.xmu.edu.cn/uploadfiles/paper-masterdownload/2009519932327055475115776.pdf """ return 2.0 def summary(self) -> Dict[str, Union[float, str]]: """ Returns: Dictionary of Logistic distirbution moments. This includes standard deviation. """ return { 'mean': self.mean(), 'median': self.median(), 'mode': self.mode(), 'var': self.var(), 'std': self.std(), 'skewness': self.skewness(), 'kurtosis': self.kurtosis() }
[ "numpy.exp", "numpy.array", "math.exp" ]
[((1614, 1633), 'math.exp', '_exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (1618, 1633), True, 'from math import sqrt as _sqrt, pi as _pi, exp as _exp\n'), ((2095, 2107), 'numpy.array', '_np.array', (['x'], {}), '(x)\n', (2104, 2107), True, 'import numpy as _np\n'), ((1502, 1514), 'numpy.array', '_np.array', (['x'], {}), '(x)\n', (1511, 1514), True, 'import numpy as _np\n'), ((1535, 1557), 'numpy.exp', '_np.exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (1542, 1557), True, 'import numpy as _np\n'), ((2186, 2205), 'math.exp', '_exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (2190, 2205), True, 'from math import sqrt as _sqrt, pi as _pi, exp as _exp\n'), ((2137, 2159), 'numpy.exp', '_np.exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (2144, 2159), True, 'import numpy as _np\n'), ((1646, 1665), 'math.exp', '_exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (1650, 1665), True, 'from math import sqrt as _sqrt, pi as _pi, exp as _exp\n'), ((1570, 1592), 'numpy.exp', '_np.exp', (['(-(x - mu) / s)'], {}), '(-(x - mu) / s)\n', (1577, 1592), True, 'import numpy as _np\n')]
import torch import pandas as pd import numpy as np import pickle as pkl import yaml import cv2 from io import BytesIO from .utils import make_detections_from_segmentation from .datasets_cfg import make_urdf_dataset from pathlib import Path import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') class SyntheticSceneDataset: def __init__(self, ds_dir, train=True): self.ds_dir = Path(ds_dir) assert self.ds_dir.exists() keys_path = ds_dir / (('train' if train else 'val') + '_keys.pkl') keys = pkl.loads(keys_path.read_bytes()) self.cfg = yaml.load((ds_dir / 'config.yaml').read_text(), Loader=yaml.FullLoader) self.object_set = self.cfg.scene_kwargs['urdf_ds'] self.keys = keys urdf_ds_name = self.cfg.scene_kwargs['urdf_ds'] urdf_ds = make_urdf_dataset(urdf_ds_name) self.all_labels = [obj['label'] for _, obj in urdf_ds.index.iterrows()] self.frame_index = pd.DataFrame(dict(scene_id=np.arange(len(keys)), view_id=np.arange(len(keys)))) def __len__(self): return len(self.frame_index) @staticmethod def _deserialize_im_cv2(im_buf, rgb=True): stream = BytesIO(im_buf) stream.seek(0) file_bytes = np.asarray(bytearray(stream.read()), dtype=np.uint8) if rgb: im = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) im = im[..., [2, 1, 0]] else: im = cv2.imdecode(file_bytes, cv2.IMREAD_UNCHANGED).astype(np.uint8) return torch.as_tensor(im) def __getitem__(self, idx): key = self.keys[idx] pkl_path = (self.ds_dir / 'dumps' / key).with_suffix('.pkl') dic = pkl.loads(pkl_path.read_bytes()) cam = dic['camera'] rgb = self._deserialize_im_cv2(cam['rgb']) mask = self._deserialize_im_cv2(cam['mask'], rgb=False) cam = {k: v for k, v in cam.items() if k not in {'rgb', 'mask'}} objects = dic['objects'] dets_gt = make_detections_from_segmentation(torch.as_tensor(mask).unsqueeze(0))[0] mask_uniqs = set(np.unique(mask[mask > 0])) for obj in objects: if obj['id_in_segm'] in mask_uniqs: obj['bbox'] = dets_gt[obj['id_in_segm']].numpy() state = dict(camera=cam, objects=objects, frame_info=self.frame_index.iloc[idx].to_dict()) return rgb, mask, state
[ "torch.as_tensor", "numpy.unique", "pathlib.Path", "io.BytesIO", "cv2.imdecode", "torch.multiprocessing.set_sharing_strategy" ]
[((270, 327), 'torch.multiprocessing.set_sharing_strategy', 'torch.multiprocessing.set_sharing_strategy', (['"""file_system"""'], {}), "('file_system')\n", (312, 327), False, 'import torch\n'), ((425, 437), 'pathlib.Path', 'Path', (['ds_dir'], {}), '(ds_dir)\n', (429, 437), False, 'from pathlib import Path\n'), ((1212, 1227), 'io.BytesIO', 'BytesIO', (['im_buf'], {}), '(im_buf)\n', (1219, 1227), False, 'from io import BytesIO\n'), ((1547, 1566), 'torch.as_tensor', 'torch.as_tensor', (['im'], {}), '(im)\n', (1562, 1566), False, 'import torch\n'), ((1358, 1400), 'cv2.imdecode', 'cv2.imdecode', (['file_bytes', 'cv2.IMREAD_COLOR'], {}), '(file_bytes, cv2.IMREAD_COLOR)\n', (1370, 1400), False, 'import cv2\n'), ((2111, 2136), 'numpy.unique', 'np.unique', (['mask[mask > 0]'], {}), '(mask[mask > 0])\n', (2120, 2136), True, 'import numpy as np\n'), ((1468, 1514), 'cv2.imdecode', 'cv2.imdecode', (['file_bytes', 'cv2.IMREAD_UNCHANGED'], {}), '(file_bytes, cv2.IMREAD_UNCHANGED)\n', (1480, 1514), False, 'import cv2\n'), ((2047, 2068), 'torch.as_tensor', 'torch.as_tensor', (['mask'], {}), '(mask)\n', (2062, 2068), False, 'import torch\n')]
import libjevois as jevois import cv2 import numpy as np import math import time import re from datetime import datetime ## Module used to detect Power Cube (Rectangular Prism) using Jevois # # By default, we get the next video frame from the camera as an OpenCV BGR (color) image named 'inimg'. # We then apply some image processing to it to create an output BGR image named 'outimg'. # We finally add some text drawings to outimg and send it to host over USB. # # # @videomapping YUYV 352 288 30.0 YUYV 352 288 30.0 JeVois RectangleDetector # @email <EMAIL> # @address University of Southern California, HNB-07A, 3641 Watt Way, Los Angeles, CA 90089-2520, USA # @copyright Copyright (C) 2017 by <NAME>, iLab and the University of Southern California # @mainurl http://jevois.org # @supporturl http://jevois.org/doc # @otherurl http://iLab.usc.edu # @license GPL v3 # @distribution Unrestricted # @restrictions None # @ingroup modules class RectangleDetector: # ################################################################################################### ## Constructor def __init__(self): # Instantiate a JeVois Timer to measure our processing framerate: self.timer = jevois.Timer("sandbox", 25, jevois.LOG_DEBUG) #A bunch of standard init stuff self.prevlcent=0 self.prevrcent=0 self.resetcounter=0 self.frame=0 self.framerate_fps=0 self.CPULoad_pct=0 self.CPUTemp_C=0 self.pipelineDelay_us=0 self.pattern = re.compile('([0-9]*\.[0-9]+|[0-9]+) fps, ([0-9]*\.[0-9]+|[0-9]+)% CPU, ([0-9]*\.[0-9]+|[0-9]+)C,') #The real world points of our object with (0,0,0) being the centerpoint of the line connecting the two closest points self.ObjPoints=np.array([(0,-5.3771,-5.3248), (0,-7.3134,-4.8241), (0,-5.9363,0.5008), (0,-4.0000,0), (0,5.3771,-5.3248), (0,4.0000,0), (0,5.9363,0.5008), (0,7.3134,-4.8241) ],dtype=np.float64) # ################################################################################################### ## Process function without USB output def processNoUSB(self, inframe): #Keeps camera from doing unnecesary drawings self.streamCheck=False #Runs main code self.processCommon(inframe,None) # ################################################################################################### ## Process function with USB output def process(self, inframe, outframe): #Camera will draw rectangles and other debugging stuff on image self.streamCheck=True #Runs main code self.processCommon(inframe,outframe) # ################################################################################################### ## Main Task def processCommon(self, inframe, outframe): #Init stuff self.InitFunction(inframe) #Calibrates Camera self.loadCameraCalibration() #Filters image based on predefined filters self.LightFilter() #Finds contours contours=self.findcontours(self.mask) #Filters contours based on width and area filteredContours = self.filtercontours(contours, 100.0, 30.0) #Detects target, will eventually return translation and rotation vector self.TargetDetection(filteredContours) #Data Tracking Stuff self.DataTracker() #sends output over serial jevois.sendSerial("{{{},{},{},{},{},{},{},{},{},{}}}\n".format(self.ret,self.yaw,self.xval,self.yval,self.resetcounter,self.framerate_fps,self.CPULoad_pct,self.CPUTemp_C,self.pipelineDelay_us,self.angle)) #Sends maskoutput if streaming if (self.streamCheck): outframe.sendCvRGB(self.maskoutput) #Methods @staticmethod def findcontours(input): contours, hierarchy =cv2.findContours(input, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE) return contours @staticmethod def filtercontours(input_contours, min_area, min_width,): output = [] for contour in input_contours: x,y,w,h = cv2.boundingRect(contour) if (w < min_width or w>600): continue area = cv2.contourArea(contour) if (area < min_area): continue output.append(contour) return output def InitFunction(self,inframe): #Starts Jevois Timer self.timer.start() #Gets the frame from the jevois camera in RGB format self.inimg = inframe.getCvRGB() #Starts timer self.pipeline_start_time = datetime.now() #Counts our frames self.frame+=1 #Measures height and width of image self.h, self.w, __ = self.inimg.shape def LightFilter(self): #Sets image to hsv colors hsv = cv2.cvtColor(self.inimg, cv2.COLOR_RGB2HSV) #Defines hsv values of targets lowerBrightness = np.array([50,0,75]) upperBrightness = np.array([100,200,255]) #Creates mask based on hsv range self.mask = cv2.inRange(hsv, lowerBrightness, upperBrightness) #Makes an image using the mask if streaming if self.streamCheck: self.maskoutput = cv2.cvtColor(self.mask, cv2.COLOR_GRAY2BGR) def loadCameraCalibration(self): cpf = "/jevois/share/camera/calibration{}x{}.yaml".format(self.w, self.h) fs = cv2.FileStorage(cpf, cv2.FILE_STORAGE_READ) if (fs.isOpened()): self.camMatrix = fs.getNode("camera_matrix").mat() self.distCoeffs = fs.getNode("distortion_coefficients").mat() else: jevois.LFATAL("Failed to read camera parameters from file [{}]".format(cpf)) def DataTracker(self): #Tracks Processing Time self.pipelineDelay_us = (datetime.now() - self.pipeline_start_time).microseconds #Tracks Framerate and some significantly less important values results = self.pattern.match(self.timer.stop()) if(results is not None): self.framerate_fps = results.group(1) self.CPULoad_pct = results.group(2) self.CPUTemp_C = results.group(3) def TargetDetection(self,contourinput): #Initializes a bunch of values that we mess with later pair=0 potentialltarget=[] potentiallrect=[] potentialrtarget=[] potentialrrect=[] self.ret="F" self.yaw=0 self.xval=0 self.yval=0 self.angle=0 PairingHighScore=999999.0 #ANGLE FILTERING for i, contour in enumerate(contourinput): #Reads Angles rect=cv2.minAreaRect(contour) angle=rect[2] box = cv2.boxPoints(rect) box = np.int0(box) #Matches Angles to Respective Targets, draws Red, Blue, and Green for left, right, and no match respectively if (angle<=-55.0 and angle>=-80.0): potentialltarget.append(i) potentiallrect.append(rect[0]) if self.streamCheck: cv2.drawContours(self.maskoutput,[box],0,(255,0,0),2) elif (angle<=-5.0 and angle>=-30.0): potentialrtarget.append(i) potentialrrect.append(rect[0]) if self.streamCheck: cv2.drawContours(self.maskoutput,[box],0,(0,0,255),2) elif self.streamCheck: cv2.drawContours(self.maskoutput,[box],0,(0,255,0),2) #PAIRING ALGORITHM for i, ltarget in enumerate(potentialltarget): for j, rtarget in enumerate(potentialrtarget): #Reads center points and checks only for matches where left is further to the left lcent=potentiallrect[i] rcent=potentialrrect[j] if (lcent[0]<=rcent[0]): #Prepares to score pairs, calculates height difference of targets, how close they are to center, and how close to eachother PairingScore=0 CenterHeightDistance=abs(lcent[1]-rcent[1]) CenterPoint=abs((lcent[0]+rcent[0])-1280) TargetDistance=abs(rcent[0]-lcent[0]) #Checks if their was a previous value if((self.prevlcent)!=0): xchange=abs(lcent[0]-self.prevlcent[0])+abs(rcent[0]-self.prevrcent[0]) ychange=abs(lcent[1]-self.prevlcent[1])+abs(rcent[1]-self.prevrcent[1]) PairingScore=CenterPoint+TargetDistance+CenterHeightDistance+xchange+ychange else: PairingScore=CenterPoint+TargetDistance+CenterHeightDistance #Adds Best Score to the List if (PairingScore<=PairingHighScore): PairingHighScore=PairingScore pair=[ltarget,rtarget] #MATH AND STUFF if (pair!=0): #Gets targets Centroids lcoordflt=cv2.minAreaRect(contourinput[pair[0]])[0] rcoordflt=cv2.minAreaRect(contourinput[pair[1]])[0] #Draws line between pairs if streaming if self.streamCheck: lcoord=(int(lcoordflt[0]),int(lcoordflt[1])) rcoord=(int(rcoordflt[0]),int(rcoordflt[1])) cv2.line(self.maskoutput,lcoord,rcoord,(255,0,0),2) #Records Centroid for next time self.prevlcent=lcoordflt self.prevrcent=rcoordflt #Gets bottom, leftmost, topmost, and rightmost points of each contour coords2d=[] for contour in pair: cnt=contourinput[contour] coords2d.append(tuple(cnt[cnt[:,:,1].argmax()][0])) coords2d.append(tuple(cnt[cnt[:,:,0].argmin()][0])) coords2d.append(tuple(cnt[cnt[:,:,1].argmin()][0])) coords2d.append(tuple(cnt[cnt[:,:,0].argmax()][0])) ImgPoints=np.array([coords2d[0],coords2d[1],coords2d[2],coords2d[3],coords2d[4],coords2d[5],coords2d[6],coords2d[7]], dtype="double") #Actual Pnp algorithm, takes the points we calculated along with predefined points of target __, rvec, tvec = cv2.solvePnP(self.ObjPoints,ImgPoints,self.camMatrix,self.distCoeffs) #Chooses the values we need for path planning self.angle=(((lcoordflt[0]+rcoordflt[0])/2)-640)/20 self.ret="T" self.yaw=(str(rvec[2]).strip('[]')) self.xval=(str(tvec[2]).strip('[]')) self.yval=(str(tvec[1]).strip('[]')) def parseSerial(self, str): jevois.LINFO("parseserial received command [{}]".format(str)) #Command to reset previous target if str == "latch": self.prevlcent=0 self.prevrcent=0 self.resetcounter+=1 return "Reset Completed" return "ERR Unsupported command"
[ "cv2.drawContours", "cv2.boxPoints", "re.compile", "cv2.inRange", "cv2.line", "numpy.int0", "cv2.FileStorage", "cv2.contourArea", "cv2.minAreaRect", "numpy.array", "datetime.datetime.now", "cv2.solvePnP", "cv2.cvtColor", "cv2.findContours", "libjevois.Timer", "cv2.boundingRect" ]
[((1256, 1301), 'libjevois.Timer', 'jevois.Timer', (['"""sandbox"""', '(25)', 'jevois.LOG_DEBUG'], {}), "('sandbox', 25, jevois.LOG_DEBUG)\n", (1268, 1301), True, 'import libjevois as jevois\n'), ((1597, 1708), 're.compile', 're.compile', (['"""([0-9]*\\\\.[0-9]+|[0-9]+) fps, ([0-9]*\\\\.[0-9]+|[0-9]+)% CPU, ([0-9]*\\\\.[0-9]+|[0-9]+)C,"""'], {}), "(\n '([0-9]*\\\\.[0-9]+|[0-9]+) fps, ([0-9]*\\\\.[0-9]+|[0-9]+)% CPU, ([0-9]*\\\\.[0-9]+|[0-9]+)C,'\n )\n", (1607, 1708), False, 'import re\n'), ((1857, 2054), 'numpy.array', 'np.array', (['[(0, -5.3771, -5.3248), (0, -7.3134, -4.8241), (0, -5.9363, 0.5008), (0, -\n 4.0, 0), (0, 5.3771, -5.3248), (0, 4.0, 0), (0, 5.9363, 0.5008), (0, \n 7.3134, -4.8241)]'], {'dtype': 'np.float64'}), '([(0, -5.3771, -5.3248), (0, -7.3134, -4.8241), (0, -5.9363, 0.5008\n ), (0, -4.0, 0), (0, 5.3771, -5.3248), (0, 4.0, 0), (0, 5.9363, 0.5008),\n (0, 7.3134, -4.8241)], dtype=np.float64)\n', (1865, 2054), True, 'import numpy as np\n'), ((4411, 4486), 'cv2.findContours', 'cv2.findContours', (['input'], {'mode': 'cv2.RETR_LIST', 'method': 'cv2.CHAIN_APPROX_SIMPLE'}), '(input, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE)\n', (4427, 4486), False, 'import cv2\n'), ((5236, 5250), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5248, 5250), False, 'from datetime import datetime\n'), ((5496, 5539), 'cv2.cvtColor', 'cv2.cvtColor', (['self.inimg', 'cv2.COLOR_RGB2HSV'], {}), '(self.inimg, cv2.COLOR_RGB2HSV)\n', (5508, 5539), False, 'import cv2\n'), ((5617, 5638), 'numpy.array', 'np.array', (['[50, 0, 75]'], {}), '([50, 0, 75])\n', (5625, 5638), True, 'import numpy as np\n'), ((5664, 5689), 'numpy.array', 'np.array', (['[100, 200, 255]'], {}), '([100, 200, 255])\n', (5672, 5689), True, 'import numpy as np\n'), ((5761, 5811), 'cv2.inRange', 'cv2.inRange', (['hsv', 'lowerBrightness', 'upperBrightness'], {}), '(hsv, lowerBrightness, upperBrightness)\n', (5772, 5811), False, 'import cv2\n'), ((6119, 6162), 'cv2.FileStorage', 'cv2.FileStorage', (['cpf', 'cv2.FILE_STORAGE_READ'], {}), '(cpf, cv2.FILE_STORAGE_READ)\n', (6134, 6162), False, 'import cv2\n'), ((4682, 4707), 'cv2.boundingRect', 'cv2.boundingRect', (['contour'], {}), '(contour)\n', (4698, 4707), False, 'import cv2\n'), ((4796, 4820), 'cv2.contourArea', 'cv2.contourArea', (['contour'], {}), '(contour)\n', (4811, 4820), False, 'import cv2\n'), ((5936, 5979), 'cv2.cvtColor', 'cv2.cvtColor', (['self.mask', 'cv2.COLOR_GRAY2BGR'], {}), '(self.mask, cv2.COLOR_GRAY2BGR)\n', (5948, 5979), False, 'import cv2\n'), ((7470, 7494), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contour'], {}), '(contour)\n', (7485, 7494), False, 'import cv2\n'), ((7541, 7560), 'cv2.boxPoints', 'cv2.boxPoints', (['rect'], {}), '(rect)\n', (7554, 7560), False, 'import cv2\n'), ((7580, 7592), 'numpy.int0', 'np.int0', (['box'], {}), '(box)\n', (7587, 7592), True, 'import numpy as np\n'), ((11137, 11271), 'numpy.array', 'np.array', (['[coords2d[0], coords2d[1], coords2d[2], coords2d[3], coords2d[4], coords2d[\n 5], coords2d[6], coords2d[7]]'], {'dtype': '"""double"""'}), "([coords2d[0], coords2d[1], coords2d[2], coords2d[3], coords2d[4],\n coords2d[5], coords2d[6], coords2d[7]], dtype='double')\n", (11145, 11271), True, 'import numpy as np\n'), ((11411, 11483), 'cv2.solvePnP', 'cv2.solvePnP', (['self.ObjPoints', 'ImgPoints', 'self.camMatrix', 'self.distCoeffs'], {}), '(self.ObjPoints, ImgPoints, self.camMatrix, self.distCoeffs)\n', (11423, 11483), False, 'import cv2\n'), ((6535, 6549), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (6547, 6549), False, 'from datetime import datetime\n'), ((10100, 10138), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contourinput[pair[0]]'], {}), '(contourinput[pair[0]])\n', (10115, 10138), False, 'import cv2\n'), ((10165, 10203), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contourinput[pair[1]]'], {}), '(contourinput[pair[1]])\n', (10180, 10203), False, 'import cv2\n'), ((10448, 10505), 'cv2.line', 'cv2.line', (['self.maskoutput', 'lcoord', 'rcoord', '(255, 0, 0)', '(2)'], {}), '(self.maskoutput, lcoord, rcoord, (255, 0, 0), 2)\n', (10456, 10505), False, 'import cv2\n'), ((7929, 7988), 'cv2.drawContours', 'cv2.drawContours', (['self.maskoutput', '[box]', '(0)', '(255, 0, 0)', '(2)'], {}), '(self.maskoutput, [box], 0, (255, 0, 0), 2)\n', (7945, 7988), False, 'import cv2\n'), ((8206, 8265), 'cv2.drawContours', 'cv2.drawContours', (['self.maskoutput', '[box]', '(0)', '(0, 0, 255)', '(2)'], {}), '(self.maskoutput, [box], 0, (0, 0, 255), 2)\n', (8222, 8265), False, 'import cv2\n'), ((8335, 8394), 'cv2.drawContours', 'cv2.drawContours', (['self.maskoutput', '[box]', '(0)', '(0, 255, 0)', '(2)'], {}), '(self.maskoutput, [box], 0, (0, 255, 0), 2)\n', (8351, 8394), False, 'import cv2\n')]
import qutip as qt import numpy as np import scipy from scipy import constants from scipy.linalg import expm, sinm, cosm import itertools import matplotlib.pyplot as plt pi = np.pi e = constants.e h = constants.h hbar = constants.hbar ep0 = constants.epsilon_0 mu0 = constants.mu_0 Phi0 = h/(2*e) kb = constants.Boltzmann def ket(Nq, i): return qt.basis(Nq, i) def ket_2Qsys(i, j, Nq1, Nq2): a = ket(Nq1, i) b = ket(Nq2, j) return qt.tensor(a, b) def ket_3Qsys(i, j, k, Nq1, Nq2, Nqc): a = ket(Nq1, i) b = ket(Nq2, j) c = ket(Nqc, k) return qt.tensor(a, b, c) def Bose_distributon(f, T): f = f * 1e9 if T==0: res = 0 else: res = ( np.exp(h*f/(kb*T)) - 1 )**(-1) return res def Maxwell_Boltzmann_distributon(fs, T, N): if N < 1: print('N should be >=1') # f1 = fs[1] * 1e9 # a = np.exp(-f1*h/(kb*T)) Z = 0 for i in range(len(fs[0:N])): fi = fs[i] * 1e9 Z = Z + np.exp(-fi*h/(kb*T)) pops = [np.exp(-fs[i]*1e9*h/(kb*T))/Z for i in range(len(fs[0:N]))] return pops ######### N-level paulis ######### def pI_N(Nq): return ket(Nq, 0) * ket(Nq, 0).dag() + ket(Nq, 1) * ket(Nq, 1).dag() def pX_N(Nq): return ket(Nq, 0) * ket(Nq, 1).dag() + ket(Nq, 1) * ket(Nq, 0).dag() def pY_N(Nq): return 1j*ket(Nq, 0) * ket(Nq, 1).dag() - 1j*ket(Nq, 1) * ket(Nq, 0).dag() def pZ_N(Nq): return ket(Nq, 0) * ket(Nq, 0).dag() - ket(Nq, 1) * ket(Nq, 1).dag() def Rarb(p:list, Nq): SX, SY, SZ = pX_N(Nq), pY_N(Nq), pZ_N(Nq) return ( -1j*(p[0]*SX + p[1]*SY + p[2]*SZ)/2 ).expm() def Rarb2Q(p:list, Nq): R1 = Rarb(p[0:3], Nq) R2 = Rarb(p[3:6], Nq) res = qt.tensor(R1, R2) return res def iniState1Qsys(Nq:int, s:int, mode='ket'): q1 = ket(Nq, s) psi0 = q1 if mode == 'rho': ini = psi0*psi0.dag() else: ini = psi0 return ini def iniState1Q1Rsys(Nq:int, Nf:int, s:int, t:int, mode='ket'): q1 = ket(Nq, s) r1 = qt.fock(Nf, t) psi0 = qt.tensor(q1, r1) if mode == 'rho': ini = psi0*psi0.dag() else: ini = psi0 return ini def iniState2Qsys(Nq1:int, Nq2:int, s1:int, s2:int, mode='ket'): q1 = ket(Nq1, s1) q2 = ket(Nq2, s2) psi0 = qt.tensor(q1, q2) if mode == 'rho': ini = psi0*psi0.dag() else: ini = psi0 return ini class transmon(): def __init__(self, EC=10, EJ=0.3, f01=None, alpha=None, N=10, Nq=3, Temp=20e-3): # Unit in [GHz] if f01 is None and alpha is None: self.EC = EC self.EJ = EJ self.N = N self.enes = self.calcChargeQubitLevels(self.EC, self.EJ, self.N) self.f01 = self.enes[1] self.anh = self.enes[2] - 2*self.enes[1] else: self.f01 = f01 self.anh = - abs(alpha) self.enes = [0] + [i*self.f01 + (i-1)*self.anh for i in range(1, N)] self.nth_q = Maxwell_Boltzmann_distributon(self.enes, Temp, N) self.P0 = iniState1Qsys(Nq, 0, mode='rho') self.P1 = iniState1Qsys(Nq, 1, mode='rho') # Thermal_state_ket = 0 # for i in range(Nq): # Thermal_state_ket += ket(Nq, i)*self.nth_q[i] # self.Thermal_state_ket = Thermal_state_ket # self.Thermal_state_dm = self.Thermal_state_ket*self.Thermal_state_ket.dag() self.Thermal_state_dm = qt.thermal_dm(Nq, self.nth_q[1]) if Nq != None: self.Q_duffingOscillator(Nq) def chargeQubitHamilonian(self, Ec, Ej, N, ng): """ Return the charge qubit hamiltonian as a Qobj instance. Parameters ---------- Ec : float unit is [GHz] Ej : float unit is [GHz] N : int Difference in the number of Cooper pairs ng : float: Voltage bias for Charge qubit. Returns ------- qobj of Charge qubit hamiltonian. """ m = np.diag(4 * Ec * (np.arange(-N,N+1)-ng)**2) + 0.5 * Ej * (np.diag(-np.ones(2*N), 1) + np.diag(-np.ones(2*N), -1)) return qt.Qobj(m) def Q_duffingOscillator(self, Nq=5): self.Nq = Nq Iq = qt.qeye(Nq) b = qt.destroy(Nq) nb = b.dag()*b self.X = pX_N(Nq) self.Y = pY_N(Nq) self.Z = pZ_N(Nq) self.Iq = Iq self.nb = nb self.b = b q1_lab = self.f01 * nb + 0.5 * self.anh * nb * (nb - Iq) self.Hqlab = q1_lab return q1_lab def calcChargeQubitLevels(self, EC, EJ, N): """ Return the list of charge qubit eigen energy at flux optimal point. Parameters ---------- Ec : float unit is [GHz] Ej : float unit is [GHz] N : int Difference in the number of Cooper pairs Returns ------- list of eigenenergies. """ ng_vec = [0] ene = np.array([self.chargeQubitHamilonian(EC, EJ, N, ng).eigenenergies() for ng in ng_vec]) return [ene[0][i] - ene[0][0] for i in range(len(ene[0])) ] class resonator(): def __init__(self, fr, Qc, Nf=5, Temp=20e-3): self.fr = fr self.Nf = Nf self.Qc = Qc self.a = qt.destroy(Nf) self.ad = self.a.dag() self.na = self.ad * self.a self.Hr = fr * self.na self.Ir = qt.qeye(Nf) self.kappa = fr/Qc self.nth_a = Bose_distributon(fr, Temp) self.Thermal_state_dm = qt.thermal_dm(Nf, self.nth_a) class QR(): def __init__(self, Q, fr, g): # Unit in [GHz] self.fr = fr self.g = g self.Q = Q self.detuning = Q.f01 - fr self.thermal_photon = qt.utilities.n_thermal(fr, Q.f01) self.f01_dressed = Q.f01 + ( 2 * (g**2) / self.detuning ) * ( self.thermal_photon + 1/2 ) self.X = ((g**2)/self.detuning)*(Q.anh/(Q.f01+Q.anh-fr)) class QRQ(): def __init__(self, Q1, Q2, frb, g1, g2): # Unit in [GHz] self.frb = frb self.g1 = g1 self.g2 = g2 self.Q1 = Q1 self.Q1 = Q2 self.detuning1 = Q1.f01 - frb self.thermal_photon1 = qt.utilities.n_thermal(frb, Q1.f01) self.f01_dressed1 = Q1.f01 + ( 2 * (g1**2) / self.detuning1 ) * ( self.thermal_photon1 + 1/2 ) self.X1 = ((g1**2)/self.detuning1)*(Q1.anh/(Q1.f01+Q1.anh-frb)) self.detuning2 = Q2.f01 - frb self.thermal_photon2 = qt.utilities.n_thermal(frb, Q2.f01) self.f01_dressed2 = Q2.f01 + ( 2 * (g2**2) / self.detuning2 ) * ( self.thermal_photon2 + 1/2 ) self.X2 = ((g2**2)/self.detuning2)*(Q2.anh/(Q2.f01+Q2.anh-frb)) self.D12 = self.f01_dressed1 - self.f01_dressed2 self.J = g1*g2*( self.detuning1 + self.detuning2 ) / ( 2 * self.detuning1 * self.detuning2 ) self.f01_coupled1 = self.f01_dressed1 + (self.J**2)/self.D12 self.f01_coupled2 = self.f01_dressed2 - (self.J**2)/self.D12 class QQ(): # For direct coupling simulation def __init__(self, Q1, Q2, g12): # duffing oscillator model # Unit in [GHz] self.g12 = g12 self.Q1 = Q1 self.Q2 = Q2 self.Nq1, self.Nq2 = Q1.Nq, Q2.Nq iq1, iq2 = qt.qeye(self.Nq1), qt.qeye(self.Nq2) b1, b2 = qt.destroy(self.Nq1), qt.destroy(self.Nq2) self.b1, self.b2 = b1, b2 self.iq1, self.iq2 = iq1, iq2 self.nb1, self.nb2 = self.b1.dag()*self.b1, self.b2.dag()*self.b2 self.B1 = qt.tensor(b1, iq2) self.B2 = qt.tensor(iq1, b2) self.Iq1 = qt.tensor(iq1, iq2) self.Iq2 = qt.tensor(iq1, iq2) self.Nb1 = self.B1.dag()*self.B1 self.Nb2 = self.B2.dag()*self.B2 # Drive term @rotating frame self.Hd1_real = self.B1 + self.B1.dag() self.Hd1_imag = (- self.B1 + self.B1.dag())*1j self.Hd2_real = (self.B2 + self.B2.dag()) self.Hd2_imag = (- self.B2 + self.B2.dag())*1j self.X1 = qt.tensor(pX_N(self.Nq1), iq2) self.Y1 = qt.tensor(pY_N(self.Nq1), iq2) self.Z1 = qt.tensor(pZ_N(self.Nq1), iq2) self.X2 = qt.tensor(iq1, pX_N(self.Nq2)) self.Y2 = qt.tensor(iq1, pY_N(self.Nq2)) self.Z2 = qt.tensor(iq1, pZ_N(self.Nq2)) bbbb1 = self.B1.dag()*self.B1.dag()*self.B1*self.B1 bbbb2 = self.B2.dag()*self.B2.dag()*self.B2*self.B2 self.duff_part1 = 0.5 * self.Q1.anh * self.Nb1 * (self.Nb1 - self.Iq1) # 0.5 * Q1.anh * bbbb1 self.duff_part2 = 0.5 * self.Q2.anh * self.Nb2 * (self.Nb2 - self.Iq2) # 0.5 * Q2.anh * bbbb2 self.Hq1 = Q1.f01 * self.Nb1 + self.duff_part1 # - self.Iq1*0 self.Hq2 = Q2.f01 * self.Nb2 + self.duff_part2 # - self.Iq2*0 self._int12 = self.B1*self.B2.dag() + self.B1.dag()*self.B2 self.Hint12 = g12*(self._int12) self.Hint = self.Hint12 self.Hlab = self.Hq1 + self.Hq2 + self.Hint self.calcStaticZZ(self.Hlab) self.fd1 = self.eigenlevels[0][self.keys['10']] - self.eigenlevels[0][self.keys['00']] self.fd2 = self.eigenlevels[0][self.keys['01']] - self.eigenlevels[0][self.keys['00']] # ref : https://doi.org/10.1103/PhysRevApplied.12.054023 self.staticZZ = self.eigenlevels[0][self.keys['11']] - self.eigenlevels[0][self.keys['10']] - self.eigenlevels[0][self.keys['01']] def dressedEnergyLevels(self, H=None): if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') if H == None: eigenlevels = self.Hlab.eigenstates() else: eigenlevels = H.eigenstates() keys = {} for i in range(Nq): for j in range(Nq): k = ket_2Qsys(i, j, Nq, Nq) e = np.abs([(k.dag() * eigenlevels[1])[i].tr() for i in range(Nq**2)]) index = np.argmax(e) keys['{}{}'.format(i, j)] = index self.keys = keys self.eigenlevels = eigenlevels def plotDressedEnergyLevels(self, figname=1): if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') d = self.keys enes = self.eigenlevels plt.figure(figname, dpi=150) plt.title(r'$|Q1, Q2\rangle$') for i in range(Nq): for j in range(Nq): key = '{}{}'.format(i,j) if key == '22': break index = d[key] ene = enes[0][index] if i < j:#p s = abs(i-j) t = s+1 elif i > j:#m t = -abs(i-j)+1 s = t-1 elif i == j: s = 0 t = 1 plt.hlines(ene, s, t) plt.text(s, ene+0.4, '|'+key+'>'+':{:.4f}GHz'.format(ene)) plt.ylim([-1.0, ene+3]) plt.ylabel('Eigen energy [GHz]') plt.xticks(color='None') plt.tick_params(length=0) plt.grid() def toRotFrameHamiltonian(self, fd, Scl=0, target=0): q1_rot = (self.Q1.f01-fd) * self.nb1 + 0.5 * self.Q1.anh * self.nb1 * (self.nb1 - self.iq1) q2_rot = (self.Q2.f01-fd) * self.nb2 + 0.5 * self.Q2.anh * self.nb2 * (self.nb2 - self.iq2) self.Hqrot = qt.tensor(q1_rot, self.iq2) + qt.tensor(self.iq1, q2_rot) if target == 0: Hdrive = self.B1 + self.B1.dag() else: Hdrive = self.B2 + self.B2.dag() return self.Hqrot + self.Hint + Scl * Hdrive def calcStaticZZ(self, H): self.dressedEnergyLevels(H=H) self.staticZZ = self.eigenlevels[0][self.keys['11']] - self.eigenlevels[0][self.keys['10']] - self.eigenlevels[0][self.keys['01']] return self.staticZZ class QQQ(): # For tunable coupling simulation def __init__(self, Q1, Q2, Qc, gc1, gc2, g12): # duffing oscillator model # Unit in [GHz] self.gc1 = gc1 self.gc2 = gc2 self.g12 = g12 self.Q1 = Q1 self.Q2 = Q2 self.Qc = Qc self.Nq1, self.Nq2, self.Nqc = Q1.Nq, Q2.Nq, Qc.Nq iq1, iq2, iqc = qt.qeye(self.Nq1), qt.qeye(self.Nq2), qt.qeye(self.Nqc) b1, b2, bc = qt.destroy(self.Nq1), qt.destroy(self.Nq2), qt.destroy(self.Nqc) self.B1 = qt.tensor(b1, iq2, iqc) self.B2 = qt.tensor(iq1, b2, iqc) self.Bc = qt.tensor(iq1, iq2, bc) self.Iq1 = qt.tensor(iq1, iq2, iqc) self.Iq2 = qt.tensor(iq1, iq2, iqc) self.Iqc = qt.tensor(iq1, iq2, iqc) self.Nb1 = self.B1.dag()*self.B1 self.Nb2 = self.B2.dag()*self.B2 self.Nbc = self.Bc.dag()*self.Bc bbbb1 = self.B1.dag()*self.B1.dag()*self.B1*self.B1 bbbb2 = self.B2.dag()*self.B2.dag()*self.B2*self.B2 bbbbc = self.Bc.dag()*self.Bc.dag()*self.Bc*self.Bc self.duff_part1 = 0.5 * self.Q1.anh * self.Nb1 * (self.Nb1 - self.Iq1) # 0.5 * Q1.anh * bbbb1 self.duff_part2 = 0.5 * self.Q2.anh * self.Nb2 * (self.Nb2 - self.Iq2) # 0.5 * Q2.anh * bbbb2 self.duff_partc = 0.5 * self.Qc.anh * self.Nbc * (self.Nbc - self.Iqc) # 0.5 * Qc.anh * bbbbc self.Hq1 = Q1.f01 * self.Nb1 + self.duff_part1 # - self.Iq1*0 self.Hq2 = Q2.f01 * self.Nb2 + self.duff_part2 # - self.Iq2*0 self.Hqc = Qc.f01 * self.Nbc + self.duff_partc # - self.Iqc*0 self._intc1 = self.B1*self.Bc.dag() + self.B1.dag()*self.Bc self._intc2 = self.B2*self.Bc.dag() + self.B2.dag()*self.Bc self._int12 = self.B1*self.B2.dag() + self.B1.dag()*self.B2 # self._intc1 = (self.B1 + self.B1.dag())*(self.Bc + self.Bc.dag()) # self._intc2 = (self.B2 + self.B2.dag())*(self.Bc + self.Bc.dag()) # self._int12 = (self.B1 + self.B1.dag())*(self.B2 + self.B2.dag()) self.Hintc1 = gc1*self._intc1 self.Hintc2 = gc2*self._intc2 self.Hint12 = g12*self._int12 self.Hint = self.Hintc1 + self.Hintc2 + self.Hint12 self.Hlab = self.Hq1 + self.Hq2 + self.Hqc + self.Hint self.eigenlevels = self.Hlab.eigenstates() self.dressedEnergyLevels() self.fd1 = self.eigenlevels[0][self.keys['100']] - self.eigenlevels[0][self.keys['000']] self.fd2 = self.eigenlevels[0][self.keys['010']] - self.eigenlevels[0][self.keys['000']] # ref : https://doi.org/10.1103/PhysRevApplied.12.054023 self.staticZZ = self.eigenlevels[0][self.keys['110']] - self.eigenlevels[0][self.keys['100']] - self.eigenlevels[0][self.keys['010']] self.effectiveCoupling = gc1*gc2*(1/(Q1.f01-Qc.f01)+1/(Q2.f01-Qc.f01))*0.5 + g12 def dressedEnergyLevels(self): if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') eigenlevels = self.eigenlevels keys = {} for i in range(Nq): for j in range(Nq): for k in range(Nq): bra = ket_3Qsys(i, j, k, Nq, Nq, Nq).dag() e = np.abs([(bra * eigenlevels[1])[i].tr() for i in range(Nq**3)]) index = np.argmax(e) keys['{}{}{}'.format(i, j, k)] = index self.keys = keys def plotDressedEnergyLevels(self, coupler_exitation_stop=0): # coupler_exitation_stop : coupler exitation number to be plotted. ces = coupler_exitation_stop if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') d = self.keys enes = self.eigenlevels plt.figure(1, dpi=150) cmap = plt.get_cmap("tab10") plt.title(r'$|Q1, Q2, Qc\rangle$') for i in range(Nq): for j in range(Nq): for k in range(Nq): key = '{}{}{}'.format(i, j, k) if key == '220' or k > ces: break index = d[key] ene = enes[0][index] if i < j:#p s = abs(i-j) t = s+1 elif i > j:#m t = -abs(i-j)+1 s = t-1 elif i == j: s = 0 t = 1 plt.hlines(ene, s, t, color=cmap(k)) plt.text(s, ene+0.4, '|'+key+r'$\rangle$'+':{:.3f}GHz'.format(ene)) plt.ylim([-1.0, ene+3]) plt.ylabel('Eigen energy [GHz]') plt.xticks(color='None') plt.tick_params(length=0) plt.grid() class RQRQR(): def __init__(self, QR1, QR2, frb, g1, g2): # Unit in [GHz] self.frb = frb self.g1 = g1 self.g2 = g2 self.QR1 = QR1 self.QR2 = QR2 self.detuning1 = QR1.f01_dressed - frb self.thermal_photon1 = qt.utilities.n_thermal(frb, QR1.f01_dressed) self.f01_dressed1 = QR1.f01_dressed + ( 2 * (g1**2) / self.detuning1 ) * ( self.thermal_photon1 + 1/2 ) self.X1 = ((g1**2)/self.detuning1)*(QR1.Q.anh/(QR1.f01_dressed + QR1.Q.anh - frb)) self.detuning2 = QR2.f01_dressed - frb self.thermal_photon2 = qt.utilities.n_thermal(frb, QR2.f01_dressed) self.f01_dressed2 = QR2.f01_dressed + ( 2 * (g2**2) / self.detuning2 ) * ( self.thermal_photon2 + 1/2 ) self.X2 = ((g2**2)/self.detuning2)*(QR2.Q.anh/(QR2.f01_dressed + QR2.Q.anh - frb)) self.D12 = self.f01_dressed1 - self.f01_dressed2 self.J = g1*g2*( self.detuning1 + self.detuning2 ) / ( 2 * self.detuning1 * self.detuning2 ) self.f01_coupled1 = self.f01_dressed1 + (self.J**2)/self.D12 self.f01_coupled2 = self.f01_dressed2 - (self.J**2)/self.D12 class labFrame2Qhamiltonian_DuffingOscillator(): def __init__(self, RQRQR, Nq1, Nq2): self.Nq1, self.Nq2 = Nq1, Nq2 Iq1, Iq2 = qt.qeye(Nq1), qt.qeye(Nq2) b1, b2 = qt.destroy(Nq1), qt.destroy(Nq2) Nb1, Nb2 = b1.dag()*b1, b2.dag()*b2 self.X1 = qt.tensor(pX_N(Nq1), Iq2) self.Y1 = qt.tensor(pY_N(Nq1), Iq2) self.Z1 = qt.tensor(pZ_N(Nq1), Iq2) self.X2 = qt.tensor(Iq1, pX_N(Nq2)) self.Y2 = qt.tensor(Iq1, pY_N(Nq2)) self.Z2 = qt.tensor(Iq1, pZ_N(Nq2)) self.Iq1, self.Iq2 = Iq1, Iq2 self.Nb1, self.Nb2 = Nb1, Nb2 self.QR1 = RQRQR.QR1 self.QR2 = RQRQR.QR2 J = RQRQR.J self.B1 = qt.tensor(b1, Iq2) self.B2 = qt.tensor(Iq1, b2) bbbb1 = b1.dag()*b1.dag()*b1*b1 bbbb2 = b2.dag()*b2.dag()*b2*b2 # Drive term @rotating frame self.Hd1_real = self.B1 + self.B1.dag() self.Hd1_imag = (- self.B1 + self.B1.dag())*1j self.Hd2_real = (self.B2 + self.B2.dag()) self.Hd2_imag = (- self.B2 + self.B2.dag())*1j q1_lab = self.QR1.f01_dressed * Nb1 + 0.5 * self.QR1.Q.anh * Nb1 * (Nb1 - Iq1) q2_lab = self.QR2.f01_dressed * Nb2 + 0.5 * self.QR2.Q.anh * Nb2 * (Nb2 - Iq2) self.Hqlab = qt.tensor(q1_lab, Iq2) + qt.tensor(Iq1, q2_lab) self.Hint = J * ( qt.tensor(b1, b2.dag()) + qt.tensor(b1.dag(), b2) ) self.Hlab = self.Hqlab + self.Hint self.dressedEnergyLevels() self.fd1 = self.eigenlevels[0][self.keys['10']] - self.eigenlevels[0][self.keys['00']] self.fd2 = self.eigenlevels[0][self.keys['01']] - self.eigenlevels[0][self.keys['00']] def dressedEnergyLevels(self): if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') eigenlevels = self.Hlab.eigenstates() keys = {} for i in range(Nq): for j in range(Nq): k = ket_2Qsys(i, j, Nq, Nq) e = np.abs([(k.dag() * eigenlevels[1])[i].tr() for i in range(Nq**2)]) index = np.argmax(e) keys['{}{}'.format(i, j)] = index self.keys = keys self.eigenlevels = eigenlevels def plotDressedEnergyLevels(self): if self.Nq1 == self.Nq2: Nq = self.Nq2 else: print('Should be Nq1 = Nq2') d = self.keys enes = self.eigenlevels plt.figure(1) for i in range(Nq): for j in range(Nq): key = '{}{}'.format(i,j) if key == '22': break index = d[key] ene = enes[0][index] if i < j:#p s = abs(i-j) t = s+1 elif i > j:#m t = -abs(i-j)+1 s = t-1 elif i == j: s = 0 t = 1 plt.hlines(ene, s, t) plt.text(s, ene+0.4, '|'+key+'>'+':{:.3f}GHz'.format(ene)) plt.ylim([-1.0, ene+3]) plt.ylabel('Eigen energy [GHz]') plt.xticks(color='None') plt.tick_params(length=0) plt.grid() def toRotFrameHamiltonian(self, fd:float): Nb1, Nb2 = self.Nb1, self.Nb2 Iq1, Iq2 = self.Iq1, self.Iq2 q1_rot = (self.QR1.f01_dressed-fd) * Nb1 + 0.5 * self.QR1.Q.anh * Nb1 * (Nb1 - Iq1) q2_rot = (self.QR2.f01_dressed-fd) * Nb2 + 0.5 * self.QR2.Q.anh * Nb2 * (Nb2 - Iq2) self.Hqrot = qt.tensor(q1_rot, self.Iq2) + qt.tensor(self.Iq1, q2_rot) return self.Hqrot + self.Hint def toDoublyRotFrameHamiltonian(self, fd1:float, fd2:float): Nb1, Nb2 = self.Nb1, self.Nb2 Iq1, Iq2 = self.Iq1, self.Iq2 q1_rot = (self.QR1.f01_dressed-fd1) * Nb1 + 0.5 * self.QR1.Q.anh * Nb1 * (Nb1 - Iq1) q2_rot = (self.QR2.f01_dressed-fd2) * Nb2 + 0.5 * self.QR2.Q.anh * Nb2 * (Nb2 - Iq2) self.Hqrot = qt.tensor(q1_rot, self.Iq2) + qt.tensor(self.Iq1, q2_rot) return self.Hqrot + self.Hint class labFrame1Qhamiltonian_DuffingOscillator(): def __init__(self, QR, Nq): self.Nq = Nq Iq = qt.qeye(Nq) b = qt.destroy(Nq) Nb = b.dag()*b self.X = pX_N(Nq) self.Y = pY_N(Nq) self.Z = pZ_N(Nq) self.Iq = Iq self.Nb = Nb self.QR = QR self.B = b # Drive term @rotating frame self.f01_dressed = QR.f01_dressed self.Hd1_real = self.B + self.B.dag() self.Hd1_imag = (- self.B + self.B.dag())*1j q1_lab = self.QR.f01_dressed * Nb + 0.5 * self.QR.Q.anh * Nb * (Nb - Iq) self.Hqlab = q1_lab self.Hlab = self.Hqlab def calcUrot(self, t_list): Urots = [] for t in t_list: u = (1j*self.f01_dressed*t*self.Nb).expm() Urots.append(u) return Urots class labFrame1Q_1R_hamiltonian(): def __init__(self, Q, R, g): """ params --- Q : class instance transmon() R : class instance resonator() g : float in [GHz] coupling constant """ self.Nq = Q.Nq self.Nf = R.Nf self.Ir = Ir = R.Ir self.Iq = Iq = Q.Iq self.II = qt.tensor(Iq, Ir) self.f01 = Q.f01 self.anh = Q.anh self.fr = R.fr self.g = g self.Q = Q self.R = R self.detuning = Q.f01 - R.fr # self.thermal_photon = qt.utilities.n_thermal(self.fr, Q.f01) # self.f01_dressed = Q.f01 + ( 2 * (g**2) / self.detuning ) * ( self.thermal_photon + 1/2 ) self.X = qt.tensor(Q.X, Ir) self.Y = qt.tensor(Q.Y, Ir) self.Z = qt.tensor(Q.Z, Ir) self.P0 = qt.tensor(Q.P0, Ir) self.P1 = qt.tensor(Q.P1, Ir) self.Na = qt.tensor(Iq, R.na) self.Nb = qt.tensor(Q.nb, Ir) self.A = A = qt.tensor(Iq, R.a) self.B = B = qt.tensor(Q.b, Ir) self.HQ1 = qt.tensor(Q.Hqlab, Ir) self.HR1 = qt.tensor(Iq, R.Hr) self.Hint = g * ( B*A.dag() + B.dag()*A ) self.Hd1_real = A + A.dag() self.Hd1_imag = (- A + A.dag())*1j self.Hlab = self.HQ1 + self.HR1 + self.Hint self.dressedEnergyLevels() self.fq10 = self.eigenlevels[0][self.keys['10']] - self.eigenlevels[0][self.keys['00']] self.fq11 = self.eigenlevels[0][self.keys['11']] - self.eigenlevels[0][self.keys['01']] self.fr0 = self.eigenlevels[0][self.keys['01']] - self.eigenlevels[0][self.keys['00']] self.fr1 = self.eigenlevels[0][self.keys['11']] - self.eigenlevels[0][self.keys['10']] def calcUrot(self, t_list, fd): Urots = [] for t in t_list: u = (1j*fd*(self.Na + self.Nb)*t).expm() Urots.append(u) return Urots def addDecoherence(self): pass return def calcDispersiveShift(self): eigenlevels = self.Hlab.eigenstates() e0 = qt.tensor(qt.basis(self.Nq, 1), qt.fock(self.Nf, 0)) g1 = qt.tensor(qt.basis(self.Nq, 0), qt.fock(self.Nf, 1)) e1 = qt.tensor(qt.basis(self.Nq, 1), qt.fock(self.Nf, 1)) ket_try = [e0, g1, e1] ket_keys = ['e0', 'g1', 'e1'] disp_dic = {} for i in range(3): e = np.abs([(ket_try[i].dag() * eigenlevels[1])[j].tr() for j in range(self.Nq*self.Nf)]) index = np.argmax(e) disp_dic[ket_keys[i]] = eigenlevels[0][index] disp_dic['chi'] = (disp_dic['e1'] - disp_dic['e0'] - disp_dic['g1'])/2 self.dispersiveshift = disp_dic return disp_dic def toRotFrameHamiltonian(self, fd:float): q1_rot = (self.f01-fd) * self.Nb + 0.5 * self.Q.anh * self.Nb * (self.Nb - self.II) r1_rot = (self.fr-fd) * self.Na self.Hrot = q1_rot + r1_rot + self.Hint return self.Hrot def dressedEnergyLevels(self, H=None): Nq = self.Nq Nf = self.Nf if H == None: eigenlevels = self.Hlab.eigenstates() else: eigenlevels = H.eigenstates() keys = {} for i in range(Nq): for j in range(2): k = ket_2Qsys(i, j, Nq, Nf) e = np.abs([(k.dag() * eigenlevels[1])[i].tr() for i in range(Nq*Nf)]) index = np.argmax(e) keys['{}{}'.format(i, j)] = index self.keys = keys self.eigenlevels = eigenlevels def plotDressedEnergyLevels(self, figname=1): Nq = self.Nq Nf = self.Nf d = self.keys enes = self.eigenlevels plt.figure(figname, dpi=150) plt.title(r'$|Transmon, Resonator\rangle$') for i in range(Nq): for j in range(2): key = '{}{}'.format(i,j) if key == '22': break index = d[key] ene = enes[0][index] if i < j:#p s = abs(i-j) t = s+1 elif i > j:#m t = -abs(i-j)+1 s = t-1 elif i == j: s = 0 t = 1 plt.hlines(ene, s, t) plt.text(s, ene+0.4, '|'+key+r'$\rangle$'+':{:.4f}GHz'.format(ene)) plt.ylim([-1.0, ene+3]) plt.ylabel('Eigen energy [GHz]') plt.xticks(color='None') plt.tick_params(length=0) plt.grid() class timeEvo(): def __init__(self): return 0
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.ylabel", "qutip.fock", "qutip.thermal_dm", "numpy.arange", "qutip.destroy", "qutip.Qobj", "qutip.basis", "numpy.exp", "matplotlib.pyplot.ylim", "qutip.utilities.n_thermal", "numpy.ones", "matplotlib.pyplot.xticks", "matplotlib.pyplot.tick_params...
[((352, 367), 'qutip.basis', 'qt.basis', (['Nq', 'i'], {}), '(Nq, i)\n', (360, 367), True, 'import qutip as qt\n'), ((451, 466), 'qutip.tensor', 'qt.tensor', (['a', 'b'], {}), '(a, b)\n', (460, 466), True, 'import qutip as qt\n'), ((578, 596), 'qutip.tensor', 'qt.tensor', (['a', 'b', 'c'], {}), '(a, b, c)\n', (587, 596), True, 'import qutip as qt\n'), ((1691, 1708), 'qutip.tensor', 'qt.tensor', (['R1', 'R2'], {}), '(R1, R2)\n', (1700, 1708), True, 'import qutip as qt\n'), ((1994, 2008), 'qutip.fock', 'qt.fock', (['Nf', 't'], {}), '(Nf, t)\n', (2001, 2008), True, 'import qutip as qt\n'), ((2020, 2037), 'qutip.tensor', 'qt.tensor', (['q1', 'r1'], {}), '(q1, r1)\n', (2029, 2037), True, 'import qutip as qt\n'), ((2255, 2272), 'qutip.tensor', 'qt.tensor', (['q1', 'q2'], {}), '(q1, q2)\n', (2264, 2272), True, 'import qutip as qt\n'), ((3403, 3435), 'qutip.thermal_dm', 'qt.thermal_dm', (['Nq', 'self.nth_q[1]'], {}), '(Nq, self.nth_q[1])\n', (3416, 3435), True, 'import qutip as qt\n'), ((4185, 4195), 'qutip.Qobj', 'qt.Qobj', (['m'], {}), '(m)\n', (4192, 4195), True, 'import qutip as qt\n'), ((4273, 4284), 'qutip.qeye', 'qt.qeye', (['Nq'], {}), '(Nq)\n', (4280, 4284), True, 'import qutip as qt\n'), ((4297, 4311), 'qutip.destroy', 'qt.destroy', (['Nq'], {}), '(Nq)\n', (4307, 4311), True, 'import qutip as qt\n'), ((5346, 5360), 'qutip.destroy', 'qt.destroy', (['Nf'], {}), '(Nf)\n', (5356, 5360), True, 'import qutip as qt\n'), ((5476, 5487), 'qutip.qeye', 'qt.qeye', (['Nf'], {}), '(Nf)\n', (5483, 5487), True, 'import qutip as qt\n'), ((5595, 5624), 'qutip.thermal_dm', 'qt.thermal_dm', (['Nf', 'self.nth_a'], {}), '(Nf, self.nth_a)\n', (5608, 5624), True, 'import qutip as qt\n'), ((5821, 5854), 'qutip.utilities.n_thermal', 'qt.utilities.n_thermal', (['fr', 'Q.f01'], {}), '(fr, Q.f01)\n', (5843, 5854), True, 'import qutip as qt\n'), ((6278, 6313), 'qutip.utilities.n_thermal', 'qt.utilities.n_thermal', (['frb', 'Q1.f01'], {}), '(frb, Q1.f01)\n', (6300, 6313), True, 'import qutip as qt\n'), ((6559, 6594), 'qutip.utilities.n_thermal', 'qt.utilities.n_thermal', (['frb', 'Q2.f01'], {}), '(frb, Q2.f01)\n', (6581, 6594), True, 'import qutip as qt\n'), ((7602, 7620), 'qutip.tensor', 'qt.tensor', (['b1', 'iq2'], {}), '(b1, iq2)\n', (7611, 7620), True, 'import qutip as qt\n'), ((7639, 7657), 'qutip.tensor', 'qt.tensor', (['iq1', 'b2'], {}), '(iq1, b2)\n', (7648, 7657), True, 'import qutip as qt\n'), ((7677, 7696), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2'], {}), '(iq1, iq2)\n', (7686, 7696), True, 'import qutip as qt\n'), ((7716, 7735), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2'], {}), '(iq1, iq2)\n', (7725, 7735), True, 'import qutip as qt\n'), ((10325, 10353), 'matplotlib.pyplot.figure', 'plt.figure', (['figname'], {'dpi': '(150)'}), '(figname, dpi=150)\n', (10335, 10353), True, 'import matplotlib.pyplot as plt\n'), ((10362, 10392), 'matplotlib.pyplot.title', 'plt.title', (['"""$|Q1, Q2\\\\rangle$"""'], {}), "('$|Q1, Q2\\\\rangle$')\n", (10371, 10392), True, 'import matplotlib.pyplot as plt\n'), ((11006, 11031), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.0, ene + 3]'], {}), '([-1.0, ene + 3])\n', (11014, 11031), True, 'import matplotlib.pyplot as plt\n'), ((11038, 11070), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigen energy [GHz]"""'], {}), "('Eigen energy [GHz]')\n", (11048, 11070), True, 'import matplotlib.pyplot as plt\n'), ((11079, 11103), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'color': '"""None"""'}), "(color='None')\n", (11089, 11103), True, 'import matplotlib.pyplot as plt\n'), ((11112, 11137), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'length': '(0)'}), '(length=0)\n', (11127, 11137), True, 'import matplotlib.pyplot as plt\n'), ((11146, 11156), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (11154, 11156), True, 'import matplotlib.pyplot as plt\n'), ((12454, 12477), 'qutip.tensor', 'qt.tensor', (['b1', 'iq2', 'iqc'], {}), '(b1, iq2, iqc)\n', (12463, 12477), True, 'import qutip as qt\n'), ((12496, 12519), 'qutip.tensor', 'qt.tensor', (['iq1', 'b2', 'iqc'], {}), '(iq1, b2, iqc)\n', (12505, 12519), True, 'import qutip as qt\n'), ((12538, 12561), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2', 'bc'], {}), '(iq1, iq2, bc)\n', (12547, 12561), True, 'import qutip as qt\n'), ((12581, 12605), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2', 'iqc'], {}), '(iq1, iq2, iqc)\n', (12590, 12605), True, 'import qutip as qt\n'), ((12625, 12649), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2', 'iqc'], {}), '(iq1, iq2, iqc)\n', (12634, 12649), True, 'import qutip as qt\n'), ((12669, 12693), 'qutip.tensor', 'qt.tensor', (['iq1', 'iq2', 'iqc'], {}), '(iq1, iq2, iqc)\n', (12678, 12693), True, 'import qutip as qt\n'), ((15696, 15718), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'dpi': '(150)'}), '(1, dpi=150)\n', (15706, 15718), True, 'import matplotlib.pyplot as plt\n'), ((15734, 15755), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab10"""'], {}), "('tab10')\n", (15746, 15755), True, 'import matplotlib.pyplot as plt\n'), ((15764, 15798), 'matplotlib.pyplot.title', 'plt.title', (['"""$|Q1, Q2, Qc\\\\rangle$"""'], {}), "('$|Q1, Q2, Qc\\\\rangle$')\n", (15773, 15798), True, 'import matplotlib.pyplot as plt\n'), ((16553, 16578), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.0, ene + 3]'], {}), '([-1.0, ene + 3])\n', (16561, 16578), True, 'import matplotlib.pyplot as plt\n'), ((16585, 16617), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigen energy [GHz]"""'], {}), "('Eigen energy [GHz]')\n", (16595, 16617), True, 'import matplotlib.pyplot as plt\n'), ((16626, 16650), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'color': '"""None"""'}), "(color='None')\n", (16636, 16650), True, 'import matplotlib.pyplot as plt\n'), ((16659, 16684), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'length': '(0)'}), '(length=0)\n', (16674, 16684), True, 'import matplotlib.pyplot as plt\n'), ((16693, 16703), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (16701, 16703), True, 'import matplotlib.pyplot as plt\n'), ((16980, 17024), 'qutip.utilities.n_thermal', 'qt.utilities.n_thermal', (['frb', 'QR1.f01_dressed'], {}), '(frb, QR1.f01_dressed)\n', (17002, 17024), True, 'import qutip as qt\n'), ((17307, 17351), 'qutip.utilities.n_thermal', 'qt.utilities.n_thermal', (['frb', 'QR2.f01_dressed'], {}), '(frb, QR2.f01_dressed)\n', (17329, 17351), True, 'import qutip as qt\n'), ((18563, 18581), 'qutip.tensor', 'qt.tensor', (['b1', 'Iq2'], {}), '(b1, Iq2)\n', (18572, 18581), True, 'import qutip as qt\n'), ((18600, 18618), 'qutip.tensor', 'qt.tensor', (['Iq1', 'b2'], {}), '(Iq1, b2)\n', (18609, 18618), True, 'import qutip as qt\n'), ((20308, 20321), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (20318, 20321), True, 'import matplotlib.pyplot as plt\n'), ((20935, 20960), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.0, ene + 3]'], {}), '([-1.0, ene + 3])\n', (20943, 20960), True, 'import matplotlib.pyplot as plt\n'), ((20967, 20999), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigen energy [GHz]"""'], {}), "('Eigen energy [GHz]')\n", (20977, 20999), True, 'import matplotlib.pyplot as plt\n'), ((21008, 21032), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'color': '"""None"""'}), "(color='None')\n", (21018, 21032), True, 'import matplotlib.pyplot as plt\n'), ((21041, 21066), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'length': '(0)'}), '(length=0)\n', (21056, 21066), True, 'import matplotlib.pyplot as plt\n'), ((21075, 21085), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (21083, 21085), True, 'import matplotlib.pyplot as plt\n'), ((22075, 22086), 'qutip.qeye', 'qt.qeye', (['Nq'], {}), '(Nq)\n', (22082, 22086), True, 'import qutip as qt\n'), ((22099, 22113), 'qutip.destroy', 'qt.destroy', (['Nq'], {}), '(Nq)\n', (22109, 22113), True, 'import qutip as qt\n'), ((23197, 23214), 'qutip.tensor', 'qt.tensor', (['Iq', 'Ir'], {}), '(Iq, Ir)\n', (23206, 23214), True, 'import qutip as qt\n'), ((23572, 23590), 'qutip.tensor', 'qt.tensor', (['Q.X', 'Ir'], {}), '(Q.X, Ir)\n', (23581, 23590), True, 'import qutip as qt\n'), ((23608, 23626), 'qutip.tensor', 'qt.tensor', (['Q.Y', 'Ir'], {}), '(Q.Y, Ir)\n', (23617, 23626), True, 'import qutip as qt\n'), ((23644, 23662), 'qutip.tensor', 'qt.tensor', (['Q.Z', 'Ir'], {}), '(Q.Z, Ir)\n', (23653, 23662), True, 'import qutip as qt\n'), ((23681, 23700), 'qutip.tensor', 'qt.tensor', (['Q.P0', 'Ir'], {}), '(Q.P0, Ir)\n', (23690, 23700), True, 'import qutip as qt\n'), ((23719, 23738), 'qutip.tensor', 'qt.tensor', (['Q.P1', 'Ir'], {}), '(Q.P1, Ir)\n', (23728, 23738), True, 'import qutip as qt\n'), ((23758, 23777), 'qutip.tensor', 'qt.tensor', (['Iq', 'R.na'], {}), '(Iq, R.na)\n', (23767, 23777), True, 'import qutip as qt\n'), ((23796, 23815), 'qutip.tensor', 'qt.tensor', (['Q.nb', 'Ir'], {}), '(Q.nb, Ir)\n', (23805, 23815), True, 'import qutip as qt\n'), ((23837, 23855), 'qutip.tensor', 'qt.tensor', (['Iq', 'R.a'], {}), '(Iq, R.a)\n', (23846, 23855), True, 'import qutip as qt\n'), ((23877, 23895), 'qutip.tensor', 'qt.tensor', (['Q.b', 'Ir'], {}), '(Q.b, Ir)\n', (23886, 23895), True, 'import qutip as qt\n'), ((23916, 23938), 'qutip.tensor', 'qt.tensor', (['Q.Hqlab', 'Ir'], {}), '(Q.Hqlab, Ir)\n', (23925, 23938), True, 'import qutip as qt\n'), ((23958, 23977), 'qutip.tensor', 'qt.tensor', (['Iq', 'R.Hr'], {}), '(Iq, R.Hr)\n', (23967, 23977), True, 'import qutip as qt\n'), ((26540, 26568), 'matplotlib.pyplot.figure', 'plt.figure', (['figname'], {'dpi': '(150)'}), '(figname, dpi=150)\n', (26550, 26568), True, 'import matplotlib.pyplot as plt\n'), ((26577, 26620), 'matplotlib.pyplot.title', 'plt.title', (['"""$|Transmon, Resonator\\\\rangle$"""'], {}), "('$|Transmon, Resonator\\\\rangle$')\n", (26586, 26620), True, 'import matplotlib.pyplot as plt\n'), ((27242, 27267), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-1.0, ene + 3]'], {}), '([-1.0, ene + 3])\n', (27250, 27267), True, 'import matplotlib.pyplot as plt\n'), ((27274, 27306), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Eigen energy [GHz]"""'], {}), "('Eigen energy [GHz]')\n", (27284, 27306), True, 'import matplotlib.pyplot as plt\n'), ((27315, 27339), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'color': '"""None"""'}), "(color='None')\n", (27325, 27339), True, 'import matplotlib.pyplot as plt\n'), ((27348, 27373), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'length': '(0)'}), '(length=0)\n', (27363, 27373), True, 'import matplotlib.pyplot as plt\n'), ((27382, 27392), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (27390, 27392), True, 'import matplotlib.pyplot as plt\n'), ((975, 1001), 'numpy.exp', 'np.exp', (['(-fi * h / (kb * T))'], {}), '(-fi * h / (kb * T))\n', (981, 1001), True, 'import numpy as np\n'), ((1008, 1052), 'numpy.exp', 'np.exp', (['(-fs[i] * 1000000000.0 * h / (kb * T))'], {}), '(-fs[i] * 1000000000.0 * h / (kb * T))\n', (1014, 1052), True, 'import numpy as np\n'), ((7340, 7357), 'qutip.qeye', 'qt.qeye', (['self.Nq1'], {}), '(self.Nq1)\n', (7347, 7357), True, 'import qutip as qt\n'), ((7359, 7376), 'qutip.qeye', 'qt.qeye', (['self.Nq2'], {}), '(self.Nq2)\n', (7366, 7376), True, 'import qutip as qt\n'), ((7394, 7414), 'qutip.destroy', 'qt.destroy', (['self.Nq1'], {}), '(self.Nq1)\n', (7404, 7414), True, 'import qutip as qt\n'), ((7416, 7436), 'qutip.destroy', 'qt.destroy', (['self.Nq2'], {}), '(self.Nq2)\n', (7426, 7436), True, 'import qutip as qt\n'), ((11437, 11464), 'qutip.tensor', 'qt.tensor', (['q1_rot', 'self.iq2'], {}), '(q1_rot, self.iq2)\n', (11446, 11464), True, 'import qutip as qt\n'), ((11467, 11494), 'qutip.tensor', 'qt.tensor', (['self.iq1', 'q2_rot'], {}), '(self.iq1, q2_rot)\n', (11476, 11494), True, 'import qutip as qt\n'), ((12293, 12310), 'qutip.qeye', 'qt.qeye', (['self.Nq1'], {}), '(self.Nq1)\n', (12300, 12310), True, 'import qutip as qt\n'), ((12312, 12329), 'qutip.qeye', 'qt.qeye', (['self.Nq2'], {}), '(self.Nq2)\n', (12319, 12329), True, 'import qutip as qt\n'), ((12331, 12348), 'qutip.qeye', 'qt.qeye', (['self.Nqc'], {}), '(self.Nqc)\n', (12338, 12348), True, 'import qutip as qt\n'), ((12370, 12390), 'qutip.destroy', 'qt.destroy', (['self.Nq1'], {}), '(self.Nq1)\n', (12380, 12390), True, 'import qutip as qt\n'), ((12392, 12412), 'qutip.destroy', 'qt.destroy', (['self.Nq2'], {}), '(self.Nq2)\n', (12402, 12412), True, 'import qutip as qt\n'), ((12414, 12434), 'qutip.destroy', 'qt.destroy', (['self.Nqc'], {}), '(self.Nqc)\n', (12424, 12434), True, 'import qutip as qt\n'), ((18002, 18014), 'qutip.qeye', 'qt.qeye', (['Nq1'], {}), '(Nq1)\n', (18009, 18014), True, 'import qutip as qt\n'), ((18016, 18028), 'qutip.qeye', 'qt.qeye', (['Nq2'], {}), '(Nq2)\n', (18023, 18028), True, 'import qutip as qt\n'), ((18046, 18061), 'qutip.destroy', 'qt.destroy', (['Nq1'], {}), '(Nq1)\n', (18056, 18061), True, 'import qutip as qt\n'), ((18063, 18078), 'qutip.destroy', 'qt.destroy', (['Nq2'], {}), '(Nq2)\n', (18073, 18078), True, 'import qutip as qt\n'), ((19140, 19162), 'qutip.tensor', 'qt.tensor', (['q1_lab', 'Iq2'], {}), '(q1_lab, Iq2)\n', (19149, 19162), True, 'import qutip as qt\n'), ((19165, 19187), 'qutip.tensor', 'qt.tensor', (['Iq1', 'q2_lab'], {}), '(Iq1, q2_lab)\n', (19174, 19187), True, 'import qutip as qt\n'), ((21416, 21443), 'qutip.tensor', 'qt.tensor', (['q1_rot', 'self.Iq2'], {}), '(q1_rot, self.Iq2)\n', (21425, 21443), True, 'import qutip as qt\n'), ((21446, 21473), 'qutip.tensor', 'qt.tensor', (['self.Iq1', 'q2_rot'], {}), '(self.Iq1, q2_rot)\n', (21455, 21473), True, 'import qutip as qt\n'), ((21862, 21889), 'qutip.tensor', 'qt.tensor', (['q1_rot', 'self.Iq2'], {}), '(q1_rot, self.Iq2)\n', (21871, 21889), True, 'import qutip as qt\n'), ((21892, 21919), 'qutip.tensor', 'qt.tensor', (['self.Iq1', 'q2_rot'], {}), '(self.Iq1, q2_rot)\n', (21901, 21919), True, 'import qutip as qt\n'), ((24924, 24944), 'qutip.basis', 'qt.basis', (['self.Nq', '(1)'], {}), '(self.Nq, 1)\n', (24932, 24944), True, 'import qutip as qt\n'), ((24946, 24965), 'qutip.fock', 'qt.fock', (['self.Nf', '(0)'], {}), '(self.Nf, 0)\n', (24953, 24965), True, 'import qutip as qt\n'), ((24990, 25010), 'qutip.basis', 'qt.basis', (['self.Nq', '(0)'], {}), '(self.Nq, 0)\n', (24998, 25010), True, 'import qutip as qt\n'), ((25012, 25031), 'qutip.fock', 'qt.fock', (['self.Nf', '(1)'], {}), '(self.Nf, 1)\n', (25019, 25031), True, 'import qutip as qt\n'), ((25056, 25076), 'qutip.basis', 'qt.basis', (['self.Nq', '(1)'], {}), '(self.Nq, 1)\n', (25064, 25076), True, 'import qutip as qt\n'), ((25078, 25097), 'qutip.fock', 'qt.fock', (['self.Nf', '(1)'], {}), '(self.Nf, 1)\n', (25085, 25097), True, 'import qutip as qt\n'), ((25339, 25351), 'numpy.argmax', 'np.argmax', (['e'], {}), '(e)\n', (25348, 25351), True, 'import numpy as np\n'), ((697, 721), 'numpy.exp', 'np.exp', (['(h * f / (kb * T))'], {}), '(h * f / (kb * T))\n', (703, 721), True, 'import numpy as np\n'), ((9970, 9982), 'numpy.argmax', 'np.argmax', (['e'], {}), '(e)\n', (9979, 9982), True, 'import numpy as np\n'), ((10900, 10921), 'matplotlib.pyplot.hlines', 'plt.hlines', (['ene', 's', 't'], {}), '(ene, s, t)\n', (10910, 10921), True, 'import matplotlib.pyplot as plt\n'), ((19964, 19976), 'numpy.argmax', 'np.argmax', (['e'], {}), '(e)\n', (19973, 19976), True, 'import numpy as np\n'), ((20829, 20850), 'matplotlib.pyplot.hlines', 'plt.hlines', (['ene', 's', 't'], {}), '(ene, s, t)\n', (20839, 20850), True, 'import matplotlib.pyplot as plt\n'), ((26257, 26269), 'numpy.argmax', 'np.argmax', (['e'], {}), '(e)\n', (26266, 26269), True, 'import numpy as np\n'), ((27127, 27148), 'matplotlib.pyplot.hlines', 'plt.hlines', (['ene', 's', 't'], {}), '(ene, s, t)\n', (27137, 27148), True, 'import matplotlib.pyplot as plt\n'), ((15244, 15256), 'numpy.argmax', 'np.argmax', (['e'], {}), '(e)\n', (15253, 15256), True, 'import numpy as np\n'), ((4010, 4030), 'numpy.arange', 'np.arange', (['(-N)', '(N + 1)'], {}), '(-N, N + 1)\n', (4019, 4030), True, 'import numpy as np\n'), ((4059, 4073), 'numpy.ones', 'np.ones', (['(2 * N)'], {}), '(2 * N)\n', (4066, 4073), True, 'import numpy as np\n'), ((4151, 4165), 'numpy.ones', 'np.ones', (['(2 * N)'], {}), '(2 * N)\n', (4158, 4165), True, 'import numpy as np\n')]
import os import numpy as np import rpy2 from biomarker_survival import analysis def test_do_cox_success(): time = [48, 79, 9, 60, 81, 0, 64, 5, 26, 39, 83, 55, 33, 20, 29, 38, 47, 49, 96, 50, 84, 45, 84, 43, 4, 87, 27, 15, 24, 34, 46, 43, 53, 41, 86, 69, 79, 25, 6, 65, 71, 52, 43, 18, 32, 7, 47, 57, 7, 45] censor = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1] split = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1] cox_dict = analysis.do_cox(time, censor, split) print(cox_dict) assert cox_dict['n'] == 50 assert cox_dict['p'] < 1 assert list(cox_dict.keys()).sort() == ['n', 'z', 'p', 'hazard_ratio', 'lower_conf', 'upper_conf'].sort() def test_do_cox_fail(): time = np.random.randint(0,1, 5) censor = np.random.randint(0,1, 5) split = np.random.randint(0,1, 5) cox_dict = analysis.do_cox(time, censor, split) if len(list(cox_dict.keys())) == 0: assert list(cox_dict.keys()) == [] else: assert np.isnan(cox_dict['p']) assert list(cox_dict.keys()).sort() == ['n', 'z', 'p', 'hazard_ratio', 'lower_conf', 'upper_conf'].sort()
[ "biomarker_survival.analysis.do_cox", "numpy.random.randint", "numpy.isnan" ]
[((700, 736), 'biomarker_survival.analysis.do_cox', 'analysis.do_cox', (['time', 'censor', 'split'], {}), '(time, censor, split)\n', (715, 736), False, 'from biomarker_survival import analysis\n'), ((953, 979), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (970, 979), True, 'import numpy as np\n'), ((990, 1016), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (1007, 1016), True, 'import numpy as np\n'), ((1026, 1052), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1)', '(5)'], {}), '(0, 1, 5)\n', (1043, 1052), True, 'import numpy as np\n'), ((1066, 1102), 'biomarker_survival.analysis.do_cox', 'analysis.do_cox', (['time', 'censor', 'split'], {}), '(time, censor, split)\n', (1081, 1102), False, 'from biomarker_survival import analysis\n'), ((1199, 1222), 'numpy.isnan', 'np.isnan', (["cox_dict['p']"], {}), "(cox_dict['p'])\n", (1207, 1222), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np import os import csv import SimpleITK import fnmatch import xml.etree.ElementTree as ET dcmfile = '/Users/yanzhexu/Google Drive/Marley Grant Data/CEDM-51/malignant/Pt50/Pt50 - LE - CC.dcm' xmlfile = '/Users/yanzhexu/Google Drive/Marley Grant Data/CEDM-51/malignant/Pt50/VES_LCC.xml' def drawplot(contourx1,contourx2,contoury1,contoury2,color,lw): plt.plot([contourx1, contourx1], [contoury1, contoury2], color,linewidth =lw ) plt.plot([contourx1, contourx2], [contoury1, contoury1], color,linewidth =lw) plt.plot([contourx1, contourx2], [contoury2, contoury2], color,linewidth =lw) plt.plot([contourx2, contourx2], [contoury1, contoury2], color,linewidth =lw) def drawbox(xcoord,ycoord,width,height,color,w): localx1 = xcoord localx2 = xcoord + width localy1 = ycoord localy2 = ycoord + height drawplot(localx1, localx2, localy1, localy2, color,w) # plot xml boundary plot of dicom image def ParseXMLDrawROI(rootDir,color,width): tree = ET.parse(rootDir) root = tree.getroot() xcoordlist = list() ycoordlist = list() for child in root.iter('string'): if not fnmatch.fnmatch(child.text,'*{*}*'): continue xcoords = str(child.text).split(',')[0] ycoords = str(child.text).split(',')[1] xc = float(xcoords.split('{')[1]) yc = float(ycoords.split('}')[0].replace(' ','')) xcoordlist.append(xc) ycoordlist.append(yc) xcoordlist.append(xcoordlist[0]) ycoordlist.append(ycoordlist[0]) return xcoordlist,ycoordlist # plt.plot(xcoordlist,ycoordlist,color,linewidth = width) # read 2D dicom image def Read2DImage(fileName, rotateAngle=0): rawImage = SimpleITK.ReadImage(fileName) imgArray = SimpleITK.GetArrayFromImage(rawImage) # Convert 3D Image to 2D if len(imgArray.shape) == 3: imgArray = imgArray[0, :, :] return imgArray def GrayScaleNormalization(imgArray, imgMax,imgMin): # try: imgRange = imgMax - imgMin imgArray = (imgArray - imgMin) * (255.0 / imgRange) # transfer to closest int imgArray = np.rint(imgArray).astype(np.int16) # except ValueError: # pass return imgArray dicomImage = Read2DImage(dcmfile) # plt.figure(figsize= (18,13)) plt.figure(figsize=(20,15)) xcoordlist, ycoordlist = ParseXMLDrawROI(xmlfile,'r',2) plt.imshow(dicomImage,cmap='gray') # xcoord = 141 # ycoord = 2332 # width = 180 # height = 161 # xlarge = max(xcoordlist) xsmall = min(xcoordlist) ylarge = max(ycoordlist) ysmall = min(ycoordlist) width = xlarge - xsmall height = ylarge - ysmall drawbox(xsmall,ysmall,width,height,'r',2) # plt.show() imgpath = '/Users/yanzhexu/Desktop/Research/featureMap/Pt50Figures/' title = 'Pt50 LE CC ROI Box' plt.title(title) plt.savefig(imgpath + title + '.png',bbox_inches='tight') plt.cla() plt.close() # plt.scatter(xlist, ylist, c=featurelist, alpha=0.5, cmap='gray') # # plt.imshow(np.transpose(z),alpha= 1,cmap= 'gray') # change interpolation: "bilinear" # # plt.colorbar() # # plt.imshow(ImageArray,alpha=0.6,cmap='gray') # # plt.imshow(ImageArray,alpha = 1, cmap='gray') # # # title = 'Pt1 LE CC' # plt.savefig(imgpath + title + '.png') # plt.cla() # plt.close() # fig, (ax0, ax1) = plt.subplots(ncols=2, # figsize=(12, 4), # sharex=True, # sharey=True, # subplot_kw={"adjustable": "box-forced"}) # En = entropy(subImage, disk(5)) # # print En # # # plt.imshow(En, cmap='gray') # # plt.set_title("Entropy") # # ax1.axis("off") # plt.title('') # plt.tight_layout() #
[ "matplotlib.pyplot.imshow", "matplotlib.pyplot.savefig", "xml.etree.ElementTree.parse", "matplotlib.pyplot.plot", "SimpleITK.GetArrayFromImage", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "fnmatch.fnmatch", "numpy.rint", "SimpleITK.ReadImage", "matplotlib.pyplot.title", "matplotlib...
[((2322, 2350), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 15)'}), '(figsize=(20, 15))\n', (2332, 2350), True, 'import matplotlib.pyplot as plt\n'), ((2408, 2443), 'matplotlib.pyplot.imshow', 'plt.imshow', (['dicomImage'], {'cmap': '"""gray"""'}), "(dicomImage, cmap='gray')\n", (2418, 2443), True, 'import matplotlib.pyplot as plt\n'), ((2812, 2828), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2821, 2828), True, 'import matplotlib.pyplot as plt\n'), ((2829, 2887), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(imgpath + title + '.png')"], {'bbox_inches': '"""tight"""'}), "(imgpath + title + '.png', bbox_inches='tight')\n", (2840, 2887), True, 'import matplotlib.pyplot as plt\n'), ((2887, 2896), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (2894, 2896), True, 'import matplotlib.pyplot as plt\n'), ((2897, 2908), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2906, 2908), True, 'import matplotlib.pyplot as plt\n'), ((405, 482), 'matplotlib.pyplot.plot', 'plt.plot', (['[contourx1, contourx1]', '[contoury1, contoury2]', 'color'], {'linewidth': 'lw'}), '([contourx1, contourx1], [contoury1, contoury2], color, linewidth=lw)\n', (413, 482), True, 'import matplotlib.pyplot as plt\n'), ((488, 565), 'matplotlib.pyplot.plot', 'plt.plot', (['[contourx1, contourx2]', '[contoury1, contoury1]', 'color'], {'linewidth': 'lw'}), '([contourx1, contourx2], [contoury1, contoury1], color, linewidth=lw)\n', (496, 565), True, 'import matplotlib.pyplot as plt\n'), ((570, 647), 'matplotlib.pyplot.plot', 'plt.plot', (['[contourx1, contourx2]', '[contoury2, contoury2]', 'color'], {'linewidth': 'lw'}), '([contourx1, contourx2], [contoury2, contoury2], color, linewidth=lw)\n', (578, 647), True, 'import matplotlib.pyplot as plt\n'), ((652, 729), 'matplotlib.pyplot.plot', 'plt.plot', (['[contourx2, contourx2]', '[contoury1, contoury2]', 'color'], {'linewidth': 'lw'}), '([contourx2, contourx2], [contoury1, contoury2], color, linewidth=lw)\n', (660, 729), True, 'import matplotlib.pyplot as plt\n'), ((1035, 1052), 'xml.etree.ElementTree.parse', 'ET.parse', (['rootDir'], {}), '(rootDir)\n', (1043, 1052), True, 'import xml.etree.ElementTree as ET\n'), ((1751, 1780), 'SimpleITK.ReadImage', 'SimpleITK.ReadImage', (['fileName'], {}), '(fileName)\n', (1770, 1780), False, 'import SimpleITK\n'), ((1796, 1833), 'SimpleITK.GetArrayFromImage', 'SimpleITK.GetArrayFromImage', (['rawImage'], {}), '(rawImage)\n', (1823, 1833), False, 'import SimpleITK\n'), ((1182, 1218), 'fnmatch.fnmatch', 'fnmatch.fnmatch', (['child.text', '"""*{*}*"""'], {}), "(child.text, '*{*}*')\n", (1197, 1218), False, 'import fnmatch\n'), ((2155, 2172), 'numpy.rint', 'np.rint', (['imgArray'], {}), '(imgArray)\n', (2162, 2172), True, 'import numpy as np\n')]
#Problema "FizzBuzz" #Para cada um dos numeros de 1 a 100 escreva: #"Fizz" se divisivel por 3, #"Buzz" se divisivel por 5, #"FizzBuzz" se divisivel por 15, # apenas o numero nos outros casos. from typing import List import numpy as np from dasxlib.train import train from dasxlib.nn import NeuralNet from dasxlib.layers import Linear, Tanh from dasxlib.optim import SGD def fizz_buzz_encode(x: int) -> List[int]: if x % 15 == 0: return [0, 0, 0, 1] elif x % 5 == 0: return [0, 0, 1, 0] elif x % 3 == 0: return [0, 1, 0, 0] else: return [1, 0, 0, 0] def binary_encode(x: int) -> List[int]: #codificação binária por 10 return [x >> i & 1 for i in range(10)] inputs = np.array([ binary_encode(x) for x in range(101, 1024) ]) targets = np.array([ fizz_buzz_encode(x) for x in range(101, 1024) ]) net = NeuralNet([ Linear(input_size=10, output_size=50), Tanh(), Linear(input_size=50, output_size=4) ]) train(net, inputs, targets, num_epochs=5000, optimizer=SGD(lr=0.001)) for x in range(1, 101): predicted = net.forward(binary_encode(x)) predicted_index = np.argmax(predicted) actual_index = np.argmax(fizz_buzz_encode(x)) labels = [str(x), "Fizz", "Buzz", "FizzBuzz"] print(x, labels[predicted_index], labels[actual_index])
[ "dasxlib.layers.Tanh", "dasxlib.layers.Linear", "numpy.argmax", "dasxlib.optim.SGD" ]
[((1185, 1205), 'numpy.argmax', 'np.argmax', (['predicted'], {}), '(predicted)\n', (1194, 1205), True, 'import numpy as np\n'), ((894, 931), 'dasxlib.layers.Linear', 'Linear', ([], {'input_size': '(10)', 'output_size': '(50)'}), '(input_size=10, output_size=50)\n', (900, 931), False, 'from dasxlib.layers import Linear, Tanh\n'), ((937, 943), 'dasxlib.layers.Tanh', 'Tanh', ([], {}), '()\n', (941, 943), False, 'from dasxlib.layers import Linear, Tanh\n'), ((949, 985), 'dasxlib.layers.Linear', 'Linear', ([], {'input_size': '(50)', 'output_size': '(4)'}), '(input_size=50, output_size=4)\n', (955, 985), False, 'from dasxlib.layers import Linear, Tanh\n'), ((1077, 1090), 'dasxlib.optim.SGD', 'SGD', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (1080, 1090), False, 'from dasxlib.optim import SGD\n')]
################################ ########### Imports ############ ################################ import sys #sys.path.append('../python/') import NGC5533_functions as nf import noordermeer as noord # Traced data of Galaxy NGC 5533 import numpy as np import matplotlib.pyplot as plt import lmfit as lm import dataPython as dp import scipy.interpolate as inter ################################ ##### Measured data points ##### ################################ data = dp.getXYdata_wXYerr('../data/100kpc_data.txt') #data = dp.getXYdata_wXYerr('../galactic-spin-binder/NGC_5533/data/final/100kpc_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']) ########################################### ###### Uncertainty Band and Weights ####### ########################################### # Uncertainty band, using Noordermeer's function with a guessed delta_i delta_i = 3 # guessed value v_i = (v_dat / np.tan(52*(np.pi/180)) * delta_i *(np.pi/180)) # Traced uncertainty band band = noord.band greyb_bottom = noord.greyb_bottom greyb_top = noord.greyb_top #change r_dat so it's strictly increasing r_dat, v_dat, v_err0, v_err1 = (np.asarray(list(a)) for a in zip(*sorted(zip(r_dat, v_dat, v_err0, v_err1)))) #converting v_err1 to an array v_err1_array = np.asarray(v_err1) # Express as weights #weighdata = 1/(np.sqrt((v_err1**2)+(v_i**2))) weighdata = 1/(np.sqrt((v_err1**2)+(band**2))) ################################ ########## Function ############ ################################ r = np.arange(0.1,200,0.1) def f(r,M,rc,rho00,c,pref,gpref): return np.sqrt(nf.bh_v(r,M,load=False)**2 + nf.h_v(r,rc,rho00,load=False)**2 + c**2*nf.b_v(r,load=True,path='../')**2 + pref**2*nf.d_thief(r)**2 + gpref**2*nf.g_thief(r)**2) ########################################## ########## Fitting Parameters ############ ########################################## # Setup f_mod = lm.Model(f) f_params = f_mod.make_params() # Black Hole f_params.add('M', value=nf.Mbh_def, min=1.0e8) #Mass # Halo f_params.add('rc', value=nf.h_rc, min=0.1) #Core Radius (kpc) f_params.add('rho00', value=nf.hrho00_c, min=0) #Halo Density # Bulge f_params.add('c', value=1,min=0,max=100) #Prefactor # Disk f_params.add('pref', value=1,min=0, max=100) #Prefactor # Gas f_params.add('gpref', value=1, vary=False) #Prefactor # Do fit f_fit = f_mod.fit(v_dat,f_params,r=r_dat,weights=weighdata) ########################################## ########## Define for Plotting ########### ########################################## bestf = f_fit.best_fit #delf = f_fit.eval_uncertainty() f_dict = f_fit.best_values f_M = f_dict['M'] f_c = f_dict['c'] f_pref = f_dict['pref'] f_rc = f_dict['rc'] f_hrho00 = f_dict['rho00'] f_gpref = f_dict['gpref'] f_curve = f(r,f_M,f_rc,f_hrho00,f_c,f_pref,f_gpref) bh_curve = nf.bh_v(r,f_M,load=False) halo_curve = nf.h_v(r,f_rc,f_hrho00,load=False) bulge_curve = f_c*nf.b_v(r,load=True) disk_curve = f_pref*nf.d_thief(r) gas_curve = f_gpref*nf.g_thief(r)
[ "lmfit.Model", "numpy.sqrt", "NGC5533_functions.b_v", "numpy.tan", "numpy.asarray", "NGC5533_functions.bh_v", "dataPython.getXYdata_wXYerr", "NGC5533_functions.d_thief", "NGC5533_functions.h_v", "numpy.arange", "NGC5533_functions.g_thief" ]
[((485, 531), 'dataPython.getXYdata_wXYerr', 'dp.getXYdata_wXYerr', (['"""../data/100kpc_data.txt"""'], {}), "('../data/100kpc_data.txt')\n", (504, 531), True, 'import dataPython as dp\n'), ((631, 653), 'numpy.asarray', 'np.asarray', (["data['xx']"], {}), "(data['xx'])\n", (641, 653), True, 'import numpy as np\n'), ((662, 684), 'numpy.asarray', 'np.asarray', (["data['yy']"], {}), "(data['yy'])\n", (672, 684), True, 'import numpy as np\n'), ((694, 716), 'numpy.asarray', 'np.asarray', (["data['ex']"], {}), "(data['ex'])\n", (704, 716), True, 'import numpy as np\n'), ((726, 748), 'numpy.asarray', 'np.asarray', (["data['ey']"], {}), "(data['ey'])\n", (736, 748), True, 'import numpy as np\n'), ((1355, 1373), 'numpy.asarray', 'np.asarray', (['v_err1'], {}), '(v_err1)\n', (1365, 1373), True, 'import numpy as np\n'), ((1594, 1618), 'numpy.arange', 'np.arange', (['(0.1)', '(200)', '(0.1)'], {}), '(0.1, 200, 0.1)\n', (1603, 1618), True, 'import numpy as np\n'), ((2056, 2067), 'lmfit.Model', 'lm.Model', (['f'], {}), '(f)\n', (2064, 2067), True, 'import lmfit as lm\n'), ((2997, 3024), 'NGC5533_functions.bh_v', 'nf.bh_v', (['r', 'f_M'], {'load': '(False)'}), '(r, f_M, load=False)\n', (3004, 3024), True, 'import NGC5533_functions as nf\n'), ((3036, 3073), 'NGC5533_functions.h_v', 'nf.h_v', (['r', 'f_rc', 'f_hrho00'], {'load': '(False)'}), '(r, f_rc, f_hrho00, load=False)\n', (3042, 3073), True, 'import NGC5533_functions as nf\n'), ((1457, 1489), 'numpy.sqrt', 'np.sqrt', (['(v_err1 ** 2 + band ** 2)'], {}), '(v_err1 ** 2 + band ** 2)\n', (1464, 1489), True, 'import numpy as np\n'), ((3089, 3109), 'NGC5533_functions.b_v', 'nf.b_v', (['r'], {'load': '(True)'}), '(r, load=True)\n', (3095, 3109), True, 'import NGC5533_functions as nf\n'), ((3129, 3142), 'NGC5533_functions.d_thief', 'nf.d_thief', (['r'], {}), '(r)\n', (3139, 3142), True, 'import NGC5533_functions as nf\n'), ((3163, 3176), 'NGC5533_functions.g_thief', 'nf.g_thief', (['r'], {}), '(r)\n', (3173, 3176), True, 'import NGC5533_functions as nf\n'), ((1002, 1028), 'numpy.tan', 'np.tan', (['(52 * (np.pi / 180))'], {}), '(52 * (np.pi / 180))\n', (1008, 1028), True, 'import numpy as np\n'), ((1891, 1904), 'NGC5533_functions.g_thief', 'nf.g_thief', (['r'], {}), '(r)\n', (1901, 1904), True, 'import NGC5533_functions as nf\n'), ((1844, 1857), 'NGC5533_functions.d_thief', 'nf.d_thief', (['r'], {}), '(r)\n', (1854, 1857), True, 'import NGC5533_functions as nf\n'), ((1671, 1696), 'NGC5533_functions.bh_v', 'nf.bh_v', (['r', 'M'], {'load': '(False)'}), '(r, M, load=False)\n', (1678, 1696), True, 'import NGC5533_functions as nf\n'), ((1720, 1752), 'NGC5533_functions.h_v', 'nf.h_v', (['r', 'rc', 'rho00'], {'load': '(False)'}), '(r, rc, rho00, load=False)\n', (1726, 1752), True, 'import NGC5533_functions as nf\n'), ((1780, 1812), 'NGC5533_functions.b_v', 'nf.b_v', (['r'], {'load': '(True)', 'path': '"""../"""'}), "(r, load=True, path='../')\n", (1786, 1812), True, 'import NGC5533_functions as nf\n')]
import pandas as pd import numpy as np import argparse import h5py import re from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.models import load_model from keras.utils import to_categorical from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from scipy.sparse import load_npz from models.supervised import RNN, EnrichedLSTM import metrics.classification as mc def parse_arguments(parser): parser.add_argument('--data_dir', type=str, default=None, help='the directory holding the data files') parser.add_argument('--text_file', type=str, default='word_sents.hdf5', help='the HDF5 file holding the integer sentences') parser.add_argument('--records_npz', type=str, default='sparse_records.npz', help='the NPZ file holding the sparsified variables') parser.add_argument('--records_csv', type=str, default='records_clipped.csv', help='the CSV holding the original dataset') parser.add_argument('--target_column', type=str, default='code', help='the target column in the original dataset') parser.add_argument('--train_batch_size', type=int, default=256, help='minibatch size to use for training') parser.add_argument('--pred_batch_size', type=int, default=256, help='minibatch size to use for inference') parser.add_argument('--epochs', type=int, default=10, help='number of epochs to use for training') parser.add_argument('--train_size', type=float, default=0.5, help='proportion of data to use for training') parser.add_argument('--patience', type=int, default=5, help='patience hyperparameter for Keras') parser.add_argument('--seed', type=int, default=10221983, help='seed to use for splitting the data') parser.add_argument('--enrichment_method', type=str, default='init', choices=['word', 'init', 'post'], help='method for encriching the LSTM') args = parser.parse_args() return args if __name__ == '__main__': parser = argparse.ArgumentParser() args = parse_arguments(parser) # Importing the integer sequences int_sents = h5py.File(args.data_dir + args.text_file, mode='r') X = np.array(int_sents['sents']) int_sents.close() # Importing the sparse records and targets sparse_records = load_npz(args.data_dir + args.records_npz) records = pd.read_csv(args.data_dir + args.records_csv) # Making a variable for the classification target y_base = records[args.target_column].astype(int) num_classes = len(np.unique(y_base)) y = to_categorical(y_base, num_classes=num_classes, dtype=int) if y.shape[1] == 2: num_classes = 1 loss = 'binary_crossentropy' else: num_classes = y.shape[1] loss = 'categorical_crossentropy' # Importing the vocabulary vocab_df = pd.read_csv(args.data_dir + 'word_dict.csv') vocab = dict(zip(vocab_df.word, vocab_df.value)) # Defining the shared hyperparameters V = len(vocab) fit_batch = args.train_batch_size pred_batch = args.pred_batch_size epochs = args.epochs max_length = X.shape[1] vocab_size = len(vocab.keys()) seed = args.seed patience = args.patience # Hyperparameters for the LSTM rnn_e_size = 256 rnn_h_size = 256 rnn_e_drop = 0.75 rnn_r_drop = 0.25 rnn_f_drop = 0.00 # Hyperparameters for the multimodal model sparse_size = sparse_records.shape[1] ehr_dense_size = 256 ehr_e_size = 256 ehr_e_drop = 0.85 ehr_r_drop = 0.00 # Splitting the data train, not_train = train_test_split(list(range(X.shape[0])), test_size=.5, stratify=y, random_state=seed) val, test = train_test_split(not_train, test_size=.3, stratify=y[not_train], random_state=seed) # Training the encoder-decoder EHR model ehr_modname = args.enrichment_method ehr_modpath = args.data_dir + ehr_modname + '.hdf5' ehr = EnrichedLSTM(sparse_size, vocab_size, max_length, method=args.enrichment_method, output_size=num_classes, embedding_size=ehr_e_size, hidden_size=ehr_dense_size, embeddings_dropout=ehr_e_drop, recurrent_dropout=ehr_r_drop) ehr_check = ModelCheckpoint(filepath=ehr_modpath, save_best_only=True, verbose=1) ehr_stop = EarlyStopping(monitor='val_loss', patience=patience) ehr.compile(loss=loss, optimizer='adam') ehr.fit([sparse_records[train], X[train]], y[train], batch_size=fit_batch, verbose=1, epochs=epochs, validation_data=([sparse_records[val], X[val]], y[val]), callbacks=[ehr_check, ehr_stop]) ehr = load_model(ehr_modpath) # Loading the trained EHR model and getting the predictions ehr_test_preds = ehr.predict([sparse_records[test], X[test]], batch_size=fit_batch).argmax(axis=1) pd.DataFrame(ehr_test_preds).to_csv(args.data_dir + 'preds.csv', index=False) f1 = f1_score(y_base[test], ehr_test_preds, average='macro') print('Weighted macro F1 score is ' + str(f1))
[ "sklearn.metrics.f1_score", "keras.models.load_model", "numpy.unique", "pandas.read_csv", "argparse.ArgumentParser", "sklearn.model_selection.train_test_split", "scipy.sparse.load_npz", "keras.callbacks.ModelCheckpoint", "h5py.File", "keras.utils.to_categorical", "numpy.array", "models.supervi...
[((2283, 2308), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2306, 2308), False, 'import argparse\n'), ((2403, 2454), 'h5py.File', 'h5py.File', (['(args.data_dir + args.text_file)'], {'mode': '"""r"""'}), "(args.data_dir + args.text_file, mode='r')\n", (2412, 2454), False, 'import h5py\n'), ((2463, 2491), 'numpy.array', 'np.array', (["int_sents['sents']"], {}), "(int_sents['sents'])\n", (2471, 2491), True, 'import numpy as np\n'), ((2587, 2629), 'scipy.sparse.load_npz', 'load_npz', (['(args.data_dir + args.records_npz)'], {}), '(args.data_dir + args.records_npz)\n', (2595, 2629), False, 'from scipy.sparse import load_npz\n'), ((2644, 2689), 'pandas.read_csv', 'pd.read_csv', (['(args.data_dir + args.records_csv)'], {}), '(args.data_dir + args.records_csv)\n', (2655, 2689), True, 'import pandas as pd\n'), ((2851, 2909), 'keras.utils.to_categorical', 'to_categorical', (['y_base'], {'num_classes': 'num_classes', 'dtype': 'int'}), '(y_base, num_classes=num_classes, dtype=int)\n', (2865, 2909), False, 'from keras.utils import to_categorical\n'), ((3131, 3175), 'pandas.read_csv', 'pd.read_csv', (["(args.data_dir + 'word_dict.csv')"], {}), "(args.data_dir + 'word_dict.csv')\n", (3142, 3175), True, 'import pandas as pd\n'), ((4118, 4206), 'sklearn.model_selection.train_test_split', 'train_test_split', (['not_train'], {'test_size': '(0.3)', 'stratify': 'y[not_train]', 'random_state': 'seed'}), '(not_train, test_size=0.3, stratify=y[not_train],\n random_state=seed)\n', (4134, 4206), False, 'from sklearn.model_selection import train_test_split\n'), ((4458, 4692), 'models.supervised.EnrichedLSTM', 'EnrichedLSTM', (['sparse_size', 'vocab_size', 'max_length'], {'method': 'args.enrichment_method', 'output_size': 'num_classes', 'embedding_size': 'ehr_e_size', 'hidden_size': 'ehr_dense_size', 'embeddings_dropout': 'ehr_e_drop', 'recurrent_dropout': 'ehr_r_drop'}), '(sparse_size, vocab_size, max_length, method=args.\n enrichment_method, output_size=num_classes, embedding_size=ehr_e_size,\n hidden_size=ehr_dense_size, embeddings_dropout=ehr_e_drop,\n recurrent_dropout=ehr_r_drop)\n', (4470, 4692), False, 'from models.supervised import RNN, EnrichedLSTM\n'), ((4880, 4949), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'ehr_modpath', 'save_best_only': '(True)', 'verbose': '(1)'}), '(filepath=ehr_modpath, save_best_only=True, verbose=1)\n', (4895, 4949), False, 'from keras.callbacks import ModelCheckpoint, EarlyStopping\n'), ((5029, 5081), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': 'patience'}), "(monitor='val_loss', patience=patience)\n", (5042, 5081), False, 'from keras.callbacks import ModelCheckpoint, EarlyStopping\n'), ((5421, 5444), 'keras.models.load_model', 'load_model', (['ehr_modpath'], {}), '(ehr_modpath)\n', (5431, 5444), False, 'from keras.models import load_model\n'), ((5782, 5837), 'sklearn.metrics.f1_score', 'f1_score', (['y_base[test]', 'ehr_test_preds'], {'average': '"""macro"""'}), "(y_base[test], ehr_test_preds, average='macro')\n", (5790, 5837), False, 'from sklearn.metrics import f1_score\n'), ((2824, 2841), 'numpy.unique', 'np.unique', (['y_base'], {}), '(y_base)\n', (2833, 2841), True, 'import numpy as np\n'), ((5654, 5682), 'pandas.DataFrame', 'pd.DataFrame', (['ehr_test_preds'], {}), '(ehr_test_preds)\n', (5666, 5682), True, 'import pandas as pd\n')]
# %load runDM.py """ runDM version 1.0 [Python implementation] Calculate low energy DM-SM couplings from high energy couplings, taking into account RG evolution due to SM loops. See arXiv:1605.04917 for further details. Please contact <NAME> (<EMAIL>) for any questions, problems, bugs and suggestions. """ from __future__ import print_function import numpy as np from scipy import linalg from scipy.interpolate import interp1d import sys #-------------Initialisation--------------- #------------------------------------------ mZ = 91.1875 #Z-mass in GeV mN = 0.938 #Nucleon mass in GeV EvolutionSM = np.zeros([16,16,1401]) EvolutionEMSM = np.zeros([16,16,453]) #Pre-calculated values of t = Log[m_V/m_Z] t_SM = np.linspace(0, 14, 1401) t_EMSM = np.append(np.linspace(-4.51, 0.0,452)-0.003, 0) #Load in the evolution tables for i in range(1401): #Truncate to a few decimal places, to prevent rounding errors in the filenames s = str(np.around(t_SM[i], 3)) if (t_SM[i] == int(t_SM[i])): s = str(int(t_SM[i])) EvolutionSM[:,:,i] = np.loadtxt('data/EvolutionSM_t=' + s + '.dat') for i in range(453): #Truncate to a few decimal places, to prevent rounding errors in the filenames s = str(np.around(t_EMSM[i], 3)) if (t_EMSM[i] == int(t_EMSM[i])): s = str(int(t_EMSM[i])) EvolutionEMSM[:,:,i] = np.loadtxt('data/EvolutionEMSM_t=' + s + '.dat') Umatch = np.loadtxt('data/Umatch.dat') #Correct the value of t_EMSM slightly # (because Log(1/mZ)~-4.51292) t_EMSM[:-1] = t_EMSM[:-1]+0.00008 #Define interpolating functions UevolutionABOVE = interp1d(t_SM, EvolutionSM) UevolutionBELOW = interp1d(t_EMSM, EvolutionEMSM) #------------------------------------------ #%% Initialise empty coupling vector def initCouplings(): """ initCouplings() Returns a numpy array with 16 elements, all set to zero, for use in initialising coupling vectors. """ return np.zeros(16) #%% Generate coupling vectors with preset operator structures def setBenchmark(benchmarkID): """ setBenchmark(benchmarkID) Returns a numpy array with 16 elements, corresponding to the vector of couplings defined in Eq. 4 of the runDM manual. The value of the couplings is defined by the string benchmarkID. Possible choices for benchmarkID are: 'Higgs', 'UniversalVector', 'UniversalAxial', 'QuarksVector', 'QuarksAxial', 'LeptonsVector', 'LeptonsAxial', 'ThirdVector', 'ThirdAxial' """ if (benchmarkID == "Higgs"): return np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0]) elif (benchmarkID == "UniversalVector"): return np.array([1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0]) elif (benchmarkID == "UniversalAxial"): return np.array([-1.0,1.0,1.0,-1.0,1.0,-1.0,1.0,1.0,-1.0,1.0,-1.0,1.0,1.0,-1.0,1.0,0.0]) elif (benchmarkID == "QuarksVector"): return np.array([1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0]) elif (benchmarkID == "QuarksAxial"): return np.array([-1.0,1.0,1.0,0.0,0.0,-1.0,1.0,1.0,0.0,0.0,-1.0,1.0,1.0,0.0,0.0,0.0]) elif (benchmarkID == "LeptonsVector"): return np.array([0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0]) elif (benchmarkID == "LeptonsAxial"): return np.array([0.0,0.0,0.0,-1.0,1.0,0.0,0.0,0.0,-1.0,1.0,0.0,0.0,0.0,-1.0,1.0,0.0]) elif (benchmarkID == "ThirdVector"): return np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0]) elif (benchmarkID == "ThirdAxial"): return np.array([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-1.0,1.0,1.0,-1.0,1.0,0.0]) else: print(" Error in runDM.setbenchmark: benchmarkID <<", benchmarkID, ">> not found...") print(" Options are: 'Higgs', 'UniversalVector', 'UniversalAxial', 'QuarksVector', 'QuarksAxial', 'LeptonsVector', 'LeptonsAxial', 'ThirdVector', 'ThirdAxial'...") print(" Returning empty coupling vector...") return np.zeros(16) #%% Calculate matrix to evolve couplings def evolutionMat(E1, E2): """ evolutionMat(E1, E2) Calculate 16x16 matrix for evolving coupling vector between energies E1 and E2 (in GeV). evolutionMat takes care of the relative values of E1 and E2. Requires E1, E2 in range [1, 1e8] GeV. Note that evolutionMat is NOT vectorized - it can only accept floats for E1 and E2. Input: E1 - energy to start from (in GeV) E2 - energy to run to (in GeV) Output: Returns a 16x16 numpy array containing the evolution matrix """ #Check to see if E1 or E2 is a list if ((hasattr(E1, "__len__"))or(hasattr(E2,"__len__"))): sys.exit(" Error in runDM.evolutionMat: E1 and E2 must both be floats") t1 = np.log(E1/mZ) t2 = np.log(E2/mZ) #Check ranges of t1 and t2 if not(np.log(1.0/mZ) <= t1 <= 14.0): sys.exit(" Error in runDM.evolutionMat: E1 out of range. Require 1 GeV <= E1 <= 1e8 GeV") if not(np.log(1.0/mZ) <= t2 <= 14.0): sys.exit(" Error in runDM.evolutionMat: E2 out of range. Require 1 GeV <= E2 <= 1e8 GeV") #Both energies below the Z-mass if ((t1 <= 0)and(t2 <= 0)): Emat = np.dot(np.dot(linalg.inv(UevolutionBELOW(t2)), UevolutionBELOW(t1)),Umatch) #Both energies above the Z-mass if ((t1 >= 0)and(t2 >= 0)): Emat = np.dot(linalg.inv(UevolutionABOVE(t2)), UevolutionABOVE(t1)) #Energies either side of the Z-mass if ((t1 >= 0)and(t2 <= 0)): EmatBELOW = np.dot(linalg.inv(UevolutionBELOW(t2)), UevolutionBELOW(0)) Emat = np.dot(EmatBELOW, np.dot(Umatch, UevolutionABOVE(t1))) #Energies either side of Z-mass (in wrong order) if ((t1 < 0)and(t2 > 0)): sys.exit(" Error in runDM.evolutionMat: E1 < mZ, E2 > mZ not supported - matching is not unique.") return Emat #%% Evolve couplings between E1 and E2 def runCouplings(c, E1, E2): """ runCouplings(c, E1, E2) Calculate running of couplings c between two energies E1 and E2. If E2 > mZ, the output is an array of couplings in the EW-unbroken phase (Eq. 4 of the manual). If E2 < mZ, the output is an array of couplings in the EW-broken phase (Eq. 6 of the manual). Note that E1 < mZ with E2 > mZ is not allowed. Input: c - numpy array with 16 elements, with values corresponding to those defined in Eq. 4 of the runDM manual E1 - energy (in GeV) at which c is defined. E1 may be a scalar or a 1-d numpy array. E2 - energy (in GeV) to run to. E2 may be a scalar or 1-d numpy array (with same length as E1). Output: Returns array with length 16 in the final dimension (corresponding either to Eq. 4 or Eq. 6 of the manual). The full dimensions of the array will be (Len(E1), 16). """ #Check length of coupling vector c if not(hasattr(c, "__len__")): sys.exit(" Error in runDM.runCouplings: c must be an array with 16 elements") if (len(c) != 16): sys.exit(" Error in runDM.runCouplings: c must be an array with 16 elements") #If E1 and E2 are scalar if not((hasattr(E1, "__len__"))or(hasattr(E2,"__len__"))): return np.dot(evolutionMat(E1, E2), c) #If E1 or E2 are arrays, need to check to make sure correct #array dimensions are returned #Both E1, E2 are arrays (check they are same length...) if ((hasattr(E1, "__len__"))and(hasattr(E2, "__len__"))): n1 = len(E1) if (len(E2) != n1): sys.exit(" Error in runDM.runCouplings: E1 and E2 must have same length (or be scalar)") else: result = np.zeros([n1,16]) for i in range(n1): result[:, i] = np.dot(evolutionMat(E1[i], E2[i]), c) #Only E1 is an array elif (hasattr(E1, "__len__")): n1 = len(E1) result = np.zeros([n1,16]) for i in range(n1): result[:, i] = np.dot(evolutionMat(E1[i], E2), c) #Only E2 is an array elif (hasattr(E2, "__len__")): n2 = len(E2) result = np.zeros([n2,16]) for i in range(n2): result[i, :] = np.dot(evolutionMat(E1, E2[i]), c) return result #%% Calculate couplings to light quarks at the nuclear scale def DDCouplingsQuarks(c, E1): """ DDCouplingsQuarks(c, E1) Calculate vector (V) and axial-vector (A) couplings to u, d, s quarks at the nuclear energy scale starting from the high energy coupling vector c, defined at energy E1 (in GeV). Input: c - numpy array with 16 elements, with values corresponding to those defined in Eq. 4 of the runDM manual E1 - energy (in GeV) at which c is defined. E1 may be a scalar or a 1-d numpy array. Output: Returns array with length 5 in the final dimension, corresponding to (CVu, CVd, CAu, CAd, CAs). The dimensions of the array will be (Len(E1), 5). """ #Check length of coupling vector c if not(hasattr(c, "__len__")): sys.exit(" Error in runDM.runCouplings: c must be an array with 16 elements") if (len(c) != 16): sys.exit(" Error in runDM.runCouplings: c must be an array with 16 elements") #If E1 is scalar if not(hasattr(E1, "__len__")): return runCouplings(c, E1, 1.0)[[0,1,8,9,11]] #If E1 is an array else: n1 = len(E1) result = np.zeros([n1,5]) for i in range(n1): result[i,:] = runCouplings(c, E1[i], 1.0)[[0,1,8,9,11]] return result #%% Calculate non-relativistic couplings to protons def DDCouplingsProton(c, E1, mx, DMcurrent): #From quarks to nucleons #Values from arXiv:1202.1292 deltau_p = 0.84 deltad_p = -0.44 deltas_p = -0.03 #Get quark couplings cuV, cdV, cuA, cdA, csA = DDCouplingsQuarks(c, E1) #Calculate non-relativistic proton couplings #Note the number of operators is shifted by 1 #because python uses zero-indexed arrays lambda_p = np.zeros(12) if (DMcurrent == "scalar"): lambda_p[0] = 4*mx*mN*(2*cuV+ cdV) lambda_p[6] = -8*mx*mN*(deltau_p*cuA + deltad_p*cdA + deltas_p*csA) elif (DMcurrent == "vector"): lambda_p[0] = 4*mx*mN *(2*cuV + cdV) lambda_p[6] = -8*mx*mN*(deltau_p*cuA + deltad_p*cdA + deltas_p*csA) lambda_p[8] = 8*mN*(deltau_p*cuA + deltad_p*cdA + deltas_p*csA) elif (DMcurrent == "axial-vector"): lambda_p[3] = -16*mx*mN*(deltau_p*cuA + deltad_p*cdA + deltas_p*csA) lambda_p[7] = 8*mx*mN*(2*cuV + cdV) lambda_p[8] = 8*mx*(2*cuV + cdV) return lambda_p/E1**2 #%% Calculate non-relativistic couplings to neutrons def DDCouplingsNeutron(c, E1, mx, DMcurrent): #From quarks to nucleons #Values from arXiv:1202.1292 deltau_p = 0.84 deltad_p = -0.44 deltas_p = -0.03 #Get quark couplings cuV, cdV, cuA, cdA, csA = DDCouplingsQuarks(c, E1) #Calculate non-relativistic neutron couplings #Note the number of operators is shifted by 1 #because python uses zero-indexed arrays lambda_n = np.zeros(12) if (DMcurrent == "scalar"): lambda_n[0] = 4*mx*mN*(cuV + 2*cdV) lambda_n[6] = -8*mx*mN*(deltad_p*cuA + deltau_p*cdA + deltas_p*csA) elif (DMcurrent == "vector"): lambda_n[0] = 4*mx*mN*(cuV + 2*cdV) lambda_n[6] = -8*mx*mN*(deltad_p*cuA + deltau_p*cdA + deltas_p*csA) lambda_n[8] = 8*mN*(deltad_p*cuA + deltau_p*cdA + deltas_p*csA) elif (DMcurrent == "axial-vector"): lambda_n[3] = -16*mx*mN*(deltad_p*cuA + deltau_p*cdA + deltas_p*csA) lambda_n[7] = 8*mx*mN*(cuV + 2*cdV) lambda_n[8] = 8*mx*(cuV + 2.0*cdV) return lambda_n/E1**2 #%% Calculate non-relativistic couplings to nucleons def DDCouplingsNR(c, E1, mx, DMcurrent, N): """ DDCouplingsNR(c, E1, mx, DMcurrent, N) Calculate coefficients of the non-relativistic DM-nucleon operators at the nuclear energy scale, with numbering as in arXiv:1307.5955, taking into account running of the couplings from high energy E1 (in GeV). The result will depend on the structure of the DM interaction and on the DM mass. Input: c - vector with 16 elements, with values corresponding to those defined in Eq. 4 of the runDM manual E1 - energy (in GeV) at which c is defined. E1 may be a scalar or an array. mx - DM mass in GeV. mx must be a single number. DMcurrent - string specifying the DM interaction current. The options are 'scalar', 'vector' and 'axial-vector'. The corresponding definitions of the DM currents are given in Eq. 8 of the manual. N - string specifying the nucleon type: 'p' for proton, 'n' for neutron. Output: Returns array with length 12 in the final dimension, corresponding to the coefficients of the first 12 non-relativistic DM-nucleon operators listed in arXiv:1307.5955. The coefficients include a factor of 1/E1^2. The dimensions of the array will be (Len(E1), 12)." """ #Check parameter values if N not in ("p", "n"): sys.exit(" Error in runDM.DDCouplingsNR: N must be either 'p' or 'n'.") if DMcurrent not in ("scalar", "vector", "axial-vector"): sys.exit(" Error in runDM.DDCouplingsNR: DMcurrent must be 'scalar', 'vector' or 'axial-vector'.") #Check length of coupling vector c if not(hasattr(c, "__len__")): sys.exit(" Error in runDM.DDCouplingsNR: c must be an array with 16 elements") if (len(c) != 16): sys.exit(" Error in runDM.DDCouplingsNR: c must be an array with 16 elements") #Check that mx is a single number if hasattr(mx, "__len__"): sys.exit(" Error in runDM.DDCouplingsNR: mx must be a single number.") #Determine nucleon type if (N == "p"): DDfunc = lambda E: DDCouplingsProton(c, E, mx, DMcurrent) elif (N == "n"): DDfunc = lambda E: DDCouplingsNeutron(c, E, mx, DMcurrent) #If E1 is scalar if not(hasattr(E1, "__len__")): return DDfunc(E1) #If E1 is an array else: n1 = len(E1) result = np.zeros([n1,12]) for i in range(n1): result[i,:] = DDfunc(E1[i]) return result
[ "numpy.log", "scipy.interpolate.interp1d", "numpy.array", "numpy.zeros", "numpy.linspace", "numpy.around", "sys.exit", "numpy.loadtxt" ]
[((607, 631), 'numpy.zeros', 'np.zeros', (['[16, 16, 1401]'], {}), '([16, 16, 1401])\n', (615, 631), True, 'import numpy as np\n'), ((646, 669), 'numpy.zeros', 'np.zeros', (['[16, 16, 453]'], {}), '([16, 16, 453])\n', (654, 669), True, 'import numpy as np\n'), ((719, 743), 'numpy.linspace', 'np.linspace', (['(0)', '(14)', '(1401)'], {}), '(0, 14, 1401)\n', (730, 743), True, 'import numpy as np\n'), ((1407, 1436), 'numpy.loadtxt', 'np.loadtxt', (['"""data/Umatch.dat"""'], {}), "('data/Umatch.dat')\n", (1417, 1436), True, 'import numpy as np\n'), ((1593, 1620), 'scipy.interpolate.interp1d', 'interp1d', (['t_SM', 'EvolutionSM'], {}), '(t_SM, EvolutionSM)\n', (1601, 1620), False, 'from scipy.interpolate import interp1d\n'), ((1639, 1670), 'scipy.interpolate.interp1d', 'interp1d', (['t_EMSM', 'EvolutionEMSM'], {}), '(t_EMSM, EvolutionEMSM)\n', (1647, 1670), False, 'from scipy.interpolate import interp1d\n'), ((1062, 1108), 'numpy.loadtxt', 'np.loadtxt', (["('data/EvolutionSM_t=' + s + '.dat')"], {}), "('data/EvolutionSM_t=' + s + '.dat')\n", (1072, 1108), True, 'import numpy as np\n'), ((1348, 1396), 'numpy.loadtxt', 'np.loadtxt', (["('data/EvolutionEMSM_t=' + s + '.dat')"], {}), "('data/EvolutionEMSM_t=' + s + '.dat')\n", (1358, 1396), True, 'import numpy as np\n'), ((1931, 1943), 'numpy.zeros', 'np.zeros', (['(16)'], {}), '(16)\n', (1939, 1943), True, 'import numpy as np\n'), ((4890, 4905), 'numpy.log', 'np.log', (['(E1 / mZ)'], {}), '(E1 / mZ)\n', (4896, 4905), True, 'import numpy as np\n'), ((4913, 4928), 'numpy.log', 'np.log', (['(E2 / mZ)'], {}), '(E2 / mZ)\n', (4919, 4928), True, 'import numpy as np\n'), ((10264, 10276), 'numpy.zeros', 'np.zeros', (['(12)'], {}), '(12)\n', (10272, 10276), True, 'import numpy as np\n'), ((11355, 11367), 'numpy.zeros', 'np.zeros', (['(12)'], {}), '(12)\n', (11363, 11367), True, 'import numpy as np\n'), ((763, 791), 'numpy.linspace', 'np.linspace', (['(-4.51)', '(0.0)', '(452)'], {}), '(-4.51, 0.0, 452)\n', (774, 791), True, 'import numpy as np\n'), ((950, 971), 'numpy.around', 'np.around', (['t_SM[i]', '(3)'], {}), '(t_SM[i], 3)\n', (959, 971), True, 'import numpy as np\n'), ((1226, 1249), 'numpy.around', 'np.around', (['t_EMSM[i]', '(3)'], {}), '(t_EMSM[i], 3)\n', (1235, 1249), True, 'import numpy as np\n'), ((2539, 2634), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0\n ]'], {}), '([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n 0.0, 0.0, 1.0])\n', (2547, 2634), True, 'import numpy as np\n'), ((4787, 4858), 'sys.exit', 'sys.exit', (['""" Error in runDM.evolutionMat: E1 and E2 must both be floats"""'], {}), "(' Error in runDM.evolutionMat: E1 and E2 must both be floats')\n", (4795, 4858), False, 'import sys\n'), ((5013, 5112), 'sys.exit', 'sys.exit', (['""" Error in runDM.evolutionMat: E1 out of range. Require 1 GeV <= E1 <= 1e8 GeV"""'], {}), "(\n ' Error in runDM.evolutionMat: E1 out of range. Require 1 GeV <= E1 <= 1e8 GeV'\n )\n", (5021, 5112), False, 'import sys\n'), ((5154, 5253), 'sys.exit', 'sys.exit', (['""" Error in runDM.evolutionMat: E2 out of range. Require 1 GeV <= E2 <= 1e8 GeV"""'], {}), "(\n ' Error in runDM.evolutionMat: E2 out of range. Require 1 GeV <= E2 <= 1e8 GeV'\n )\n", (5162, 5253), False, 'import sys\n'), ((5877, 5985), 'sys.exit', 'sys.exit', (['""" Error in runDM.evolutionMat: E1 < mZ, E2 > mZ not supported - matching is not unique."""'], {}), "(\n ' Error in runDM.evolutionMat: E1 < mZ, E2 > mZ not supported - matching is not unique.'\n )\n", (5885, 5985), False, 'import sys\n'), ((7112, 7189), 'sys.exit', 'sys.exit', (['""" Error in runDM.runCouplings: c must be an array with 16 elements"""'], {}), "(' Error in runDM.runCouplings: c must be an array with 16 elements')\n", (7120, 7189), False, 'import sys\n'), ((7221, 7298), 'sys.exit', 'sys.exit', (['""" Error in runDM.runCouplings: c must be an array with 16 elements"""'], {}), "(' Error in runDM.runCouplings: c must be an array with 16 elements')\n", (7229, 7298), False, 'import sys\n'), ((9271, 9348), 'sys.exit', 'sys.exit', (['""" Error in runDM.runCouplings: c must be an array with 16 elements"""'], {}), "(' Error in runDM.runCouplings: c must be an array with 16 elements')\n", (9279, 9348), False, 'import sys\n'), ((9380, 9457), 'sys.exit', 'sys.exit', (['""" Error in runDM.runCouplings: c must be an array with 16 elements"""'], {}), "(' Error in runDM.runCouplings: c must be an array with 16 elements')\n", (9388, 9457), False, 'import sys\n'), ((9646, 9663), 'numpy.zeros', 'np.zeros', (['[n1, 5]'], {}), '([n1, 5])\n', (9654, 9663), True, 'import numpy as np\n'), ((13389, 13460), 'sys.exit', 'sys.exit', (['""" Error in runDM.DDCouplingsNR: N must be either \'p\' or \'n\'."""'], {}), '(" Error in runDM.DDCouplingsNR: N must be either \'p\' or \'n\'.")\n', (13397, 13460), False, 'import sys\n'), ((13531, 13639), 'sys.exit', 'sys.exit', (['""" Error in runDM.DDCouplingsNR: DMcurrent must be \'scalar\', \'vector\' or \'axial-vector\'."""'], {}), '(\n " Error in runDM.DDCouplingsNR: DMcurrent must be \'scalar\', \'vector\' or \'axial-vector\'."\n )\n', (13539, 13639), False, 'import sys\n'), ((13717, 13795), 'sys.exit', 'sys.exit', (['""" Error in runDM.DDCouplingsNR: c must be an array with 16 elements"""'], {}), "(' Error in runDM.DDCouplingsNR: c must be an array with 16 elements')\n", (13725, 13795), False, 'import sys\n'), ((13827, 13905), 'sys.exit', 'sys.exit', (['""" Error in runDM.DDCouplingsNR: c must be an array with 16 elements"""'], {}), "(' Error in runDM.DDCouplingsNR: c must be an array with 16 elements')\n", (13835, 13905), False, 'import sys\n'), ((13988, 14058), 'sys.exit', 'sys.exit', (['""" Error in runDM.DDCouplingsNR: mx must be a single number."""'], {}), "(' Error in runDM.DDCouplingsNR: mx must be a single number.')\n", (13996, 14058), False, 'import sys\n'), ((14421, 14439), 'numpy.zeros', 'np.zeros', (['[n1, 12]'], {}), '([n1, 12])\n', (14429, 14439), True, 'import numpy as np\n'), ((2675, 2770), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0\n ]'], {}), '([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 0.0])\n', (2683, 2770), True, 'import numpy as np\n'), ((4974, 4990), 'numpy.log', 'np.log', (['(1.0 / mZ)'], {}), '(1.0 / mZ)\n', (4980, 4990), True, 'import numpy as np\n'), ((5115, 5131), 'numpy.log', 'np.log', (['(1.0 / mZ)'], {}), '(1.0 / mZ)\n', (5121, 5131), True, 'import numpy as np\n'), ((7744, 7842), 'sys.exit', 'sys.exit', (['""" Error in runDM.runCouplings: E1 and E2 must have same length (or be scalar)"""'], {}), "(\n ' Error in runDM.runCouplings: E1 and E2 must have same length (or be scalar)'\n )\n", (7752, 7842), False, 'import sys\n'), ((7868, 7886), 'numpy.zeros', 'np.zeros', (['[n1, 16]'], {}), '([n1, 16])\n', (7876, 7886), True, 'import numpy as np\n'), ((8086, 8104), 'numpy.zeros', 'np.zeros', (['[n1, 16]'], {}), '([n1, 16])\n', (8094, 8104), True, 'import numpy as np\n'), ((2810, 2911), 'numpy.array', 'np.array', (['[-1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0,\n 1.0, 0.0]'], {}), '([-1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, \n 1.0, -1.0, 1.0, 0.0])\n', (2818, 2911), True, 'import numpy as np\n'), ((8293, 8311), 'numpy.zeros', 'np.zeros', (['[n2, 16]'], {}), '([n2, 16])\n', (8301, 8311), True, 'import numpy as np\n'), ((2949, 3044), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0\n ]'], {}), '([1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, \n 0.0, 0.0, 0.0])\n', (2957, 3044), True, 'import numpy as np\n'), ((3081, 3179), 'numpy.array', 'np.array', (['[-1.0, 1.0, 1.0, 0.0, 0.0, -1.0, 1.0, 1.0, 0.0, 0.0, -1.0, 1.0, 1.0, 0.0, \n 0.0, 0.0]'], {}), '([-1.0, 1.0, 1.0, 0.0, 0.0, -1.0, 1.0, 1.0, 0.0, 0.0, -1.0, 1.0, \n 1.0, 0.0, 0.0, 0.0])\n', (3089, 3179), True, 'import numpy as np\n'), ((3218, 3313), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0\n ]'], {}), '([0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, \n 1.0, 1.0, 0.0])\n', (3226, 3313), True, 'import numpy as np\n'), ((3351, 3448), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0, \n 1.0, 0.0]'], {}), '([0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0,\n -1.0, 1.0, 0.0])\n', (3359, 3448), True, 'import numpy as np\n'), ((3486, 3581), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0\n ]'], {}), '([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, \n 1.0, 1.0, 0.0])\n', (3494, 3581), True, 'import numpy as np\n'), ((3617, 3713), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0, 1.0, -1.0, \n 1.0, 0.0]'], {}), '([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0, 1.0,\n -1.0, 1.0, 0.0])\n', (3625, 3713), True, 'import numpy as np\n'), ((4044, 4056), 'numpy.zeros', 'np.zeros', (['(16)'], {}), '(16)\n', (4052, 4056), True, 'import numpy as np\n')]
from functools import reduce from math import degrees, sin, cos from time import time from skimage import img_as_float from skimage.io import imread from skimage.color import rgb2hsv, label2rgb from skimage.morphology import dilation, erosion, disk from skimage.transform import ProjectiveTransform, resize, warp from skimage.measure import label, regionprops from numpy import logical_and, array import matplotlib.pyplot as plt from utils import make_colormap, show_images class MarekSolution: WIDTH, HEIGHT = 1000, 500 mini_selem = disk(3) selem = disk(6) COLOR_BLOCKS = { #'name': (hue_start, hue_end) 'green': (0.4, 0.6), 'yellow': (0.05, 0.18), } def __init__(self, filename, scale=None): img = imread(filename) if scale: h = img.shape[0] * scale w = img.shape[1] * scale img = resize(img, (w, h), anti_aliasing=True) self.img = img_as_float(img) self.hsv = rgb2hsv(self.img) def crop_image(self, debug=False, with_img=False): t0 = time() corners = self._find_corners() t1 = time() corner_points = self._get_positions_of_corners(corners) t2 = time() center_points = self._get_center_of_image(corner_points) t3 = time() if debug: print('find corners: %8.3f' % (t1 - t0)) print('get positions of corners: %8.3f' % (t2 - t1)) print('find center: %8.3f' % (t3 - t2)) plt.figure(figsize=(20, 10)) plt.imshow(label2rgb(corners, self.img)) plt.plot([x for x,y in corner_points], [y for x,y in corner_points], '.w') plt.plot(center_points[0], center_points[1], '+w') plt.show() t4 = time() tform = self._make_transform_to_crop(corner_points, center_points) t5 = time() if with_img: self.crop_img = warp(self.img, tform, output_shape=(self.HEIGHT, self.WIDTH)) self.crop_hsv = warp(self.hsv, tform, output_shape=(self.HEIGHT, self.WIDTH)) t6 = time() if debug: print('make transform to crop: %8.3f' % (t5 - t4)) print('crop and transform: %8.3f' % (t6 - t5)) print('total: %8.3f' % (t3 - t0 + t6 - t4)) def find_blocks(self, debug=False, debug_small=False): hue = self.crop_hsv[:,:,0] sat = self.crop_hsv[:,:,1] val = self.crop_hsv[:,:,2] blocks_mask = logical_and(sat > 0.2, val > 0.3) blocks_mask = erosion(blocks_mask, self.mini_selem) blocks_mask = dilation(blocks_mask, self.selem) def seek_color(hue_start, hue_end): mask = logical_and( blocks_mask, logical_and(hue > hue_start, hue < hue_end) ) mask = erosion(mask, self.mini_selem) return mask masks = { name: seek_color(hue_start, hue_end) for name, (hue_start, hue_end) in self.COLOR_BLOCKS.items() } if debug: show_images([ ('all', blocks_mask, 'gray'), ] + [ (name, mask, make_colormap(name)) for name, mask in masks.items() ]) labels = { name: label(mask) for name, mask in masks.items() } return labels @staticmethod def transform_blocks_to_json(blocks): objs = [] for color_name, labels in blocks.items(): for region in regionprops(labels): cy, cx = region.centroid angle = abs(region.orientation) length = region.major_axis_length sx = cx - sin(angle) * 0.5 * length sy = cy - cos(angle) * 0.5 * length objs.append({ 'color': color_name, 'angle': degrees(angle), 'x': sx, 'y': sy, 'length': length, }) return { 'type': 'marek-solution', 'objs': objs, } def _find_corners(self): hsv = self.hsv h = hsv[:,:,0] s = hsv[:,:,1] v = hsv[:,:,2] corners_mask = logical_and( logical_and(s > 0.2, v > 0.3), logical_and(h > 0.8, h < 0.95), ) corners_mask = dilation(corners_mask, self.selem) corners = label(corners_mask) return corners def _get_positions_of_corners(self, corners): tmp_points = [] for region in regionprops(corners): y, x = region.centroid tmp_points.append((x, y)) assert len(tmp_points) >= 4, 'not enough corners!' return tmp_points def _get_center_of_image(self, points): len_points = len(points) sx, sy = reduce( lambda a, b: (a[0] + b[0], a[1] + b[1]), points, ) return sx / len_points , sy / len_points def _get_points_to_transform(self, points, center_points): cenx, ceny = center_points dst_points = array([(0, 0)] * 4) UP_LEFT, DOWN_LEFT, DOWN_RIGHT, UP_RIGHT = range(4) def get_corner_index(x, y): if y < ceny: return UP_LEFT if x < cenx else UP_RIGHT else: return DOWN_LEFT if x < cenx else DOWN_RIGHT for x, y in points: corner_index = get_corner_index(x, y) dst_points[corner_index] = (x, y) return dst_points def _make_transform_to_crop(self, points, center_points): dst_points = self._get_points_to_transform(points, center_points) src_points = array([ (0, 0), (0, self.HEIGHT), (self.WIDTH, self.HEIGHT), (self.WIDTH, 0), ]) tform = ProjectiveTransform() tform.estimate(src_points, dst_points) return tform
[ "skimage.img_as_float", "math.cos", "numpy.array", "utils.make_colormap", "matplotlib.pyplot.plot", "skimage.morphology.erosion", "skimage.measure.regionprops", "functools.reduce", "math.degrees", "skimage.morphology.dilation", "skimage.io.imread", "skimage.color.rgb2hsv", "skimage.transform...
[((546, 553), 'skimage.morphology.disk', 'disk', (['(3)'], {}), '(3)\n', (550, 553), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((566, 573), 'skimage.morphology.disk', 'disk', (['(6)'], {}), '(6)\n', (570, 573), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((770, 786), 'skimage.io.imread', 'imread', (['filename'], {}), '(filename)\n', (776, 786), False, 'from skimage.io import imread\n'), ((956, 973), 'skimage.img_as_float', 'img_as_float', (['img'], {}), '(img)\n', (968, 973), False, 'from skimage import img_as_float\n'), ((993, 1010), 'skimage.color.rgb2hsv', 'rgb2hsv', (['self.img'], {}), '(self.img)\n', (1000, 1010), False, 'from skimage.color import rgb2hsv, label2rgb\n'), ((1088, 1094), 'time.time', 'time', ([], {}), '()\n', (1092, 1094), False, 'from time import time\n'), ((1147, 1153), 'time.time', 'time', ([], {}), '()\n', (1151, 1153), False, 'from time import time\n'), ((1231, 1237), 'time.time', 'time', ([], {}), '()\n', (1235, 1237), False, 'from time import time\n'), ((1316, 1322), 'time.time', 'time', ([], {}), '()\n', (1320, 1322), False, 'from time import time\n'), ((1826, 1832), 'time.time', 'time', ([], {}), '()\n', (1830, 1832), False, 'from time import time\n'), ((1921, 1927), 'time.time', 'time', ([], {}), '()\n', (1925, 1927), False, 'from time import time\n'), ((2063, 2124), 'skimage.transform.warp', 'warp', (['self.hsv', 'tform'], {'output_shape': '(self.HEIGHT, self.WIDTH)'}), '(self.hsv, tform, output_shape=(self.HEIGHT, self.WIDTH))\n', (2067, 2124), False, 'from skimage.transform import ProjectiveTransform, resize, warp\n'), ((2138, 2144), 'time.time', 'time', ([], {}), '()\n', (2142, 2144), False, 'from time import time\n'), ((2555, 2588), 'numpy.logical_and', 'logical_and', (['(sat > 0.2)', '(val > 0.3)'], {}), '(sat > 0.2, val > 0.3)\n', (2566, 2588), False, 'from numpy import logical_and, array\n'), ((2611, 2648), 'skimage.morphology.erosion', 'erosion', (['blocks_mask', 'self.mini_selem'], {}), '(blocks_mask, self.mini_selem)\n', (2618, 2648), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((2671, 2704), 'skimage.morphology.dilation', 'dilation', (['blocks_mask', 'self.selem'], {}), '(blocks_mask, self.selem)\n', (2679, 2704), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((4532, 4566), 'skimage.morphology.dilation', 'dilation', (['corners_mask', 'self.selem'], {}), '(corners_mask, self.selem)\n', (4540, 4566), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((4585, 4604), 'skimage.measure.label', 'label', (['corners_mask'], {}), '(corners_mask)\n', (4590, 4604), False, 'from skimage.measure import label, regionprops\n'), ((4733, 4753), 'skimage.measure.regionprops', 'regionprops', (['corners'], {}), '(corners)\n', (4744, 4753), False, 'from skimage.measure import label, regionprops\n'), ((5012, 5067), 'functools.reduce', 'reduce', (['(lambda a, b: (a[0] + b[0], a[1] + b[1]))', 'points'], {}), '(lambda a, b: (a[0] + b[0], a[1] + b[1]), points)\n', (5018, 5067), False, 'from functools import reduce\n'), ((5277, 5296), 'numpy.array', 'array', (['([(0, 0)] * 4)'], {}), '([(0, 0)] * 4)\n', (5282, 5296), False, 'from numpy import logical_and, array\n'), ((5884, 5961), 'numpy.array', 'array', (['[(0, 0), (0, self.HEIGHT), (self.WIDTH, self.HEIGHT), (self.WIDTH, 0)]'], {}), '([(0, 0), (0, self.HEIGHT), (self.WIDTH, self.HEIGHT), (self.WIDTH, 0)])\n', (5889, 5961), False, 'from numpy import logical_and, array\n'), ((6037, 6058), 'skimage.transform.ProjectiveTransform', 'ProjectiveTransform', ([], {}), '()\n', (6056, 6058), False, 'from skimage.transform import ProjectiveTransform, resize, warp\n'), ((897, 936), 'skimage.transform.resize', 'resize', (['img', '(w, h)'], {'anti_aliasing': '(True)'}), '(img, (w, h), anti_aliasing=True)\n', (903, 936), False, 'from skimage.transform import ProjectiveTransform, resize, warp\n'), ((1545, 1573), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 10)'}), '(figsize=(20, 10))\n', (1555, 1573), True, 'import matplotlib.pyplot as plt\n'), ((1639, 1715), 'matplotlib.pyplot.plot', 'plt.plot', (['[x for x, y in corner_points]', '[y for x, y in corner_points]', '""".w"""'], {}), "([x for x, y in corner_points], [y for x, y in corner_points], '.w')\n", (1647, 1715), True, 'import matplotlib.pyplot as plt\n'), ((1726, 1776), 'matplotlib.pyplot.plot', 'plt.plot', (['center_points[0]', 'center_points[1]', '"""+w"""'], {}), "(center_points[0], center_points[1], '+w')\n", (1734, 1776), True, 'import matplotlib.pyplot as plt\n'), ((1789, 1799), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1797, 1799), True, 'import matplotlib.pyplot as plt\n'), ((1977, 2038), 'skimage.transform.warp', 'warp', (['self.img', 'tform'], {'output_shape': '(self.HEIGHT, self.WIDTH)'}), '(self.img, tform, output_shape=(self.HEIGHT, self.WIDTH))\n', (1981, 2038), False, 'from skimage.transform import ProjectiveTransform, resize, warp\n'), ((2905, 2935), 'skimage.morphology.erosion', 'erosion', (['mask', 'self.mini_selem'], {}), '(mask, self.mini_selem)\n', (2912, 2935), False, 'from skimage.morphology import dilation, erosion, disk\n'), ((3390, 3401), 'skimage.measure.label', 'label', (['mask'], {}), '(mask)\n', (3395, 3401), False, 'from skimage.measure import label, regionprops\n'), ((3637, 3656), 'skimage.measure.regionprops', 'regionprops', (['labels'], {}), '(labels)\n', (3648, 3656), False, 'from skimage.measure import label, regionprops\n'), ((4423, 4452), 'numpy.logical_and', 'logical_and', (['(s > 0.2)', '(v > 0.3)'], {}), '(s > 0.2, v > 0.3)\n', (4434, 4452), False, 'from numpy import logical_and, array\n'), ((4467, 4497), 'numpy.logical_and', 'logical_and', (['(h > 0.8)', '(h < 0.95)'], {}), '(h > 0.8, h < 0.95)\n', (4478, 4497), False, 'from numpy import logical_and, array\n'), ((1597, 1625), 'skimage.color.label2rgb', 'label2rgb', (['corners', 'self.img'], {}), '(corners, self.img)\n', (1606, 1625), False, 'from skimage.color import rgb2hsv, label2rgb\n'), ((2828, 2871), 'numpy.logical_and', 'logical_and', (['(hue > hue_start)', '(hue < hue_end)'], {}), '(hue > hue_start, hue < hue_end)\n', (2839, 2871), False, 'from numpy import logical_and, array\n'), ((4001, 4015), 'math.degrees', 'degrees', (['angle'], {}), '(angle)\n', (4008, 4015), False, 'from math import degrees, sin, cos\n'), ((3256, 3275), 'utils.make_colormap', 'make_colormap', (['name'], {}), '(name)\n', (3269, 3275), False, 'from utils import make_colormap, show_images\n'), ((3823, 3833), 'math.sin', 'sin', (['angle'], {}), '(angle)\n', (3826, 3833), False, 'from math import degrees, sin, cos\n'), ((3875, 3885), 'math.cos', 'cos', (['angle'], {}), '(angle)\n', (3878, 3885), False, 'from math import degrees, sin, cos\n')]
# Licensed under the MIT license. import os import torch import torch.nn as nn from torchvision import transforms import json from PIL import Image import numpy as np from azureml.core.model import Model def transform_image(array): """Transform a numpy array into a torch tensor, resized and normalized correctly - most torchvision transforms operate on PIL Image format""" # Prepare image for inference loader = transforms.Compose([ transforms.Resize(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # Converts to a PIL Image image = Image.fromarray(np.uint8(array)) # Creates a torch tensor image = loader(image).float() # Add a dimension to beginning of tensor ("batch") image = image.unsqueeze(0) return image def init(): global model # Get a registered model example: # model_path = Model.get_model_path('suspicious-behavior-pytorch') VERSION = os.getenv('VERSION','') # this is provided by the inference config MODEL_NAME = os.getenv('MODEL_NAME', '') # this is provided by the inference config AZUREML_MODEL_DIR = os.getenv('AZUREML_MODEL_DIR', '') # this env var is native to the Azure ML container model_path = os.path.join(AZUREML_MODEL_DIR, MODEL_NAME, VERSION, 'model_finetuned.pth') # Load with pytorch model = torch.load(model_path, map_location=lambda storage, loc: storage) # Set to evaluation mode model.eval() def run(input_data): # input_data = torch.tensor(np.array(json.loads(input_data)['data'])) input_data = transform_image(np.array(json.loads(input_data)['data'])) classes = ['normal', 'suspicious'] # get prediction with torch.no_grad(): output = model(input_data) softmax = nn.Softmax(dim=1) pred_probs = softmax(output).numpy()[0] index = torch.argmax(output, 1) result = {"label": classes[index], "probability": str(pred_probs[index])} return result
[ "numpy.uint8", "json.loads", "os.getenv", "torch.nn.Softmax", "torch.load", "os.path.join", "torchvision.transforms.Normalize", "torchvision.transforms.Resize", "torch.no_grad", "torchvision.transforms.ToTensor", "torch.argmax" ]
[((1014, 1038), 'os.getenv', 'os.getenv', (['"""VERSION"""', '""""""'], {}), "('VERSION', '')\n", (1023, 1038), False, 'import os\n'), ((1098, 1125), 'os.getenv', 'os.getenv', (['"""MODEL_NAME"""', '""""""'], {}), "('MODEL_NAME', '')\n", (1107, 1125), False, 'import os\n'), ((1193, 1227), 'os.getenv', 'os.getenv', (['"""AZUREML_MODEL_DIR"""', '""""""'], {}), "('AZUREML_MODEL_DIR', '')\n", (1202, 1227), False, 'import os\n'), ((1296, 1371), 'os.path.join', 'os.path.join', (['AZUREML_MODEL_DIR', 'MODEL_NAME', 'VERSION', '"""model_finetuned.pth"""'], {}), "(AZUREML_MODEL_DIR, MODEL_NAME, VERSION, 'model_finetuned.pth')\n", (1308, 1371), False, 'import os\n'), ((1408, 1473), 'torch.load', 'torch.load', (['model_path'], {'map_location': '(lambda storage, loc: storage)'}), '(model_path, map_location=lambda storage, loc: storage)\n', (1418, 1473), False, 'import torch\n'), ((678, 693), 'numpy.uint8', 'np.uint8', (['array'], {}), '(array)\n', (686, 693), True, 'import numpy as np\n'), ((1762, 1777), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1775, 1777), False, 'import torch\n'), ((1833, 1850), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (1843, 1850), True, 'import torch.nn as nn\n'), ((1915, 1938), 'torch.argmax', 'torch.argmax', (['output', '(1)'], {}), '(output, 1)\n', (1927, 1938), False, 'import torch\n'), ((471, 493), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224)'], {}), '(224)\n', (488, 493), False, 'from torchvision import transforms\n'), ((507, 528), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (526, 528), False, 'from torchvision import transforms\n'), ((542, 608), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (562, 608), False, 'from torchvision import transforms\n'), ((1658, 1680), 'json.loads', 'json.loads', (['input_data'], {}), '(input_data)\n', (1668, 1680), False, 'import json\n')]
# -*- coding: utf-8 -*- import os, sys import numpy as np from skimage import io import random, uuid import matplotlib.pyplot as plt from pydaily import filesystem def plot_lr(l_img, r_img, l_title=None, r_title=None, suptitle=None): fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 4)) axes[0].imshow(l_img, cmap="gray") axes[0].set_title(l_title) axes[0].set_axis_off() axes[1].imshow(r_img, cmap="gray") axes[1].set_title(r_title) axes[1].set_axis_off() plt.suptitle(suptitle, fontsize=16) plt.tight_layout() plt.show() def simulate_overlap(dataset_dir, cur_id, overlap_size, simulate_num, overlap_ratio_low=0.5, overlap_ratio_high=1.0): overlap_dir = os.path.join(dataset_dir, "simu_train") if not os.path.exists(overlap_dir): os.makedirs(overlap_dir) img_list = os.listdir(os.path.join(dataset_dir, cur_id+"use")) mask_list = os.listdir(os.path.join(dataset_dir, cur_id+"mask")) img_list.sort() mask_list.sort() success_num, try_num = 0, 0 while success_num < simulate_num: try_num += 1 if try_num > 5000: print("Try more than {} times, quit!".format(try_num)) break cur_selection = random.sample(img_list, 2) img1_path = os.path.join(dataset_dir, cur_id+"use", cur_selection[0]) img2_path = os.path.join(dataset_dir, cur_id+"use", cur_selection[1]) mask1_path = os.path.join(dataset_dir, cur_id+"mask", cur_selection[0]) mask2_path = os.path.join(dataset_dir, cur_id+"mask", cur_selection[1]) overlap_img = np.zeros((overlap_size, overlap_size), np.float32) overlap_mask = np.zeros((overlap_size, overlap_size), np.uint8) img1 = io.imread(img1_path) h1, w1 = img1.shape[0], img1.shape[1] img2 = io.imread(img2_path) h2, w2 = img2.shape[0], img2.shape[1] max_size = overlap_size - 3 if h1 > max_size or w1 > max_size or h2 > max_size or w2 > max_size: continue rand_h1 = random.choice(np.arange(overlap_size-h1)) rand_w1 = random.choice(np.arange(overlap_size-w1)) rand_h2 = random.choice(np.arange(overlap_size-h2)) rand_w2 = random.choice(np.arange(overlap_size-w2)) mask1 = io.imread(mask1_path) / 2 mask1 = mask1.astype(np.uint8) mask2 = io.imread(mask2_path) / 2 mask2 = mask2.astype(np.uint8) overlap_mask[rand_h1:rand_h1+h1, rand_w1:rand_w1+w1] += mask1 overlap_mask[rand_h2:rand_h2+h2, rand_w2:rand_w2+w2] += mask2 num_overlap = np.count_nonzero(overlap_mask == 254) num_single = np.count_nonzero(overlap_mask == 127) overlap_ratio = num_overlap * 2.0 / (num_single + num_overlap * 2.0) if overlap_ratio > overlap_ratio_low and overlap_ratio < overlap_ratio_high: extend_img1 = np.zeros((overlap_size, overlap_size), np.uint8) extend_img1[rand_h1:rand_h1+h1, rand_w1:rand_w1+w1] = img1 overlap_img += extend_img1 extend_img2 = np.zeros((overlap_size, overlap_size), np.uint8) extend_img2[rand_h2:rand_h2+h2, rand_w2:rand_w2+w2] = img2 overlap_img += extend_img2 sum_overlap_img = overlap_img.copy() sum_overlap_img[sum_overlap_img > 255] = 255 sum_overlap_img = sum_overlap_img.astype(np.uint8) overlap_r = overlap_mask == 254 overlap_img[overlap_r] = 0 inv_overlap_r = np.invert(overlap_r) extend_img1[inv_overlap_r] = 0 extend_img2[inv_overlap_r] = 0 overlap_ratio1 = round(np.random.uniform(0.6, 1.0), 2) overlap_ratio2 = round(np.random.uniform(0.6, 1.0), 2) rand_overlap_img = overlap_img.copy() rand_overlap_img += overlap_ratio1 * extend_img1 rand_overlap_img += overlap_ratio2 * extend_img2 rand_overlap_img[rand_overlap_img > 255] = 255 rand_overlap_img = rand_overlap_img.astype(np.uint8) l_title = "Summing overlap" r_title = r"Overlap with $ \alpha_{1}= $" + "{}".format(overlap_ratio1) + r" and $ \alpha_{2}= $" + "{}".format(overlap_ratio2) plot_lr(sum_overlap_img, rand_overlap_img, l_title, r_title) else: continue if __name__ == "__main__": dataset_dir = "../data/OverlapSeg/single_chromosomes" img_ids = [str(id) for id in np.arange(1, 80)] for cur_id in img_ids: print("Processing {}".format(cur_id)) # simulate_overlap(dataset_dir, cur_id, overlap_size=160, simulate_num=10, overlap_ratio_low=0.3, overlap_ratio_high=0.5) simulate_overlap(dataset_dir, cur_id, overlap_size=160, simulate_num=10, overlap_ratio_low=0.1, overlap_ratio_high=0.3)
[ "os.path.exists", "random.sample", "os.makedirs", "os.path.join", "numpy.invert", "numpy.count_nonzero", "numpy.zeros", "skimage.io.imread", "matplotlib.pyplot.subplots", "matplotlib.pyplot.tight_layout", "numpy.random.uniform", "matplotlib.pyplot.suptitle", "numpy.arange", "matplotlib.pyp...
[((253, 300), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(2)', 'figsize': '(10, 4)'}), '(nrows=1, ncols=2, figsize=(10, 4))\n', (265, 300), True, 'import matplotlib.pyplot as plt\n'), ((502, 537), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['suptitle'], {'fontsize': '(16)'}), '(suptitle, fontsize=16)\n', (514, 537), True, 'import matplotlib.pyplot as plt\n'), ((542, 560), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (558, 560), True, 'import matplotlib.pyplot as plt\n'), ((565, 575), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (573, 575), True, 'import matplotlib.pyplot as plt\n'), ((736, 775), 'os.path.join', 'os.path.join', (['dataset_dir', '"""simu_train"""'], {}), "(dataset_dir, 'simu_train')\n", (748, 775), False, 'import os, sys\n'), ((787, 814), 'os.path.exists', 'os.path.exists', (['overlap_dir'], {}), '(overlap_dir)\n', (801, 814), False, 'import os, sys\n'), ((824, 848), 'os.makedirs', 'os.makedirs', (['overlap_dir'], {}), '(overlap_dir)\n', (835, 848), False, 'import os, sys\n'), ((876, 917), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'use')"], {}), "(dataset_dir, cur_id + 'use')\n", (888, 917), False, 'import os, sys\n'), ((944, 986), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'mask')"], {}), "(dataset_dir, cur_id + 'mask')\n", (956, 986), False, 'import os, sys\n'), ((1257, 1283), 'random.sample', 'random.sample', (['img_list', '(2)'], {}), '(img_list, 2)\n', (1270, 1283), False, 'import random, uuid\n'), ((1304, 1363), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'use')", 'cur_selection[0]'], {}), "(dataset_dir, cur_id + 'use', cur_selection[0])\n", (1316, 1363), False, 'import os, sys\n'), ((1382, 1441), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'use')", 'cur_selection[1]'], {}), "(dataset_dir, cur_id + 'use', cur_selection[1])\n", (1394, 1441), False, 'import os, sys\n'), ((1461, 1521), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'mask')", 'cur_selection[0]'], {}), "(dataset_dir, cur_id + 'mask', cur_selection[0])\n", (1473, 1521), False, 'import os, sys\n'), ((1541, 1601), 'os.path.join', 'os.path.join', (['dataset_dir', "(cur_id + 'mask')", 'cur_selection[1]'], {}), "(dataset_dir, cur_id + 'mask', cur_selection[1])\n", (1553, 1601), False, 'import os, sys\n'), ((1623, 1673), 'numpy.zeros', 'np.zeros', (['(overlap_size, overlap_size)', 'np.float32'], {}), '((overlap_size, overlap_size), np.float32)\n', (1631, 1673), True, 'import numpy as np\n'), ((1697, 1745), 'numpy.zeros', 'np.zeros', (['(overlap_size, overlap_size)', 'np.uint8'], {}), '((overlap_size, overlap_size), np.uint8)\n', (1705, 1745), True, 'import numpy as np\n'), ((1762, 1782), 'skimage.io.imread', 'io.imread', (['img1_path'], {}), '(img1_path)\n', (1771, 1782), False, 'from skimage import io\n'), ((1844, 1864), 'skimage.io.imread', 'io.imread', (['img2_path'], {}), '(img2_path)\n', (1853, 1864), False, 'from skimage import io\n'), ((2613, 2650), 'numpy.count_nonzero', 'np.count_nonzero', (['(overlap_mask == 254)'], {}), '(overlap_mask == 254)\n', (2629, 2650), True, 'import numpy as np\n'), ((2672, 2709), 'numpy.count_nonzero', 'np.count_nonzero', (['(overlap_mask == 127)'], {}), '(overlap_mask == 127)\n', (2688, 2709), True, 'import numpy as np\n'), ((2079, 2107), 'numpy.arange', 'np.arange', (['(overlap_size - h1)'], {}), '(overlap_size - h1)\n', (2088, 2107), True, 'import numpy as np\n'), ((2139, 2167), 'numpy.arange', 'np.arange', (['(overlap_size - w1)'], {}), '(overlap_size - w1)\n', (2148, 2167), True, 'import numpy as np\n'), ((2199, 2227), 'numpy.arange', 'np.arange', (['(overlap_size - h2)'], {}), '(overlap_size - h2)\n', (2208, 2227), True, 'import numpy as np\n'), ((2259, 2287), 'numpy.arange', 'np.arange', (['(overlap_size - w2)'], {}), '(overlap_size - w2)\n', (2268, 2287), True, 'import numpy as np\n'), ((2304, 2325), 'skimage.io.imread', 'io.imread', (['mask1_path'], {}), '(mask1_path)\n', (2313, 2325), False, 'from skimage import io\n'), ((2385, 2406), 'skimage.io.imread', 'io.imread', (['mask2_path'], {}), '(mask2_path)\n', (2394, 2406), False, 'from skimage import io\n'), ((2899, 2947), 'numpy.zeros', 'np.zeros', (['(overlap_size, overlap_size)', 'np.uint8'], {}), '((overlap_size, overlap_size), np.uint8)\n', (2907, 2947), True, 'import numpy as np\n'), ((3084, 3132), 'numpy.zeros', 'np.zeros', (['(overlap_size, overlap_size)', 'np.uint8'], {}), '((overlap_size, overlap_size), np.uint8)\n', (3092, 3132), True, 'import numpy as np\n'), ((3524, 3544), 'numpy.invert', 'np.invert', (['overlap_r'], {}), '(overlap_r)\n', (3533, 3544), True, 'import numpy as np\n'), ((4470, 4486), 'numpy.arange', 'np.arange', (['(1)', '(80)'], {}), '(1, 80)\n', (4479, 4486), True, 'import numpy as np\n'), ((3666, 3693), 'numpy.random.uniform', 'np.random.uniform', (['(0.6)', '(1.0)'], {}), '(0.6, 1.0)\n', (3683, 3693), True, 'import numpy as np\n'), ((3733, 3760), 'numpy.random.uniform', 'np.random.uniform', (['(0.6)', '(1.0)'], {}), '(0.6, 1.0)\n', (3750, 3760), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import IMLearn.learners.regressors.linear_regression from IMLearn.learners.regressors import PolynomialFitting from IMLearn.utils import split_train_test import numpy as np import pandas as pd import plotly.express as px import plotly.io as pio pio.templates.default = "simple_white" def load_data(filename: str) -> pd.DataFrame: """ Load city daily temperature dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (Temp) """ # raise NotImplementedError() three_in_four = [[0, 0], [31, 31], [28, 59], [31, 90], [30, 120], [31, 151], [30, 181], [31, 212], [31, 243], [30, 273], [31, 304], [30, 334], [31, 365]] once_in_four = [[0, 0], [31, 31], [29, 60], [31, 91], [30, 121], [31, 152], [30, 182], [31, 213], [31, 244], [30, 274], [31, 305], [30, 335], [31, 366]] four_loop = [once_in_four, three_in_four, three_in_four, three_in_four] full_data = pd.read_csv(filename, parse_dates=[2]).dropna().drop_duplicates() into_the_year = [] for index, sample in enumerate(full_data["Date"]): row = full_data.loc[[index]] if 1 <= sample.month <= 12 and 1 <= sample.day <= four_loop[sample.year % 4][sample.month][0]: if int(row["Month"]) == sample.month and int(row["Day"]) == sample.day and int(row["Year"]) == sample.year: into_the_year.append(sample.day_of_year) # alter.append(sample.day + four_loop[sample.year % 4][sample.month - 1][1]) full_data["DayOfYear"] = into_the_year full_data = pd.get_dummies(full_data, prefix='Month', columns=["Month"]) full_data = pd.get_dummies(full_data, prefix='Country', columns=["Country"]) full_data = pd.get_dummies(full_data, prefix='City', columns=["City"]) full_data = full_data[full_data["Temp"] < 55] full_data = full_data[-25 < full_data["Temp"]] return full_data if __name__ == '__main__': np.random.seed(0) countries = ["South Africa", "Israel", "The Netherlands", "Jordan"] # Question 1 - Load and preprocessing of city temperature dataset # raise NotImplementedError() data = load_data("C:/Users/user/IML.HUJI/datasets/City_Temperature.csv") # Question 2 - Exploring data for specific country # raise NotImplementedError() Israel_data = data[data["Country_Israel"] == 1] colors = ['brown', 'royalblue', 'gold', 'limegreen', 'darkorchid', 'deeppink', 'violet', 'olivedrab', 'chocolate', 'black', 'darkorange', 'lightslategray', 'crimson'] for i, year in enumerate(range(1995, 2008)): data_year = Israel_data[Israel_data.Year == year] plt.scatter(data_year.DayOfYear, data_year.Temp, c=colors[i], label=str(year)) plt.legend(bbox_to_anchor=(0.95, 1)) plt.xlabel("DayOfYear") plt.ylabel("Temp") plt.title("Temperature in Israel as for day of the year") plt.show() # plt.savefig("ex2_2_2") Israel_temp_std_month = [] for i in range(1, 13): std_i = Israel_data.groupby("Month_" + str(i)).Temp.std()[1] Israel_temp_std_month.append(std_i) plt.bar(range(1, 13), Israel_temp_std_month) plt.xlabel("month") plt.ylabel("std") plt.title("std in Israel as for month") plt.show() # Question 3 - Exploring differences between countries # raise NotImplementedError() stds = [[], [], [], []] means = [[], [], [], []] for j, country in enumerate(countries): for i in range(1, 13): month_i = data[data["Month_" + str(i)] == 1] filtered = month_i[month_i["Country_" + country] == 1] stds[j].append(filtered.Temp.std()) means[j].append(filtered.Temp.mean()) plt.errorbar(range(1, 13), means[j], yerr=stds[j], label=country) plt.legend() plt.xlabel("Month") plt.ylabel("avg Temp.") plt.title("avg Temp. as for each month with std as error bars") plt.show() # Question 4 - Fitting model for different values of `k` # raise NotImplementedError() y_label = "Temp" x = Israel_data.drop(columns=[y_label]) y = Israel_data[y_label] train_x, train_y, test_x, test_y = split_train_test(x, y, 0.75) train_x = train_x.DayOfYear test_x = test_x.DayOfYear losses = [] for k in range(1, 11): poly = PolynomialFitting(k) poly.fit(train_x.to_numpy(), train_y.to_numpy()) loss_k = poly.loss(test_x.to_numpy(), test_y.to_numpy()) loss_k = round(loss_k, 2) print(loss_k) losses.append(loss_k) plt.bar(range(1, 11), losses) plt.xlabel("k") plt.ylabel("loss") plt.title("loss as for k") plt.show() # Question 5 - Evaluating fitted model on different countries # raise NotImplementedError() best_k = min(losses) poly_best_k = PolynomialFitting(int(best_k)) poly_best_k.fit(Israel_data.DayOfYear, Israel_data.Temp) errors = [] for country in countries: country_j = data[data["Country_" + country] == 1] errors.append(poly_best_k.loss(country_j.DayOfYear, country_j.Temp)) plt.bar(countries, errors) plt.xlabel("country") plt.ylabel("error") plt.title("error in country as for Israel fit") plt.show()
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "IMLearn.utils.split_train_test", "matplotlib.pyplot.bar", "numpy.random.seed", "pandas.get_dummies", "matplotlib.pyplot.title", "IMLearn.learners.regressors.PolynomialFitting", "matplotlib.pyplot.legend", "matplotlib.pyp...
[((1699, 1759), 'pandas.get_dummies', 'pd.get_dummies', (['full_data'], {'prefix': '"""Month"""', 'columns': "['Month']"}), "(full_data, prefix='Month', columns=['Month'])\n", (1713, 1759), True, 'import pandas as pd\n'), ((1776, 1840), 'pandas.get_dummies', 'pd.get_dummies', (['full_data'], {'prefix': '"""Country"""', 'columns': "['Country']"}), "(full_data, prefix='Country', columns=['Country'])\n", (1790, 1840), True, 'import pandas as pd\n'), ((1857, 1915), 'pandas.get_dummies', 'pd.get_dummies', (['full_data'], {'prefix': '"""City"""', 'columns': "['City']"}), "(full_data, prefix='City', columns=['City'])\n", (1871, 1915), True, 'import pandas as pd\n'), ((2073, 2090), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2087, 2090), True, 'import numpy as np\n'), ((2906, 2942), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'bbox_to_anchor': '(0.95, 1)'}), '(bbox_to_anchor=(0.95, 1))\n', (2916, 2942), True, 'import matplotlib.pyplot as plt\n'), ((2947, 2970), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""DayOfYear"""'], {}), "('DayOfYear')\n", (2957, 2970), True, 'import matplotlib.pyplot as plt\n'), ((2975, 2993), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Temp"""'], {}), "('Temp')\n", (2985, 2993), True, 'import matplotlib.pyplot as plt\n'), ((2998, 3055), 'matplotlib.pyplot.title', 'plt.title', (['"""Temperature in Israel as for day of the year"""'], {}), "('Temperature in Israel as for day of the year')\n", (3007, 3055), True, 'import matplotlib.pyplot as plt\n'), ((3060, 3070), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3068, 3070), True, 'import matplotlib.pyplot as plt\n'), ((3326, 3345), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""month"""'], {}), "('month')\n", (3336, 3345), True, 'import matplotlib.pyplot as plt\n'), ((3350, 3367), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""std"""'], {}), "('std')\n", (3360, 3367), True, 'import matplotlib.pyplot as plt\n'), ((3372, 3411), 'matplotlib.pyplot.title', 'plt.title', (['"""std in Israel as for month"""'], {}), "('std in Israel as for month')\n", (3381, 3411), True, 'import matplotlib.pyplot as plt\n'), ((3416, 3426), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3424, 3426), True, 'import matplotlib.pyplot as plt\n'), ((3956, 3968), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3966, 3968), True, 'import matplotlib.pyplot as plt\n'), ((3973, 3992), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Month"""'], {}), "('Month')\n", (3983, 3992), True, 'import matplotlib.pyplot as plt\n'), ((3997, 4020), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""avg Temp."""'], {}), "('avg Temp.')\n", (4007, 4020), True, 'import matplotlib.pyplot as plt\n'), ((4025, 4088), 'matplotlib.pyplot.title', 'plt.title', (['"""avg Temp. as for each month with std as error bars"""'], {}), "('avg Temp. as for each month with std as error bars')\n", (4034, 4088), True, 'import matplotlib.pyplot as plt\n'), ((4093, 4103), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4101, 4103), True, 'import matplotlib.pyplot as plt\n'), ((4333, 4361), 'IMLearn.utils.split_train_test', 'split_train_test', (['x', 'y', '(0.75)'], {}), '(x, y, 0.75)\n', (4349, 4361), False, 'from IMLearn.utils import split_train_test\n'), ((4752, 4767), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""k"""'], {}), "('k')\n", (4762, 4767), True, 'import matplotlib.pyplot as plt\n'), ((4772, 4790), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""loss"""'], {}), "('loss')\n", (4782, 4790), True, 'import matplotlib.pyplot as plt\n'), ((4795, 4821), 'matplotlib.pyplot.title', 'plt.title', (['"""loss as for k"""'], {}), "('loss as for k')\n", (4804, 4821), True, 'import matplotlib.pyplot as plt\n'), ((4826, 4836), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4834, 4836), True, 'import matplotlib.pyplot as plt\n'), ((5256, 5282), 'matplotlib.pyplot.bar', 'plt.bar', (['countries', 'errors'], {}), '(countries, errors)\n', (5263, 5282), True, 'import matplotlib.pyplot as plt\n'), ((5287, 5308), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""country"""'], {}), "('country')\n", (5297, 5308), True, 'import matplotlib.pyplot as plt\n'), ((5313, 5332), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""error"""'], {}), "('error')\n", (5323, 5332), True, 'import matplotlib.pyplot as plt\n'), ((5337, 5384), 'matplotlib.pyplot.title', 'plt.title', (['"""error in country as for Israel fit"""'], {}), "('error in country as for Israel fit')\n", (5346, 5384), True, 'import matplotlib.pyplot as plt\n'), ((5389, 5399), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5397, 5399), True, 'import matplotlib.pyplot as plt\n'), ((4484, 4504), 'IMLearn.learners.regressors.PolynomialFitting', 'PolynomialFitting', (['k'], {}), '(k)\n', (4501, 4504), False, 'from IMLearn.learners.regressors import PolynomialFitting\n'), ((1083, 1121), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'parse_dates': '[2]'}), '(filename, parse_dates=[2])\n', (1094, 1121), True, 'import pandas as pd\n')]
# System libs import os import random import time # Numerical libs import torch import torch.nn.functional as F import numpy as np from tensorboardX import SummaryWriter # Our libs from arguments import ArgParser from dataset import MUSICMixDataset from models import ModelBuilder, activate from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals from viz import plot_loss_metrics, HTMLVisualizer import json import pdb # Network wrapper, defines forward pass class NetWrapper(torch.nn.Module): def __init__(self, nets, crit, mode='Minus'): super(NetWrapper, self).__init__() self.net_sound_M, self.net_frame_M, self.net_sound_P = nets self.crit = crit self.mode = mode @staticmethod def choose_max(index_record, total_energy): MIN = -100 for index in index_record: Len = len(index) total_energy[list(range(Len)), index] = np.ones(Len) * MIN max_index = np.argmax(total_energy, axis=1) return max_index @staticmethod def requires_grad(model, flag=True): for p in model.parameters(): p.requires_grad = flag def forward(self, batch_data, args): ### prepare data mag_mix = batch_data['mag_mix'] mags = batch_data['mags'] frames = batch_data['frames'] mag_mix = mag_mix + 1e-10 mag_mix_tmp = mag_mix.clone() N = args.num_mix B = mag_mix.size(0) T = mag_mix.size(3) # 0.0 warp the spectrogram if args.log_freq: grid_warp = torch.from_numpy( warpgrid(B, 256, T, warp=True)).to(args.device) mag_mix = F.grid_sample(mag_mix, grid_warp) for n in range(N): mags[n] = F.grid_sample(mags[n], grid_warp) # 0.1 calculate loss weighting coefficient: magnitude of input mixture if args.weighted_loss: weight = torch.log1p(mag_mix) weight = torch.clamp(weight, 1e-3, 10) else: weight = torch.ones_like(mag_mix) # 0.2 ground truth masks are computed after warpping! # Please notice that, gt_masks are unordered gt_masks = [None for n in range(N)] for n in range(N): if args.binary_mask: # for simplicity, mag_N > 0.5 * mag_mix gt_masks[n] = (mags[n] > 0.5 * mag_mix).float() else: gt_masks[n] = mags[n] / mag_mix # clamp to avoid large numbers in ratio masks gt_masks[n].clamp_(0., 2.) ### Minus part if 'Minus' not in self.mode: self.requires_grad(self.net_sound_M, False) self.requires_grad(self.net_frame_M, False) feat_frames = [None for n in range(N)] ordered_pred_masks = [None for n in range(N)] ordered_pred_mags = [None for n in range(N)] # Step1: obtain all the frame features # forward net_frame_M -> Bx1xC for n in range(N): log_mag_mix = torch.log(mag_mix) feat_frames[n] = self.net_frame_M.forward_multiframe(frames[n]) feat_frames[n] = activate(feat_frames[n], args.img_activation) # Step2: separate the sounds one by one # forward net_sound_M -> BxCxHxW if args.log_freq: grid_unwarp = torch.from_numpy( warpgrid(B, args.stft_frame//2+1, 256, warp=False)).to(args.device) index_record = [] for n in range(N): log_mag_mix = torch.log(mag_mix).detach() feat_sound = self.net_sound_M(log_mag_mix) _, C, H, W = feat_sound.shape feat_sound = feat_sound.view(B, C, -1) # obtain current separated sound energy_list = [] tmp_masks = [] tmp_pred_mags = [] for feat_frame in feat_frames: cur_pred_mask = torch.bmm(feat_frame.unsqueeze(1), feat_sound).view(B, 1, H, W) cur_pred_mask = activate(cur_pred_mask, args.output_activation) tmp_masks.append(cur_pred_mask) # Here we cut off the loss flow from Minus net to Plus net # in order to train more steadily if args.log_freq: cur_pred_mask_unwrap = F.grid_sample(cur_pred_mask.detach(), grid_unwarp) if args.binary_mask: cur_pred_mask_unwrap = (cur_pred_mask_unwrap > args.mask_thres).float() else: cur_pred_mask_unwrap = cur_pred_mask.detach() cur_pred_mag = cur_pred_mask_unwrap * mag_mix_tmp tmp_pred_mags.append(cur_pred_mag) energy_list.append(np.array(cur_pred_mag.view(B, -1).mean(dim=1).cpu().data)) total_energy = np.stack(energy_list, axis=1) # _, cur_index = torch.max(total_energy) cur_index = self.choose_max(index_record, total_energy) index_record.append(cur_index) masks = torch.stack(tmp_masks, dim=0) ordered_pred_masks[n] = masks[cur_index, list(range(B))] pred_mags = torch.stack(tmp_pred_mags, dim=0) ordered_pred_mags[n] = pred_mags[cur_index, list(range(B))] #log_mag_mix = log_mag_mix - log_mag_mix * pred_masks[n] mag_mix = mag_mix - mag_mix * ordered_pred_masks[n] + 1e-10 # just for swap pred_masks, in order to compute loss conveniently # since gt_masks are unordered, we must transfer ordered_pred_masks to unordered index_record = np.stack(index_record, axis=1) total_masks = torch.stack(ordered_pred_masks, dim=1) total_pred_mags = torch.stack(ordered_pred_mags, dim=1) unordered_pred_masks = [] unordered_pred_mags = [] for n in range(N): mask_index = np.where(index_record == n) if args.binary_mask: unordered_pred_masks.append(total_masks[mask_index]) unordered_pred_mags.append(total_pred_mags[mask_index]) else: unordered_pred_masks.append(total_masks[mask_index] * 2) unordered_pred_mags.append(total_pred_mags[mask_index]) ### Plus part if 'Plus' in self.mode: pre_sum = torch.zeros_like(unordered_pred_masks[0]).to(args.device) Plus_pred_masks = [] for n in range(N): unordered_pred_mag = unordered_pred_mags[n].log() unordered_pred_mag = F.grid_sample(unordered_pred_mag, grid_warp) input_concat = torch.cat((pre_sum, unordered_pred_mag), dim=1) residual_mask = activate(self.net_sound_P(input_concat), args.sound_activation) Plus_pred_masks.append(unordered_pred_masks[n] + residual_mask) pre_sum = pre_sum.sum(dim=1, keepdim=True).detach() unordered_pred_masks = Plus_pred_masks # loss if args.need_loss_ratio: err = 0 for n in range(N): err += self.crit(unordered_pred_masks[n], gt_masks[n], weight) / N * 2 ** (n-1) else: err = self.crit(unordered_pred_masks, gt_masks, weight).reshape(1) if 'Minus' in self.mode: res_mag_mix = torch.exp(log_mag_mix) err_remain = torch.mean(weight * torch.clamp(res_mag_mix - 1e-2, min=0)) err += err_remain outputs = {'pred_masks': unordered_pred_masks, 'gt_masks': gt_masks, 'mag_mix': mag_mix, 'mags': mags, 'weight': weight} return err, outputs class MP_Trainer(torch.nn.Module): def __init__(self, netwrapper, optimizer, args): super().__init__() self.mode = args.mode self.netwrapper = netwrapper self.optimizer = optimizer self.args = args self.history = { 'train': {'epoch': [], 'err': []}, 'val': {'epoch': [], 'err': [], 'sdr': [], 'sir': [], 'sar': []} } if self.mode == 'train': self.writer = SummaryWriter(log_dir=os.path.join('./logs', self.args.exp_name)) self.epoch = 0 # epoch initialize def evaluate(self, loader): print('Evaluating at {} epochs...'.format(self.epoch)) torch.set_grad_enabled(False) # remove previous viz results makedirs(self.args.vis, remove=True) self.netwrapper.eval() # initialize meters loss_meter = AverageMeter() sdr_mix_meter = AverageMeter() sdr_meter = AverageMeter() sir_meter = AverageMeter() sar_meter = AverageMeter() # initialize HTML header visualizer = HTMLVisualizer(os.path.join(self.args.vis, 'index.html')) header = ['Filename', 'Input Mixed Audio'] for n in range(1, self.args.num_mix+1): header += ['Video {:d}'.format(n), 'Predicted Audio {:d}'.format(n), 'GroundTruth Audio {}'.format(n), 'Predicted Mask {}'.format(n), 'GroundTruth Mask {}'.format(n)] header += ['Loss weighting'] visualizer.add_header(header) vis_rows = [] eval_num = 0 valid_num = 0 #for i, batch_data in enumerate(self.loader['eval']): for i, batch_data in enumerate(loader): # forward pass eval_num += batch_data['mag_mix'].shape[0] with torch.no_grad(): err, outputs = self.netwrapper.forward(batch_data, args) err = err.mean() if self.mode == 'train': self.writer.add_scalar('data/val_loss', err, self.args.epoch_iters * self.epoch + i) loss_meter.update(err.item()) print('[Eval] iter {}, loss: {:.4f}'.format(i, err.item())) # calculate metrics sdr_mix, sdr, sir, sar, cur_valid_num = calc_metrics(batch_data, outputs, self.args) print("sdr_mix, sdr, sir, sar: ", sdr_mix, sdr, sir, sar) sdr_mix_meter.update(sdr_mix) sdr_meter.update(sdr) sir_meter.update(sir) sar_meter.update(sar) valid_num += cur_valid_num ''' # output visualization if len(vis_rows) < self.args.num_vis: output_visuals(vis_rows, batch_data, outputs, self.args) ''' metric_output = '[Eval Summary] Epoch: {}, Loss: {:.4f}, ' \ 'SDR_mixture: {:.4f}, SDR: {:.4f}, SIR: {:.4f}, SAR: {:.4f}'.format( self.epoch, loss_meter.average(), sdr_mix_meter.sum_value()/eval_num, sdr_meter.sum_value()/eval_num, sir_meter.sum_value()/eval_num, sar_meter.sum_value()/eval_num ) if valid_num / eval_num < 0.8: metric_output += ' ---- Invalid ---- ' print(metric_output) learning_rate = ' lr_sound: {}, lr_frame: {}'.format(self.args.lr_sound, self.args.lr_frame) with open(self.args.log, 'a') as F: F.write(metric_output + learning_rate + '\n') self.history['val']['epoch'].append(self.epoch) self.history['val']['err'].append(loss_meter.average()) self.history['val']['sdr'].append(sdr_meter.sum_value()/eval_num) self.history['val']['sir'].append(sir_meter.sum_value()/eval_num) self.history['val']['sar'].append(sar_meter.sum_value()/eval_num) ''' print('Plotting html for visualization...') visualizer.add_rows(vis_rows) visualizer.write_html() ''' # Plot figure if self.epoch > 0: print('Plotting figures...') plot_loss_metrics(self.args.ckpt, self.history) def train(self, loader): torch.set_grad_enabled(True) batch_time = AverageMeter() data_time = AverageMeter() # switch to train mode self.netwrapper.train() # main loop torch.cuda.synchronize() tic = time.perf_counter() for i, batch_data in enumerate(loader): # measure data time torch.cuda.synchronize() data_time.update(time.perf_counter() - tic) # forward pass self.netwrapper.zero_grad() err, outputs = self.netwrapper.forward(batch_data, args) err = err.mean() self.writer.add_scalar('data/loss', err.mean(), self.args.epoch_iters * self.epoch + i) # backward err.backward() self.optimizer.step() # measure total time torch.cuda.synchronize() batch_time.update(time.perf_counter() - tic) tic = time.perf_counter() # display if i % self.args.disp_iter == 0: print('Epoch: [{}][{}/{}], Time: {:.2f}, Data: {:.2f}, ' 'lr_sound: {}, lr_frame: {}, ' 'loss: {:.4f}' .format(self.epoch, i, self.args.epoch_iters, batch_time.average(), data_time.average(), self.args.lr_sound, self.args.lr_frame, err.item())) fractional_epoch = self.epoch - 1 + 1. * i / self.args.epoch_iters self.history['train']['epoch'].append(fractional_epoch) self.history['train']['err'].append(err.item()) def checkpoint(self): print('Saving checkpoints at {} epochs.'.format(self.epoch)) torch.save(self.history, '{}/history_{:03d}.pth'.format(self.args.ckpt, self.epoch)) torch.save(self.netwrapper.module.net_sound_M.state_dict(), '{}/sound_M_{:03d}.pth'.format(self.args.ckpt, self.epoch)) torch.save(self.netwrapper.module.net_frame_M.state_dict(), '{}/frame_M_{:03d}.pth'.format(self.args.ckpt, self.epoch)) torch.save(self.netwrapper.module.net_sound_P.state_dict(), '{}/sound_P_{:03d}.pth'.format(self.args.ckpt, self.epoch)) @staticmethod def create_optimizer(nets, args): (net_sound_M, net_frame_M, net_sound_P) = nets param_groups = [{'params': net_sound_M.parameters(), 'lr': args.lr_sound}, {'params': net_sound_P.parameters(), 'lr': args.lr_sound}, {'params': net_frame_M.features.parameters(), 'lr': args.lr_frame}, {'params': net_frame_M.fc.parameters(), 'lr': args.lr_sound}] return torch.optim.SGD(param_groups, momentum=args.beta1, weight_decay=args.weight_decay) def adjust_learning_rate(self): self.args.lr_sound *= 0.1 self.args.lr_frame *= 0.1 for param_group in self.optimizer.param_groups: param_group['lr'] *= 0.1 def main(args): # Network Builders builder = ModelBuilder() net_sound_M = builder.build_sound( arch=args.arch_sound, fc_dim=args.num_channels, weights=args.weights_sound_M) net_frame_M = builder.build_frame( arch=args.arch_frame, fc_dim=args.num_channels, pool_type=args.img_pool, weights=args.weights_frame_M) net_sound_P = builder.build_sound( input_nc=2, arch=args.arch_sound, # fc_dim=args.num_channels, fc_dim=1, weights=args.weights_sound_P) nets = (net_sound_M, net_frame_M, net_sound_P) crit = builder.build_criterion(arch=args.loss) # Wrap networks # set netwrapper forward mode # there are there modes for different training stages # ['Minus', 'Plus', 'Minus_Plus'] netwrapper = NetWrapper(nets, crit, mode=args.forward_mode) netwrapper = torch.nn.DataParallel(netwrapper, device_ids=range(args.num_gpus)) netwrapper.to(args.device) # Dataset and Loader dataset_train = MUSICMixDataset( args.list_train, args, split='train') dataset_val = MUSICMixDataset( args.list_val, args, max_sample=args.num_val, split='val') loader_train = torch.utils.data.DataLoader( dataset_train, batch_size=args.batch_size, shuffle=True, num_workers=int(args.workers), drop_last=True) loader_val = torch.utils.data.DataLoader( dataset_val, batch_size=args.batch_size, shuffle=False, num_workers=2, drop_last=False) args.epoch_iters = len(dataset_train) // args.batch_size print('1 Epoch = {} iters'.format(args.epoch_iters)) # Set up optimizer optimizer = MP_Trainer.create_optimizer(nets, args) mp_trainer = MP_Trainer(netwrapper, optimizer, args) # Eval firstly mp_trainer.evaluate(loader_val) if mp_trainer.mode == 'eval': print('Evaluation Done!') else: # start training for epoch in range(1, args.num_epoch + 1): mp_trainer.epoch = epoch mp_trainer.train(loader_train) # Evaluation and visualization if epoch % args.eval_epoch == 0: mp_trainer.evaluate(loader_val) # checkpointing mp_trainer.checkpoint() # adjust learning rate if epoch in args.lr_steps: mp_trainer.adjust_learning_rate() print('Training Done!') mp_trainer.writer.close() if __name__ == '__main__': # arguments parser = ArgParser() args = parser.parse_train_arguments() args.batch_size = args.num_gpus * args.batch_size_per_gpu args.device = torch.device("cuda") os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_ids # experiment name if args.mode == 'train': args.id += '-{}mix'.format(args.num_mix) if args.log_freq: args.id += '-LogFreq' args.id += '-{}-{}'.format(args.arch_frame, args.arch_sound) args.id += '-frames{}stride{}'.format(args.num_frames, args.stride_frames) args.id += '-{}'.format(args.img_pool) if args.binary_mask: assert args.loss == 'bce', 'Binary Mask should go with BCE loss' args.id += '-binary' else: args.id += '-ratio' if args.weighted_loss: args.id += '-weightedLoss' args.id += '-channels{}'.format(args.num_channels) args.id += '-epoch{}'.format(args.num_epoch) args.id += '-step' + '_'.join([str(x) for x in args.lr_steps]) args.id += '_' + args.exp_name print('Model ID: {}'.format(args.id)) # paths to save/load output args.ckpt = os.path.join(args.ckpt, args.id) args.vis = os.path.join(args.ckpt, 'visualization/') args.log = os.path.join(args.ckpt, 'running_log.txt') pretrained_path = '' if args.mode == 'train': makedirs(args.ckpt, remove=True) args_path = os.path.join(args.ckpt, 'args.json') args_store = vars(args).copy() args_store['device'] = None with open(args_path, 'w') as json_file: json.dump(args_store, json_file) elif args.mode == 'eval': args.weights_sound_M = os.path.join(args.ckpt, 'sound_M_best.pth') args.weights_frame_M = os.path.join(args.ckpt, 'frame_M_best.pth') args.weights_sound_P = os.path.join(args.ckpt, 'sound_P_best.pth') # initialize best error with a big number args.best_err = float("inf") random.seed(args.seed) torch.manual_seed(args.seed) main(args)
[ "dataset.MUSICMixDataset", "torch.exp", "torch.cuda.synchronize", "models.activate", "torch.nn.functional.grid_sample", "torch.nn.functional.write", "models.ModelBuilder", "numpy.where", "time.perf_counter", "numpy.stack", "arguments.ArgParser", "torch.zeros_like", "utils.calc_metrics", "t...
[((15093, 15107), 'models.ModelBuilder', 'ModelBuilder', ([], {}), '()\n', (15105, 15107), False, 'from models import ModelBuilder, activate\n'), ((16092, 16145), 'dataset.MUSICMixDataset', 'MUSICMixDataset', (['args.list_train', 'args'], {'split': '"""train"""'}), "(args.list_train, args, split='train')\n", (16107, 16145), False, 'from dataset import MUSICMixDataset\n'), ((16173, 16247), 'dataset.MUSICMixDataset', 'MUSICMixDataset', (['args.list_val', 'args'], {'max_sample': 'args.num_val', 'split': '"""val"""'}), "(args.list_val, args, max_sample=args.num_val, split='val')\n", (16188, 16247), False, 'from dataset import MUSICMixDataset\n'), ((16467, 16586), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset_val'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(2)', 'drop_last': '(False)'}), '(dataset_val, batch_size=args.batch_size,\n shuffle=False, num_workers=2, drop_last=False)\n', (16494, 16586), False, 'import torch\n'), ((17634, 17645), 'arguments.ArgParser', 'ArgParser', ([], {}), '()\n', (17643, 17645), False, 'from arguments import ArgParser\n'), ((17768, 17788), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (17780, 17788), False, 'import torch\n'), ((18774, 18806), 'os.path.join', 'os.path.join', (['args.ckpt', 'args.id'], {}), '(args.ckpt, args.id)\n', (18786, 18806), False, 'import os\n'), ((18822, 18863), 'os.path.join', 'os.path.join', (['args.ckpt', '"""visualization/"""'], {}), "(args.ckpt, 'visualization/')\n", (18834, 18863), False, 'import os\n'), ((18879, 18921), 'os.path.join', 'os.path.join', (['args.ckpt', '"""running_log.txt"""'], {}), "(args.ckpt, 'running_log.txt')\n", (18891, 18921), False, 'import os\n'), ((19591, 19613), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (19602, 19613), False, 'import random\n'), ((19618, 19646), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (19635, 19646), False, 'import torch\n'), ((977, 1008), 'numpy.argmax', 'np.argmax', (['total_energy'], {'axis': '(1)'}), '(total_energy, axis=1)\n', (986, 1008), True, 'import numpy as np\n'), ((5669, 5699), 'numpy.stack', 'np.stack', (['index_record'], {'axis': '(1)'}), '(index_record, axis=1)\n', (5677, 5699), True, 'import numpy as np\n'), ((5722, 5760), 'torch.stack', 'torch.stack', (['ordered_pred_masks'], {'dim': '(1)'}), '(ordered_pred_masks, dim=1)\n', (5733, 5760), False, 'import torch\n'), ((5787, 5824), 'torch.stack', 'torch.stack', (['ordered_pred_mags'], {'dim': '(1)'}), '(ordered_pred_mags, dim=1)\n', (5798, 5824), False, 'import torch\n'), ((8445, 8474), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (8467, 8474), False, 'import torch\n'), ((8522, 8558), 'utils.makedirs', 'makedirs', (['self.args.vis'], {'remove': '(True)'}), '(self.args.vis, remove=True)\n', (8530, 8558), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((8641, 8655), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8653, 8655), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((8680, 8694), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8692, 8694), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((8715, 8729), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8727, 8729), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((8750, 8764), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8762, 8764), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((8785, 8799), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8797, 8799), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((11993, 12021), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (12015, 12021), False, 'import torch\n'), ((12043, 12057), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (12055, 12057), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((12078, 12092), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (12090, 12092), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((12194, 12218), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (12216, 12218), False, 'import torch\n'), ((12233, 12252), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (12250, 12252), False, 'import time\n'), ((14756, 14843), 'torch.optim.SGD', 'torch.optim.SGD', (['param_groups'], {'momentum': 'args.beta1', 'weight_decay': 'args.weight_decay'}), '(param_groups, momentum=args.beta1, weight_decay=args.\n weight_decay)\n', (14771, 14843), False, 'import torch\n'), ((18984, 19016), 'utils.makedirs', 'makedirs', (['args.ckpt'], {'remove': '(True)'}), '(args.ckpt, remove=True)\n', (18992, 19016), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((19037, 19073), 'os.path.join', 'os.path.join', (['args.ckpt', '"""args.json"""'], {}), "(args.ckpt, 'args.json')\n", (19049, 19073), False, 'import os\n'), ((1694, 1727), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['mag_mix', 'grid_warp'], {}), '(mag_mix, grid_warp)\n', (1707, 1727), True, 'import torch.nn.functional as F\n'), ((1951, 1971), 'torch.log1p', 'torch.log1p', (['mag_mix'], {}), '(mag_mix)\n', (1962, 1971), False, 'import torch\n'), ((1993, 2023), 'torch.clamp', 'torch.clamp', (['weight', '(0.001)', '(10)'], {}), '(weight, 0.001, 10)\n', (2004, 2023), False, 'import torch\n'), ((2058, 2082), 'torch.ones_like', 'torch.ones_like', (['mag_mix'], {}), '(mag_mix)\n', (2073, 2082), False, 'import torch\n'), ((3062, 3080), 'torch.log', 'torch.log', (['mag_mix'], {}), '(mag_mix)\n', (3071, 3080), False, 'import torch\n'), ((3186, 3231), 'models.activate', 'activate', (['feat_frames[n]', 'args.img_activation'], {}), '(feat_frames[n], args.img_activation)\n', (3194, 3231), False, 'from models import ModelBuilder, activate\n'), ((4882, 4911), 'numpy.stack', 'np.stack', (['energy_list'], {'axis': '(1)'}), '(energy_list, axis=1)\n', (4890, 4911), True, 'import numpy as np\n'), ((5103, 5132), 'torch.stack', 'torch.stack', (['tmp_masks'], {'dim': '(0)'}), '(tmp_masks, dim=0)\n', (5114, 5132), False, 'import torch\n'), ((5226, 5259), 'torch.stack', 'torch.stack', (['tmp_pred_mags'], {'dim': '(0)'}), '(tmp_pred_mags, dim=0)\n', (5237, 5259), False, 'import torch\n'), ((5944, 5971), 'numpy.where', 'np.where', (['(index_record == n)'], {}), '(index_record == n)\n', (5952, 5971), True, 'import numpy as np\n'), ((7450, 7472), 'torch.exp', 'torch.exp', (['log_mag_mix'], {}), '(log_mag_mix)\n', (7459, 7472), False, 'import torch\n'), ((8870, 8911), 'os.path.join', 'os.path.join', (['self.args.vis', '"""index.html"""'], {}), "(self.args.vis, 'index.html')\n", (8882, 8911), False, 'import os\n'), ((10083, 10127), 'utils.calc_metrics', 'calc_metrics', (['batch_data', 'outputs', 'self.args'], {}), '(batch_data, outputs, self.args)\n', (10095, 10127), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((11261, 11306), 'torch.nn.functional.write', 'F.write', (["(metric_output + learning_rate + '\\n')"], {}), "(metric_output + learning_rate + '\\n')\n", (11268, 11306), True, 'import torch.nn.functional as F\n'), ((11906, 11953), 'viz.plot_loss_metrics', 'plot_loss_metrics', (['self.args.ckpt', 'self.history'], {}), '(self.args.ckpt, self.history)\n', (11923, 11953), False, 'from viz import plot_loss_metrics, HTMLVisualizer\n'), ((12345, 12369), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (12367, 12369), False, 'import torch\n'), ((12824, 12848), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (12846, 12848), False, 'import torch\n'), ((12924, 12943), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (12941, 12943), False, 'import time\n'), ((19209, 19241), 'json.dump', 'json.dump', (['args_store', 'json_file'], {}), '(args_store, json_file)\n', (19218, 19241), False, 'import json\n'), ((19312, 19355), 'os.path.join', 'os.path.join', (['args.ckpt', '"""sound_M_best.pth"""'], {}), "(args.ckpt, 'sound_M_best.pth')\n", (19324, 19355), False, 'import os\n'), ((19387, 19430), 'os.path.join', 'os.path.join', (['args.ckpt', '"""frame_M_best.pth"""'], {}), "(args.ckpt, 'frame_M_best.pth')\n", (19399, 19430), False, 'import os\n'), ((19462, 19505), 'os.path.join', 'os.path.join', (['args.ckpt', '"""sound_P_best.pth"""'], {}), "(args.ckpt, 'sound_P_best.pth')\n", (19474, 19505), False, 'import os\n'), ((937, 949), 'numpy.ones', 'np.ones', (['Len'], {}), '(Len)\n', (944, 949), True, 'import numpy as np\n'), ((1785, 1818), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['mags[n]', 'grid_warp'], {}), '(mags[n], grid_warp)\n', (1798, 1818), True, 'import torch.nn.functional as F\n'), ((4057, 4104), 'models.activate', 'activate', (['cur_pred_mask', 'args.output_activation'], {}), '(cur_pred_mask, args.output_activation)\n', (4065, 4104), False, 'from models import ModelBuilder, activate\n'), ((6619, 6663), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['unordered_pred_mag', 'grid_warp'], {}), '(unordered_pred_mag, grid_warp)\n', (6632, 6663), True, 'import torch.nn.functional as F\n'), ((6695, 6742), 'torch.cat', 'torch.cat', (['(pre_sum, unordered_pred_mag)'], {'dim': '(1)'}), '((pre_sum, unordered_pred_mag), dim=1)\n', (6704, 6742), False, 'import torch\n'), ((9621, 9636), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9634, 9636), False, 'import torch\n'), ((3563, 3581), 'torch.log', 'torch.log', (['mag_mix'], {}), '(mag_mix)\n', (3572, 3581), False, 'import torch\n'), ((6394, 6435), 'torch.zeros_like', 'torch.zeros_like', (['unordered_pred_masks[0]'], {}), '(unordered_pred_masks[0])\n', (6410, 6435), False, 'import torch\n'), ((7518, 7556), 'torch.clamp', 'torch.clamp', (['(res_mag_mix - 0.01)'], {'min': '(0)'}), '(res_mag_mix - 0.01, min=0)\n', (7529, 7556), False, 'import torch\n'), ((8245, 8287), 'os.path.join', 'os.path.join', (['"""./logs"""', 'self.args.exp_name'], {}), "('./logs', self.args.exp_name)\n", (8257, 8287), False, 'import os\n'), ((12399, 12418), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (12416, 12418), False, 'import time\n'), ((12879, 12898), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (12896, 12898), False, 'import time\n'), ((1624, 1654), 'utils.warpgrid', 'warpgrid', (['B', '(256)', 'T'], {'warp': '(True)'}), '(B, 256, T, warp=True)\n', (1632, 1654), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n'), ((3416, 3470), 'utils.warpgrid', 'warpgrid', (['B', '(args.stft_frame // 2 + 1)', '(256)'], {'warp': '(False)'}), '(B, args.stft_frame // 2 + 1, 256, warp=False)\n', (3424, 3470), False, 'from utils import AverageMeter, warpgrid, makedirs, calc_metrics, output_visuals\n')]
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Network(nn.Module): def __init__(self, input_dim, output_dim): super(Network, self).__init__() h1, h2 = 200, 100 self.layer_1 = nn.Linear(input_dim, h1) self.layer_2 = nn.Linear(h1, h2) self.layer_3 = nn.Linear(h2, output_dim) def forward(self, X): X = F.relu(self.layer_1(X)) X = F.relu(self.layer_2(X)) X = self.layer_3(X) return X class Predictor: def __init__(self, input_dim, output_dim, eta=1e-3, alpha=0.0): self.model = Network(input_dim, output_dim) self.optimizer = torch.optim.Adam( self.model.parameters(), lr=eta, weight_decay=alpha, ) self.X_full = [] self.y_full = [] def commit(self, X, y): self.X_full.append(X) self.y_full.append(y) def sample(self, batch_size=100): idx = np.random.randint(0, len(self.X_full), size=batch_size) X, y = [], [] for i in idx: X.append(self.X_full[i][:-1, :-2].flatten().copy()) y.append(self.y_full[i][:-1, 5].copy()) return X, y def train(self, epochs=10, batch_size=100): X, y = self.sample(batch_size) X = torch.stack([torch.FloatTensor(x_) for x_ in X]) y = torch.stack([torch.FloatTensor(y_) for y_ in y]) for i in np.arange(epochs): loss = F.mse_loss(self.model(X), y) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return self def predict(self, X): _X = torch.FloatTensor( X[:-1, :-2].flatten().copy() ) y = self.model(_X) return np.c_[X, [*y.data, 0]].astype(np.float64) def predict_many(self, X): X_new = [] for x in X: X_new.append( self.predict(x) ) return np.array(X_new) def save(self, filename, directory): torch.save(self.model.state_dict(), f'{directory}/{filename}_predictor.pth') def load(self, filename, directory): self.model.load_state_dict(torch.load(f'{directory}/{filename}_predictor.pth')) class NetworkDropout(nn.Module): def __init__(self, input_dim, output_dim): super(NetworkDropout, self).__init__() h1, h2 = 200, 100 prob = 0.1 self.layer_1 = nn.Linear(input_dim, h1) self.dropout_1 = nn.Dropout(prob) self.layer_2 = nn.Linear(h1, h2) self.dropout_2 = nn.Dropout(prob) self.layer_3 = nn.Linear(h2, output_dim) def forward(self, X): X = F.relu(self.layer_1(X)) X = self.dropout_1(X) X = F.relu(self.layer_2(X)) X = self.dropout_2(X) X = self.layer_3(X) return X class DropoutPredictor(Predictor): def __init__(self, input_dim, output_dim, eta=1e-3, alpha=0.0): super(DropoutPredictor, self).__init__( input_dim, output_dim, eta=1e-3, alpha=0.0, ) self.model = NetworkDropout(input_dim, output_dim) self.optimizer = torch.optim.Adam( self.model.parameters(), lr=eta, weight_decay=alpha, )
[ "torch.nn.Dropout", "torch.load", "numpy.array", "torch.nn.Linear", "torch.FloatTensor", "numpy.arange" ]
[((284, 308), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'h1'], {}), '(input_dim, h1)\n', (293, 308), True, 'import torch.nn as nn\n'), ((333, 350), 'torch.nn.Linear', 'nn.Linear', (['h1', 'h2'], {}), '(h1, h2)\n', (342, 350), True, 'import torch.nn as nn\n'), ((375, 400), 'torch.nn.Linear', 'nn.Linear', (['h2', 'output_dim'], {}), '(h2, output_dim)\n', (384, 400), True, 'import torch.nn as nn\n'), ((1615, 1632), 'numpy.arange', 'np.arange', (['epochs'], {}), '(epochs)\n', (1624, 1632), True, 'import numpy as np\n'), ((2248, 2263), 'numpy.array', 'np.array', (['X_new'], {}), '(X_new)\n', (2256, 2263), True, 'import numpy as np\n'), ((2781, 2805), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'h1'], {}), '(input_dim, h1)\n', (2790, 2805), True, 'import torch.nn as nn\n'), ((2832, 2848), 'torch.nn.Dropout', 'nn.Dropout', (['prob'], {}), '(prob)\n', (2842, 2848), True, 'import torch.nn as nn\n'), ((2872, 2889), 'torch.nn.Linear', 'nn.Linear', (['h1', 'h2'], {}), '(h1, h2)\n', (2881, 2889), True, 'import torch.nn as nn\n'), ((2916, 2932), 'torch.nn.Dropout', 'nn.Dropout', (['prob'], {}), '(prob)\n', (2926, 2932), True, 'import torch.nn as nn\n'), ((2956, 2981), 'torch.nn.Linear', 'nn.Linear', (['h2', 'output_dim'], {}), '(h2, output_dim)\n', (2965, 2981), True, 'import torch.nn as nn\n'), ((2490, 2541), 'torch.load', 'torch.load', (['f"""{directory}/{filename}_predictor.pth"""'], {}), "(f'{directory}/{filename}_predictor.pth')\n", (2500, 2541), False, 'import torch\n'), ((1488, 1509), 'torch.FloatTensor', 'torch.FloatTensor', (['x_'], {}), '(x_)\n', (1505, 1509), False, 'import torch\n'), ((1549, 1570), 'torch.FloatTensor', 'torch.FloatTensor', (['y_'], {}), '(y_)\n', (1566, 1570), False, 'import torch\n')]
import numpy as np from sklearn import preprocessing import math X_ = np.genfromtxt('data_nextyear.csv',delimiter=',',skip_header = 2,dtype=float,usecols=(range(2,51))) scaler = preprocessing.StandardScaler().fit(X_) X = scaler.transform(X_) Y = np.genfromtxt('data_nextyear.csv',delimiter=',',skip_header = 2,dtype=float,usecols=(51)) M,N = X.shape correlations = np.zeros(N) for feature in range(N): correlations[feature] = math.fabs(np.corrcoef(X[:,feature],Y)[0][1]) indices_sorted = np.argsort(-correlations) # print indices_sorted columns = indices_sorted + 2 print(','.join(str(x) for x in columns)) print(np.sort(correlations)[::-1])
[ "numpy.corrcoef", "numpy.sort", "numpy.argsort", "sklearn.preprocessing.StandardScaler", "numpy.zeros", "numpy.genfromtxt" ]
[((248, 342), 'numpy.genfromtxt', 'np.genfromtxt', (['"""data_nextyear.csv"""'], {'delimiter': '""","""', 'skip_header': '(2)', 'dtype': 'float', 'usecols': '(51)'}), "('data_nextyear.csv', delimiter=',', skip_header=2, dtype=\n float, usecols=51)\n", (261, 342), True, 'import numpy as np\n'), ((368, 379), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (376, 379), True, 'import numpy as np\n'), ((492, 517), 'numpy.argsort', 'np.argsort', (['(-correlations)'], {}), '(-correlations)\n', (502, 517), True, 'import numpy as np\n'), ((180, 210), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (208, 210), False, 'from sklearn import preprocessing\n'), ((617, 638), 'numpy.sort', 'np.sort', (['correlations'], {}), '(correlations)\n', (624, 638), True, 'import numpy as np\n'), ((440, 469), 'numpy.corrcoef', 'np.corrcoef', (['X[:, feature]', 'Y'], {}), '(X[:, feature], Y)\n', (451, 469), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf-8 import pandas as pd import numpy as np import os import datetime import json import git import sys repo = git.Repo("./", search_parent_directories=True) homedir = repo.working_dir def makeHMMUnSupData(Input, colname, fipsname): #Takes input dataframe, and gives out HMM format of Input data, a list of lists #of the colname value, each list in the set represents one fips code. Output = [] for fips in Input[fipsname].unique(): temp = list(Input[Input[fipsname] == fips][colname]) Output.append(temp) return Output def monotonicCol(Data, colname): #Takes a column that should have monotonically increasing data for a column (number of deaths) #and adjusts the column to ensure this property, iterating backwards through each fips code's entries ls = [] tempvals = [] for fips in Data.FIPS.unique(): vals = list(Data[Data['FIPS'] == fips][colname]) flag = True for val in reversed(vals): if flag: flag = False maxval = val tempvals.append(maxval) else: if val > maxval: tempvals.append(maxval) else: maxval = val tempvals.append(val) ls.extend(reversed(tempvals)) tempvals = [] return ls def cumtoDaily(Data, colname): #Takes cumulative column data and turns the data into daily changes ls = [] column = Data[colname] for fips in Data.FIPS.unique(): ls.extend(list(Data[Data['FIPS'] == fips][colname].diff().fillna(0))) return ls #Cumulative Death Data NYT_tot = pd.read_csv(f"{homedir}/data/us/covid/nyt_us_counties.csv") NYT_tot.loc[NYT_tot["county"]=='New York City', "fips"]=36061 NYT_tot = NYT_tot.drop(columns=['county','state']).sort_values(['fips','date']).reset_index(drop=True) NYT_tot = NYT_tot.dropna(subset=['fips']) NYT_tot['fips'] = NYT_tot.fips.astype(int) NYT_tot['date'] = pd.to_datetime(NYT_tot['date']) NYT_tot['id'] = NYT_tot.fips.astype(str).str.cat(NYT_tot.date.astype(str), sep=', ') #Making new parameter for deathrate NYT_tot['deathrate'] = NYT_tot['deaths']/NYT_tot['cases'] NYT_tot = NYT_tot.fillna(0) #multiplying death rate by 1000 to give integer state values NYT_tot['deathstate'] = NYT_tot['deathrate']*1000 NYT_tot['deathstate'] = NYT_tot['deathstate'].astype(int) #Differenced Daily Death Data NYT_daily = pd.read_csv(f"{homedir}/data/us/covid/nyt_us_counties_daily.csv") NYT_daily.loc[NYT_daily["county"]=='New York City', "fips"]=36061 NYT_daily = NYT_daily.drop(columns=['county','state']).sort_values(['fips','date']).reset_index(drop=True) NYT_daily['fips'] = NYT_daily.fips.astype(int) NYT_daily['date'] = pd.to_datetime(NYT_daily['date']) NYT_daily['id'] = NYT_daily.fips.astype(str).str.cat(NYT_daily.date.astype(str), sep=', ') FirstDay = min(NYT_daily.date.unique()) LastDay = max(NYT_daily.date.unique()) #Making a time-warping of NYT daily data, so each county has a value at the starting day of 2020-01-21 # and then a final value at the most recent day NYT_daily_Warp = NYT_daily for fips in NYT_daily.fips.unique(): rows = NYT_daily[NYT_daily['fips'] == fips] #adding in the first day values if FirstDay not in rows.date.unique(): NYT_daily_Warp = NYT_daily_Warp.append({'fips': fips, 'date': pd.to_datetime('2020-01-21'), 'cases': 0, 'deaths' : 0, 'id' : str(fips) + ', 2020-01-21'}, ignore_index=True) #making sure each entry has the final day values if LastDay not in rows.date.unique(): NYT_daily_Warp = NYT_daily_Warp[NYT_daily_Warp['fips'] != fips] NYT_daily_Warp = NYT_daily_Warp.sort_values(['fips','date']).reset_index(drop=True) NYT_daily_Warp.to_csv('NYT_daily_Warp.csv') NYT_daily_Warp_Death = makeHMMUnSupData(NYT_daily_Warp, 'deaths', 'fips') #This is a list of all the counties and dates County_List = list(NYT_daily.fips.unique()) Date_List = list(NYT_daily.date.unique()) #This creates a base dataframe that contains all pairs of FIPS codes with the valid dates given in Air_Qual CL, DL = pd.core.reshape.util.cartesian_product([County_List, Date_List]) BaseFrame = pd.DataFrame(dict(fips=CL, date=DL)).sort_values(['fips','date']).reset_index(drop=True) BaseFrame['id'] = BaseFrame.fips.astype(str).str.cat(BaseFrame.date.astype(str), sep=', ') #Making frame of all deaths at all dates to properly do DTW clustering NYT_daily_Filled = BaseFrame.join(NYT_daily.set_index('id'), on='id', how='outer', lsuffix='',rsuffix='_x').sort_values(['fips', 'date']).drop(columns=['fips_x','date_x']).fillna(0).drop_duplicates(subset=['fips','date']).reset_index(drop=True) NYT_daily_Filled.to_csv('NYT_daily_Filled.csv') #List of lists of daily death count for each county, starting 1/23/20, ending most recent date. NYT_daily_Death_Filled = makeHMMUnSupData(NYT_daily_Filled, 'deaths', 'fips') #JHU Data JHU_tot = pd.read_csv(f"{homedir}/data/us/covid/JHU_daily_US.csv").sort_values(['FIPS','Date']) FIPSlist = JHU_tot.FIPS.unique() Datelist = JHU_tot.Date.unique() Datepair = [Datelist[0],Datelist[-1]] #Getting rid of unneded fips code in the list of total codes for fips in FIPSlist: rows = JHU_tot[JHU_tot['FIPS'] == fips] datelist = rows.Date.unique() datepair = [datelist[0],datelist[-1]] if np.array_equal(Datepair,datepair) != True: JHU_tot = JHU_tot.drop(list(JHU_tot[JHU_tot['FIPS'] == fips].index)) JHU_tot = JHU_tot.sort_values(['FIPS','Date']).reset_index(drop=True) d = {'FIPS': JHU_tot['FIPS'], 'Date' : JHU_tot['Date'], 'Confirmed' : monotonicCol(JHU_tot,'Confirmed'), 'Deaths' : monotonicCol(JHU_tot,'Deaths'),'Active' : monotonicCol(JHU_tot,'Active'), 'Recovered' : monotonicCol(JHU_tot,'Recovered')} JHU_mono = pd.DataFrame(data=d) d = {'FIPS': JHU_mono['FIPS'], 'Date' : JHU_mono['Date'], 'Confirmed' : cumtoDaily(JHU_mono,'Confirmed'), 'Deaths' : cumtoDaily(JHU_mono,'Deaths'),'Active' : cumtoDaily(JHU_mono,'Active'), 'Recovered' : cumtoDaily(JHU_mono,'Recovered')} #Daily changing data based on monotonically transformed data JHU_daily = pd.DataFrame(data=d) JHU_daily.to_csv('JHU_Daily.csv') #List of lists of daily death count for each county, starting 3/23/20, ending most recent date. JHU_daily_death = makeHMMUnSupData(JHU_daily, 'Deaths', 'FIPS') #Saving the death data filesw f = open('NYT_daily_Warp_Death.txt', 'w') json.dump(NYT_daily_Warp_Death, f) f.close() g = open('NYT_daily_Death_Filled.txt', 'w') json.dump(NYT_daily_Death_Filled, g) g.close() h = open('JHU_daily_death.txt', 'w') json.dump(JHU_daily_death, h) h.close()
[ "pandas.core.reshape.util.cartesian_product", "pandas.read_csv", "json.dump", "numpy.array_equal", "git.Repo", "pandas.DataFrame", "pandas.to_datetime" ]
[((144, 190), 'git.Repo', 'git.Repo', (['"""./"""'], {'search_parent_directories': '(True)'}), "('./', search_parent_directories=True)\n", (152, 190), False, 'import git\n'), ((1700, 1759), 'pandas.read_csv', 'pd.read_csv', (['f"""{homedir}/data/us/covid/nyt_us_counties.csv"""'], {}), "(f'{homedir}/data/us/covid/nyt_us_counties.csv')\n", (1711, 1759), True, 'import pandas as pd\n'), ((2028, 2059), 'pandas.to_datetime', 'pd.to_datetime', (["NYT_tot['date']"], {}), "(NYT_tot['date'])\n", (2042, 2059), True, 'import pandas as pd\n'), ((2480, 2545), 'pandas.read_csv', 'pd.read_csv', (['f"""{homedir}/data/us/covid/nyt_us_counties_daily.csv"""'], {}), "(f'{homedir}/data/us/covid/nyt_us_counties_daily.csv')\n", (2491, 2545), True, 'import pandas as pd\n'), ((2786, 2819), 'pandas.to_datetime', 'pd.to_datetime', (["NYT_daily['date']"], {}), "(NYT_daily['date'])\n", (2800, 2819), True, 'import pandas as pd\n'), ((4139, 4203), 'pandas.core.reshape.util.cartesian_product', 'pd.core.reshape.util.cartesian_product', (['[County_List, Date_List]'], {}), '([County_List, Date_List])\n', (4177, 4203), True, 'import pandas as pd\n'), ((5804, 5824), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (5816, 5824), True, 'import pandas as pd\n'), ((6135, 6155), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (6147, 6155), True, 'import pandas as pd\n'), ((6423, 6457), 'json.dump', 'json.dump', (['NYT_daily_Warp_Death', 'f'], {}), '(NYT_daily_Warp_Death, f)\n', (6432, 6457), False, 'import json\n'), ((6513, 6549), 'json.dump', 'json.dump', (['NYT_daily_Death_Filled', 'g'], {}), '(NYT_daily_Death_Filled, g)\n', (6522, 6549), False, 'import json\n'), ((6598, 6627), 'json.dump', 'json.dump', (['JHU_daily_death', 'h'], {}), '(JHU_daily_death, h)\n', (6607, 6627), False, 'import json\n'), ((4960, 5016), 'pandas.read_csv', 'pd.read_csv', (['f"""{homedir}/data/us/covid/JHU_daily_US.csv"""'], {}), "(f'{homedir}/data/us/covid/JHU_daily_US.csv')\n", (4971, 5016), True, 'import pandas as pd\n'), ((5362, 5396), 'numpy.array_equal', 'np.array_equal', (['Datepair', 'datepair'], {}), '(Datepair, datepair)\n', (5376, 5396), True, 'import numpy as np\n'), ((3406, 3434), 'pandas.to_datetime', 'pd.to_datetime', (['"""2020-01-21"""'], {}), "('2020-01-21')\n", (3420, 3434), True, 'import pandas as pd\n')]
import glob import cv2 import os import numpy as np def disp_map(I): map = [[0,0,0,114], [0,0,1,185], [1,0,0,114], [1,0,1,174], [0,1,0,114], [0,1,1,185],[1,1,0,114], [1,1,1,0]] map = np.array(map,dtype=np.int) bins = map[:-1,3] cbins = np.cumsum(bins) bins = bins / cbins[-1] cbins = cbins[:-1] / cbins[-1] ind = sum(np.tile(I,[6,1]) > np.tile(cbins,[I.size,1]).T) bins = 1 / bins cbins = np.insert(cbins,0,0.0) t1 = [cbins[t] for t in ind] t1 = np.array(t1) t2 = [bins[t] for t in ind] t2 = np.array(t2) I = (I-t1) * t2 #map(ind+1,1:3) .* repmat(I, [1 3]) t3 = [map[t,:3] for t in ind] t3 = np.array(t3) t3 = t3 * np.tile(1-I.T,[3,1]).T t4 = [map[t+1,:3] for t in ind] t4 = np.array(t4) t4 = t4 * np.tile(I.T,[3,1]).T t5 = t3 + t4 t5[np.where(t5<0)] = 0 t5[np.where(t5>1)] = 1 t5 = np.reshape(t5,[img.shape[0],img.shape[1],3],order='F') * 255 t5 = np.array(t5,dtype=np.uint8) t5 = cv2.cvtColor(t5,cv2.COLOR_RGB2BGR) return t5 origin_disp_dir = './_output/disparities/' all_disps = glob.glob(origin_disp_dir + '*.png') output_disp_dir = './_output/color_disp/' if not os.path.exists(output_disp_dir): os.makedirs(output_disp_dir) max_disp = 256 for disp in all_disps: print('colorlize ',disp) img = cv2.imread(disp,-1) I = np.uint16(np.around(img/256)) I = np.array(I,dtype=np.float) I = (I.T.flatten()) / max_disp r = disp_map(I) output_color_disp_name = output_disp_dir + disp.split('/')[-1] cv2.imwrite(output_color_disp_name, r)
[ "numpy.insert", "os.path.exists", "cv2.imwrite", "numpy.tile", "numpy.reshape", "os.makedirs", "numpy.where", "numpy.array", "numpy.around", "cv2.cvtColor", "numpy.cumsum", "cv2.imread", "glob.glob" ]
[((1052, 1088), 'glob.glob', 'glob.glob', (["(origin_disp_dir + '*.png')"], {}), "(origin_disp_dir + '*.png')\n", (1061, 1088), False, 'import glob\n'), ((195, 222), 'numpy.array', 'np.array', (['map'], {'dtype': 'np.int'}), '(map, dtype=np.int)\n', (203, 222), True, 'import numpy as np\n'), ((252, 267), 'numpy.cumsum', 'np.cumsum', (['bins'], {}), '(bins)\n', (261, 267), True, 'import numpy as np\n'), ((416, 440), 'numpy.insert', 'np.insert', (['cbins', '(0)', '(0.0)'], {}), '(cbins, 0, 0.0)\n', (425, 440), True, 'import numpy as np\n'), ((478, 490), 'numpy.array', 'np.array', (['t1'], {}), '(t1)\n', (486, 490), True, 'import numpy as np\n'), ((528, 540), 'numpy.array', 'np.array', (['t2'], {}), '(t2)\n', (536, 540), True, 'import numpy as np\n'), ((636, 648), 'numpy.array', 'np.array', (['t3'], {}), '(t3)\n', (644, 648), True, 'import numpy as np\n'), ((726, 738), 'numpy.array', 'np.array', (['t4'], {}), '(t4)\n', (734, 738), True, 'import numpy as np\n'), ((914, 942), 'numpy.array', 'np.array', (['t5'], {'dtype': 'np.uint8'}), '(t5, dtype=np.uint8)\n', (922, 942), True, 'import numpy as np\n'), ((949, 984), 'cv2.cvtColor', 'cv2.cvtColor', (['t5', 'cv2.COLOR_RGB2BGR'], {}), '(t5, cv2.COLOR_RGB2BGR)\n', (961, 984), False, 'import cv2\n'), ((1138, 1169), 'os.path.exists', 'os.path.exists', (['output_disp_dir'], {}), '(output_disp_dir)\n', (1152, 1169), False, 'import os\n'), ((1173, 1201), 'os.makedirs', 'os.makedirs', (['output_disp_dir'], {}), '(output_disp_dir)\n', (1184, 1201), False, 'import os\n'), ((1276, 1296), 'cv2.imread', 'cv2.imread', (['disp', '(-1)'], {}), '(disp, -1)\n', (1286, 1296), False, 'import cv2\n'), ((1338, 1365), 'numpy.array', 'np.array', (['I'], {'dtype': 'np.float'}), '(I, dtype=np.float)\n', (1346, 1365), True, 'import numpy as np\n'), ((1484, 1522), 'cv2.imwrite', 'cv2.imwrite', (['output_color_disp_name', 'r'], {}), '(output_color_disp_name, r)\n', (1495, 1522), False, 'import cv2\n'), ((793, 809), 'numpy.where', 'np.where', (['(t5 < 0)'], {}), '(t5 < 0)\n', (801, 809), True, 'import numpy as np\n'), ((818, 834), 'numpy.where', 'np.where', (['(t5 > 1)'], {}), '(t5 > 1)\n', (826, 834), True, 'import numpy as np\n'), ((846, 904), 'numpy.reshape', 'np.reshape', (['t5', '[img.shape[0], img.shape[1], 3]'], {'order': '"""F"""'}), "(t5, [img.shape[0], img.shape[1], 3], order='F')\n", (856, 904), True, 'import numpy as np\n'), ((1312, 1332), 'numpy.around', 'np.around', (['(img / 256)'], {}), '(img / 256)\n', (1321, 1332), True, 'import numpy as np\n'), ((339, 357), 'numpy.tile', 'np.tile', (['I', '[6, 1]'], {}), '(I, [6, 1])\n', (346, 357), True, 'import numpy as np\n'), ((661, 685), 'numpy.tile', 'np.tile', (['(1 - I.T)', '[3, 1]'], {}), '(1 - I.T, [3, 1])\n', (668, 685), True, 'import numpy as np\n'), ((751, 771), 'numpy.tile', 'np.tile', (['I.T', '[3, 1]'], {}), '(I.T, [3, 1])\n', (758, 771), True, 'import numpy as np\n'), ((358, 385), 'numpy.tile', 'np.tile', (['cbins', '[I.size, 1]'], {}), '(cbins, [I.size, 1])\n', (365, 385), True, 'import numpy as np\n')]
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array import numpy as np import imutils import cv2 confidence_bound = 0.5 def mask_prediction(frame, face_net, mask_net): (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0)) face_net.setInput(blob) detections = face_net.forward() faces = [] locs = [] preds = [] for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > confidence_bound: box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (start_x, start_y, end_x, end_y) = box.astype("int") (start_x, start_y) = (max(0, start_x), max(0, start_y)) (end_x, end_y) = (min(w - 1, end_x), min(h - 1, end_y)) face = frame[start_y:end_y, start_x:end_x] face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face = cv2.resize(face, (224, 224)) face = img_to_array(face) face = preprocess_input(face) faces.append(face) locs.append((start_x, start_y, end_x, end_y)) if len(faces) > 0: faces = np.array(faces, dtype="float32") preds = mask_net.predict(faces, batch_size=32) return (locs, preds)
[ "cv2.dnn.blobFromImage", "numpy.array", "tensorflow.keras.applications.mobilenet_v2.preprocess_input", "cv2.cvtColor", "tensorflow.keras.preprocessing.image.img_to_array", "cv2.resize" ]
[((287, 355), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['frame', '(1.0)', '(300, 300)', '(104.0, 177.0, 123.0)'], {}), '(frame, 1.0, (300, 300), (104.0, 177.0, 123.0))\n', (308, 355), False, 'import cv2\n'), ((1102, 1134), 'numpy.array', 'np.array', (['faces'], {'dtype': '"""float32"""'}), "(faces, dtype='float32')\n", (1110, 1134), True, 'import numpy as np\n'), ((860, 897), 'cv2.cvtColor', 'cv2.cvtColor', (['face', 'cv2.COLOR_BGR2RGB'], {}), '(face, cv2.COLOR_BGR2RGB)\n', (872, 897), False, 'import cv2\n'), ((908, 936), 'cv2.resize', 'cv2.resize', (['face', '(224, 224)'], {}), '(face, (224, 224))\n', (918, 936), False, 'import cv2\n'), ((947, 965), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['face'], {}), '(face)\n', (959, 965), False, 'from tensorflow.keras.preprocessing.image import img_to_array\n'), ((976, 998), 'tensorflow.keras.applications.mobilenet_v2.preprocess_input', 'preprocess_input', (['face'], {}), '(face)\n', (992, 998), False, 'from tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n'), ((605, 627), 'numpy.array', 'np.array', (['[w, h, w, h]'], {}), '([w, h, w, h])\n', (613, 627), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2021, Amazon Web Services. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import cv2 import pycocotools.mask as maskUtils from collections import defaultdict from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval def process_boxes(image_info, box_coordinates): """Process the model prediction for COCO eval.""" '''image_info = prediction['image_info'] box_coordinates = prediction['detection_boxes']''' processed_box_coordinates = np.zeros_like(box_coordinates) for image_id in range(box_coordinates.shape[0]): scale = image_info[image_id][2] for box_id in range(box_coordinates.shape[1]): # Map [y1, x1, y2, x2] -> [x1, y1, w, h] and multiply detections # Map [y1, x1, y2, x2] -> [x1, y1, w, h] and multiply detections # by image scale. y1, x1, y2, x2 = box_coordinates[image_id, box_id, :] new_box = scale * np.array([x1, y1, x2 - x1, y2 - y1]) processed_box_coordinates[image_id, box_id, :] = new_box #prediction['detection_boxes'] = processed_box_coordinates return processed_box_coordinates def generate_segmentation_from_masks(masks, detected_boxes, image_height, image_width, is_image_mask=False): """Generates segmentation result from instance masks. Args: masks: a numpy array of shape [N, mask_height, mask_width] representing the instance masks w.r.t. the `detected_boxes`. detected_boxes: a numpy array of shape [N, 4] representing the reference bounding boxes. image_height: an integer representing the height of the image. image_width: an integer representing the width of the image. is_image_mask: bool. True: input masks are whole-image masks. False: input masks are bounding-box level masks. Returns: segms: a numpy array of shape [N, image_height, image_width] representing the instance masks *pasted* on the image canvas. """ def expand_boxes(boxes, scale): """Expands an array of boxes by a given scale.""" # Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/boxes.py#L227 # The `boxes` in the reference implementation is in [x1, y1, x2, y2] form, # whereas `boxes` here is in [x1, y1, w, h] form w_half = boxes[:, 2] * .5 h_half = boxes[:, 3] * .5 x_c = boxes[:, 0] + w_half y_c = boxes[:, 1] + h_half w_half *= scale h_half *= scale boxes_exp = np.zeros(boxes.shape) boxes_exp[:, 0] = x_c - w_half boxes_exp[:, 2] = x_c + w_half boxes_exp[:, 1] = y_c - h_half boxes_exp[:, 3] = y_c + h_half return boxes_exp # Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/core/test.py#L812 # To work around an issue with cv2.resize (it seems to automatically pad # with repeated border values), we manually zero-pad the masks by 1 pixel # prior to resizing back to the original image resolution. This prevents # "top hat" artifacts. We therefore need to expand the reference boxes by an # appropriate factor. _, mask_height, mask_width = masks.shape scale = max((mask_width + 2.0) / mask_width, (mask_height + 2.0) / mask_height) ref_boxes = expand_boxes(detected_boxes, scale) ref_boxes = ref_boxes.astype(np.int32) padded_mask = np.zeros((mask_height + 2, mask_width + 2), dtype=np.float32) segms = [] for mask_ind, mask in enumerate(masks): im_mask = np.zeros((image_height, image_width), dtype=np.uint8) if is_image_mask: # Process whole-image masks. im_mask[:, :] = mask[:, :] else: # Process mask inside bounding boxes. padded_mask[1:-1, 1:-1] = mask[:, :] ref_box = ref_boxes[mask_ind, :] w = ref_box[2] - ref_box[0] + 1 h = ref_box[3] - ref_box[1] + 1 w = np.maximum(w, 1) h = np.maximum(h, 1) mask = cv2.resize(padded_mask, (w, h)) mask = np.array(mask > 0.5, dtype=np.uint8) x_0 = max(ref_box[0], 0) x_1 = min(ref_box[2] + 1, image_width) y_0 = max(ref_box[1], 0) y_1 = min(ref_box[3] + 1, image_height) im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - ref_box[1]):(y_1 - ref_box[1]), ( x_0 - ref_box[0]):(x_1 - ref_box[0])] segms.append(im_mask) segms = np.array(segms) assert masks.shape[0] == segms.shape[0] return segms def format_predictions(image_id, detection_boxes, detection_scores, detection_classes, rles): box_predictions = [] mask_predictions = [] detection_count = len(detection_scores) for i in range(detection_count): box_predictions.append({'image_id': int(image_id), 'category_id': int(detection_classes[i]), 'bbox': list(map(lambda x: float(round(x, 2)), detection_boxes[i])), 'score': float(detection_scores[i])}) if rles: segmentation = {'size': rles[i]['size'], 'counts': rles[i]['counts'].decode()} mask_predictions.append({'image_id': int(image_id), 'category_id': int(detection_classes[i]), 'score': float(detection_scores[i]), 'segmentation': segmentation}) return box_predictions, mask_predictions def process_prediction(prediction): prediction.update({'detection_boxes': process_boxes(prediction['image_info'], prediction['detection_boxes'])}) batch_size = prediction['num_detections'].shape[0] box_predictions = [] mask_predictions = [] imgIds = [] for i in range(batch_size): detection_boxes = prediction['detection_boxes'][i] detection_classes = prediction['detection_classes'][i] detection_scores = prediction['detection_scores'][i] source_id = prediction['source_ids'][i] detection_masks = prediction['detection_masks'][i] if 'detection_masks' in prediction.keys() else None segments = generate_segmentation_from_masks(detection_masks, detection_boxes, int(prediction['image_info'][i][3]), int(prediction['image_info'][i][4])) if detection_masks is not None else None rles = None if detection_masks is not None: rles = [ maskUtils.encode(np.asfortranarray(instance_mask.astype(np.uint8))) for instance_mask in segments ] formatted_predictions = format_predictions(source_id, detection_boxes, detection_scores, detection_classes, rles) imgIds.append(source_id) box_predictions.extend(formatted_predictions[0]) mask_predictions.extend(formatted_predictions[1]) return imgIds, box_predictions, mask_predictions def build_output_dict(iou, stats, verbose=False): if verbose: format_string = ["AP 0.50:0.95 all", "AP 0.50 all", "AP 0.75 all", "AP 0.50:0.95 small", "AP 0.50:0.95 medium", "AP 0.50:0.95 large", "AR 0.50:0.95 all", "AR 0.50 all", "AR 0.75 all", "AR 0.50:0.95 small", "AR 0.50:0.95 medium", "AR 0.50:0.95 large"] stat_dict = {"{0} {1}".format(iou, i): j for i,j in zip(format_string, stats)} else: stat_dict = {"{0} AP 0.50:0.95 all".format(iou): stats[0]} return stat_dict def evaluate_coco_predictions(annotations_file, iou_types, predictions, verbose=False): cocoGt = COCO(annotation_file=annotations_file, use_ext=True) stat_dict = dict() for iou in iou_types: cocoDt = cocoGt.loadRes(predictions[iou], use_ext=True) cocoEval = COCOeval(cocoGt, cocoDt, iouType=iou, use_ext=True) cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() stat_dict[iou] = build_output_dict(iou, cocoEval.stats, verbose) return stat_dict
[ "pycocotools.cocoeval.COCOeval", "cv2.resize", "pycocotools.coco.COCO", "numpy.array", "numpy.zeros", "numpy.maximum", "numpy.zeros_like" ]
[((1072, 1102), 'numpy.zeros_like', 'np.zeros_like', (['box_coordinates'], {}), '(box_coordinates)\n', (1085, 1102), True, 'import numpy as np\n'), ((4160, 4221), 'numpy.zeros', 'np.zeros', (['(mask_height + 2, mask_width + 2)'], {'dtype': 'np.float32'}), '((mask_height + 2, mask_width + 2), dtype=np.float32)\n', (4168, 4221), True, 'import numpy as np\n'), ((5241, 5256), 'numpy.array', 'np.array', (['segms'], {}), '(segms)\n', (5249, 5256), True, 'import numpy as np\n'), ((9079, 9131), 'pycocotools.coco.COCO', 'COCO', ([], {'annotation_file': 'annotations_file', 'use_ext': '(True)'}), '(annotation_file=annotations_file, use_ext=True)\n', (9083, 9131), False, 'from pycocotools.coco import COCO\n'), ((3256, 3277), 'numpy.zeros', 'np.zeros', (['boxes.shape'], {}), '(boxes.shape)\n', (3264, 3277), True, 'import numpy as np\n'), ((4299, 4352), 'numpy.zeros', 'np.zeros', (['(image_height, image_width)'], {'dtype': 'np.uint8'}), '((image_height, image_width), dtype=np.uint8)\n', (4307, 4352), True, 'import numpy as np\n'), ((9264, 9315), 'pycocotools.cocoeval.COCOeval', 'COCOeval', (['cocoGt', 'cocoDt'], {'iouType': 'iou', 'use_ext': '(True)'}), '(cocoGt, cocoDt, iouType=iou, use_ext=True)\n', (9272, 9315), False, 'from pycocotools.cocoeval import COCOeval\n'), ((4722, 4738), 'numpy.maximum', 'np.maximum', (['w', '(1)'], {}), '(w, 1)\n', (4732, 4738), True, 'import numpy as np\n'), ((4755, 4771), 'numpy.maximum', 'np.maximum', (['h', '(1)'], {}), '(h, 1)\n', (4765, 4771), True, 'import numpy as np\n'), ((4791, 4822), 'cv2.resize', 'cv2.resize', (['padded_mask', '(w, h)'], {}), '(padded_mask, (w, h))\n', (4801, 4822), False, 'import cv2\n'), ((4842, 4878), 'numpy.array', 'np.array', (['(mask > 0.5)'], {'dtype': 'np.uint8'}), '(mask > 0.5, dtype=np.uint8)\n', (4850, 4878), True, 'import numpy as np\n'), ((1533, 1569), 'numpy.array', 'np.array', (['[x1, y1, x2 - x1, y2 - y1]'], {}), '([x1, y1, x2 - x1, y2 - y1])\n', (1541, 1569), True, 'import numpy as np\n')]
"""This module contains common inference methods.""" __all__ = ['Rejection', 'SMC', 'AdaptiveDistanceSMC', 'BayesianOptimization', 'BOLFI', 'ROMC'] import logging import timeit from math import ceil import matplotlib.pyplot as plt import numpy as np import scipy.optimize as optim import scipy.spatial as spatial import scipy.stats as ss from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import Pipeline from sklearn.linear_model import LinearRegression from functools import partial from multiprocessing import Pool import elfi.client import elfi.methods.mcmc as mcmc import elfi.visualization.interactive as visin import elfi.visualization.visualization as vis import copy from elfi.loader import get_sub_seed from elfi.methods.bo.acquisition import LCBSC from elfi.methods.bo.gpy_regression import GPyRegression from elfi.methods.bo.utils import stochastic_optimization from elfi.methods.posteriors import BolfiPosterior, RomcPosterior from elfi.methods.results import BolfiSample, OptimizationResult, RomcSample, Sample, SmcSample from elfi.methods.utils import (GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var) from elfi.model.elfi_model import AdaptiveDistance, ComputationContext, ElfiModel, NodeReference from elfi.utils import is_array from elfi.visualization.visualization import ProgressBar logger = logging.getLogger(__name__) # TODO: refactor the plotting functions class ParameterInference: """A base class for parameter inference methods. Attributes ---------- model : elfi.ElfiModel The ELFI graph used by the algorithm output_names : list Names of the nodes whose outputs are included in the batches client : elfi.client.ClientBase The batches are computed in the client max_parallel_batches : int state : dict Stores any changing data related to achieving the objective. Must include a key ``n_batches`` for determining when the inference is finished. objective : dict Holds the data for the algorithm to internally determine how many batches are still needed. You must have a key ``n_batches`` here. By default the algorithm finished when the ``n_batches`` in the state dictionary is equal or greater to the corresponding objective value. batches : elfi.client.BatchHandler Helper class for submitting batches to the client and keeping track of their indexes. pool : elfi.store.OutputPool Pool object for storing and reusing node outputs. """ def __init__(self, model, output_names, batch_size=1, seed=None, pool=None, max_parallel_batches=None): """Construct the inference algorithm object. If you are implementing your own algorithm do not forget to call `super`. Parameters ---------- model : ElfiModel Model to perform the inference with. output_names : list Names of the nodes whose outputs will be requested from the ELFI graph. batch_size : int, optional The number of parameter evaluations in each pass through the ELFI graph. When using a vectorized simulator, using a suitably large batch_size can provide a significant performance boost. seed : int, optional Seed for the data generation from the ElfiModel pool : OutputPool, optional OutputPool both stores and provides precomputed values for batches. max_parallel_batches : int, optional Maximum number of batches allowed to be in computation at the same time. Defaults to number of cores in the client """ model = model.model if isinstance(model, NodeReference) else model if not model.parameter_names: raise ValueError('Model {} defines no parameters'.format(model)) self.model = model.copy() self.output_names = self._check_outputs(output_names) self.client = elfi.client.get_client() # Prepare the computation_context context = ComputationContext( batch_size=batch_size, seed=seed, pool=pool) self.batches = elfi.client.BatchHandler( self.model, context=context, output_names=output_names, client=self.client) self.computation_context = context self.max_parallel_batches = max_parallel_batches or self.client.num_cores if self.max_parallel_batches <= 0: msg = 'Value for max_parallel_batches ({}) must be at least one.'.format( self.max_parallel_batches) if self.client.num_cores == 0: msg += ' Client has currently no workers available. Please make sure ' \ 'the cluster has fully started or set the max_parallel_batches ' \ 'parameter by hand.' raise ValueError(msg) # State and objective should contain all information needed to continue the # inference after an iteration. self.state = dict(n_sim=0, n_batches=0) self.objective = dict() self.progress_bar = ProgressBar(prefix='Progress', suffix='Complete', decimals=1, length=50, fill='=') @property def pool(self): """Return the output pool of the inference.""" return self.computation_context.pool @property def seed(self): """Return the seed of the inference.""" return self.computation_context.seed @property def parameter_names(self): """Return the parameters to be inferred.""" return self.model.parameter_names @property def batch_size(self): """Return the current batch_size.""" return self.computation_context.batch_size def set_objective(self, *args, **kwargs): """Set the objective of the inference. This method sets the objective of the inference (values typically stored in the `self.objective` dict). Returns ------- None """ raise NotImplementedError def extract_result(self): """Prepare the result from the current state of the inference. ELFI calls this method in the end of the inference to return the result. Returns ------- result : elfi.methods.result.Result """ raise NotImplementedError def update(self, batch, batch_index): """Update the inference state with a new batch. ELFI calls this method when a new batch has been computed and the state of the inference should be updated with it. It is also possible to bypass ELFI and call this directly to update the inference. Parameters ---------- batch : dict dict with `self.outputs` as keys and the corresponding outputs for the batch as values batch_index : int Returns ------- None """ self.state['n_batches'] += 1 self.state['n_sim'] += self.batch_size def prepare_new_batch(self, batch_index): """Prepare values for a new batch. ELFI calls this method before submitting a new batch with an increasing index `batch_index`. This is an optional method to override. Use this if you have a need do do preparations, e.g. in Bayesian optimization algorithm, the next acquisition points would be acquired here. If you need provide values for certain nodes, you can do so by constructing a batch dictionary and returning it. See e.g. BayesianOptimization for an example. Parameters ---------- batch_index : int next batch_index to be submitted Returns ------- batch : dict or None Keys should match to node names in the model. These values will override any default values or operations in those nodes. """ pass def plot_state(self, **kwargs): """Plot the current state of the algorithm. Parameters ---------- axes : matplotlib.axes.Axes (optional) figure : matplotlib.figure.Figure (optional) xlim x-axis limits ylim y-axis limits interactive : bool (default False) If true, uses IPython.display to update the cell figure close Close figure in the end of plotting. Used in the end of interactive mode. Returns ------- None """ raise NotImplementedError def infer(self, *args, vis=None, bar=True, **kwargs): """Set the objective and start the iterate loop until the inference is finished. See the other arguments from the `set_objective` method. Parameters ---------- vis : dict, optional Plotting options. More info in self.plot_state method bar : bool, optional Flag to remove (False) or keep (True) the progress bar from/in output. Returns ------- result : Sample """ vis_opt = vis if isinstance(vis, dict) else {} self.set_objective(*args, **kwargs) while not self.finished: self.iterate() if vis: self.plot_state(interactive=True, **vis_opt) if bar: self.progress_bar.update_progressbar(self.state['n_batches'], self._objective_n_batches) self.batches.cancel_pending() if vis: self.plot_state(close=True, **vis_opt) return self.extract_result() def iterate(self): """Advance the inference by one iteration. This is a way to manually progress the inference. One iteration consists of waiting and processing the result of the next batch in succession and possibly submitting new batches. Notes ----- If the next batch is ready, it will be processed immediately and no new batches are submitted. New batches are submitted only while waiting for the next one to complete. There will never be more batches submitted in parallel than the `max_parallel_batches` setting allows. Returns ------- None """ # Submit new batches if allowed while self._allow_submit(self.batches.next_index): next_batch = self.prepare_new_batch(self.batches.next_index) logger.debug("Submitting batch %d" % self.batches.next_index) self.batches.submit(next_batch) # Handle the next ready batch in succession batch, batch_index = self.batches.wait_next() logger.debug('Received batch %d' % batch_index) self.update(batch, batch_index) @property def finished(self): return self._objective_n_batches <= self.state['n_batches'] def _allow_submit(self, batch_index): return (self.max_parallel_batches > self.batches.num_pending and self._has_batches_to_submit and (not self.batches.has_ready())) @property def _has_batches_to_submit(self): return self._objective_n_batches > self.state['n_batches'] + self.batches.num_pending @property def _objective_n_batches(self): """Check that n_batches can be computed from the objective.""" if 'n_batches' in self.objective: n_batches = self.objective['n_batches'] elif 'n_sim' in self.objective: n_batches = ceil(self.objective['n_sim'] / self.batch_size) else: raise ValueError( 'Objective must define either `n_batches` or `n_sim`.') return n_batches def _extract_result_kwargs(self): """Extract common arguments for the ParameterInferenceResult object.""" return { 'method_name': self.__class__.__name__, 'parameter_names': self.parameter_names, 'seed': self.seed, 'n_sim': self.state['n_sim'], 'n_batches': self.state['n_batches'] } @staticmethod def _resolve_model(model, target, default_reference_class=NodeReference): if isinstance(model, ElfiModel) and target is None: raise NotImplementedError( "Please specify the target node of the inference method") if isinstance(model, NodeReference): target = model model = target.model if isinstance(target, str): target = model[target] if not isinstance(target, default_reference_class): raise ValueError('Unknown target node class') return model, target.name def _check_outputs(self, output_names): """Filter out duplicates and check that corresponding nodes exist. Preserves the order. """ output_names = output_names or [] checked_names = [] seen = set() for name in output_names: if isinstance(name, NodeReference): name = name.name if name in seen: continue elif not isinstance(name, str): raise ValueError( 'All output names must be strings, object {} was given'.format(name)) elif not self.model.has_node(name): raise ValueError( 'Node {} output was requested, but it is not in the model.') seen.add(name) checked_names.append(name) return checked_names class Sampler(ParameterInference): def sample(self, n_samples, *args, **kwargs): """Sample from the approximate posterior. See the other arguments from the `set_objective` method. Parameters ---------- n_samples : int Number of samples to generate from the (approximate) posterior *args **kwargs Returns ------- result : Sample """ bar = kwargs.pop('bar', True) return self.infer(n_samples, *args, bar=bar, **kwargs) def _extract_result_kwargs(self): kwargs = super(Sampler, self)._extract_result_kwargs() for state_key in ['threshold', 'accept_rate']: if state_key in self.state: kwargs[state_key] = self.state[state_key] if hasattr(self, 'discrepancy_name'): kwargs['discrepancy_name'] = self.discrepancy_name return kwargs class Rejection(Sampler): """Parallel ABC rejection sampler. For a description of the rejection sampler and a general introduction to ABC, see e.g. Lintusaari et al. 2016. References ---------- <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2016). Fundamentals and Recent Developments in Approximate Bayesian Computation. Systematic Biology. http://dx.doi.org/10.1093/sysbio/syw077. """ def __init__(self, model, discrepancy_name=None, output_names=None, **kwargs): """Initialize the Rejection sampler. Parameters ---------- model : ElfiModel or NodeReference discrepancy_name : str, NodeReference, optional Only needed if model is an ElfiModel output_names : list, optional Additional outputs from the model to be included in the inference result, e.g. corresponding summaries to the acquired samples kwargs: See InferenceMethod """ model, discrepancy_name = self._resolve_model(model, discrepancy_name) output_names = [discrepancy_name] + model.parameter_names + (output_names or []) self.adaptive = isinstance(model[discrepancy_name], AdaptiveDistance) if self.adaptive: model[discrepancy_name].init_adaptation_round() # Summaries are needed as adaptation data self.sums = [sumstat.name for sumstat in model[discrepancy_name].parents] for k in self.sums: if k not in output_names: output_names.append(k) super(Rejection, self).__init__(model, output_names, **kwargs) self.discrepancy_name = discrepancy_name def set_objective(self, n_samples, threshold=None, quantile=None, n_sim=None): """Set objective for inference. Parameters ---------- n_samples : int number of samples to generate threshold : float Acceptance threshold quantile : float In between (0,1). Define the threshold as the p-quantile of all the simulations. n_sim = n_samples/quantile. n_sim : int Total number of simulations. The threshold will be the n_samples-th smallest discrepancy among n_sim simulations. """ if quantile is None and threshold is None and n_sim is None: quantile = .01 self.state = dict(samples=None, threshold=np.Inf, n_sim=0, accept_rate=1, n_batches=0) if quantile: n_sim = ceil(n_samples / quantile) # Set initial n_batches estimate if n_sim: n_batches = ceil(n_sim / self.batch_size) else: n_batches = self.max_parallel_batches self.objective = dict(n_samples=n_samples, threshold=threshold, n_batches=n_batches) # Reset the inference self.batches.reset() def update(self, batch, batch_index): """Update the inference state with a new batch. Parameters ---------- batch : dict dict with `self.outputs` as keys and the corresponding outputs for the batch as values batch_index : int """ super(Rejection, self).update(batch, batch_index) if self.state['samples'] is None: # Lazy initialization of the outputs dict self._init_samples_lazy(batch) self._merge_batch(batch) self._update_state_meta() self._update_objective_n_batches() def extract_result(self): """Extract the result from the current state. Returns ------- result : Sample """ if self.state['samples'] is None: raise ValueError('Nothing to extract') if self.adaptive: self._update_distances() # Take out the correct number of samples outputs = dict() for k, v in self.state['samples'].items(): outputs[k] = v[:self.objective['n_samples']] return Sample(outputs=outputs, **self._extract_result_kwargs()) def _init_samples_lazy(self, batch): """Initialize the outputs dict based on the received batch.""" samples = {} e_noarr = "Node {} output must be in a numpy array of length {} (batch_size)." e_len = "Node {} output has array length {}. It should be equal to the batch size {}." for node in self.output_names: # Check the requested outputs if node not in batch: raise KeyError( "Did not receive outputs for node {}".format(node)) nbatch = batch[node] if not is_array(nbatch): raise ValueError(e_noarr.format(node, self.batch_size)) elif len(nbatch) != self.batch_size: raise ValueError(e_len.format( node, len(nbatch), self.batch_size)) # Prepare samples shape = (self.objective['n_samples'] + self.batch_size, ) + nbatch.shape[1:] dtype = nbatch.dtype if node == self.discrepancy_name: # Initialize the distances to inf samples[node] = np.ones(shape, dtype=dtype) * np.inf else: samples[node] = np.empty(shape, dtype=dtype) self.state['samples'] = samples def _merge_batch(self, batch): # TODO: add index vector so that you can recover the original order samples = self.state['samples'] # Add current batch to adaptation data if self.adaptive: observed_sums = [batch[s] for s in self.sums] self.model[self.discrepancy_name].add_data(*observed_sums) # Check acceptance condition if self.objective.get('threshold') is None: accepted = slice(None, None) num_accepted = self.batch_size else: accepted = batch[self.discrepancy_name] <= self.objective.get('threshold') accepted = np.all(np.atleast_2d(np.transpose(accepted)), axis=0) num_accepted = np.sum(accepted) # Put the acquired samples to the end if num_accepted > 0: for node, v in samples.items(): v[-num_accepted:] = batch[node][accepted] # Sort the smallest to the beginning # note: last (-1) distance measure is used when distance calculation is nested sort_distance = np.atleast_2d(np.transpose(samples[self.discrepancy_name]))[-1] sort_mask = np.argsort(sort_distance) for k, v in samples.items(): v[:] = v[sort_mask] def _update_state_meta(self): """Update `n_sim`, `threshold`, and `accept_rate`.""" o = self.objective s = self.state s['threshold'] = s['samples'][self.discrepancy_name][o['n_samples'] - 1] s['accept_rate'] = min(1, o['n_samples'] / s['n_sim']) def _update_objective_n_batches(self): # Only in the case that the threshold is used if self.objective.get('threshold') is None: return s = self.state t, n_samples = [self.objective.get(k) for k in ('threshold', 'n_samples')] # noinspection PyTypeChecker if s['samples']: accepted = s['samples'][self.discrepancy_name] <= t n_acceptable = np.sum(np.all(np.atleast_2d(np.transpose(accepted)), axis=0)) else: n_acceptable = 0 if n_acceptable == 0: # No acceptable samples found yet, increase n_batches of objective by one in # order to keep simulating n_batches = self.objective['n_batches'] + 1 else: accept_rate_t = n_acceptable / s['n_sim'] # Add some margin to estimated n_batches. One could also use confidence # bounds here margin = .2 * self.batch_size * int(n_acceptable < n_samples) n_batches = (n_samples / accept_rate_t + margin) / self.batch_size n_batches = ceil(n_batches) self.objective['n_batches'] = n_batches logger.debug('Estimated objective n_batches=%d' % self.objective['n_batches']) def _update_distances(self): # Update adaptive distance node self.model[self.discrepancy_name].update_distance() # Recalculate distances in current sample nums = self.objective['n_samples'] data = {s: self.state['samples'][s][:nums] for s in self.sums} ds = self.model[self.discrepancy_name].generate(with_values=data) # Sort based on new distance measure sort_distance = np.atleast_2d(np.transpose(ds))[-1] sort_mask = np.argsort(sort_distance) # Update state self.state['samples'][self.discrepancy_name] = sort_distance for k in self.state['samples'].keys(): if k != self.discrepancy_name: self.state['samples'][k][:nums] = self.state['samples'][k][sort_mask] self._update_state_meta() def plot_state(self, **options): """Plot the current state of the inference algorithm. This feature is still experimental and only supports 1d or 2d cases. """ displays = [] if options.get('interactive'): from IPython import display displays.append( display.HTML('<span>Threshold: {}</span>'.format(self.state['threshold']))) visin.plot_sample( self.state['samples'], nodes=self.parameter_names, n=self.objective['n_samples'], displays=displays, **options) class SMC(Sampler): """Sequential Monte Carlo ABC sampler.""" def __init__(self, model, discrepancy_name=None, output_names=None, **kwargs): """Initialize the SMC-ABC sampler. Parameters ---------- model : ElfiModel or NodeReference discrepancy_name : str, NodeReference, optional Only needed if model is an ElfiModel output_names : list, optional Additional outputs from the model to be included in the inference result, e.g. corresponding summaries to the acquired samples kwargs: See InferenceMethod """ model, discrepancy_name = self._resolve_model(model, discrepancy_name) output_names = [discrepancy_name] + model.parameter_names + (output_names or []) super(SMC, self).__init__(model, output_names, **kwargs) self._prior = ModelPrior(self.model) self.discrepancy_name = discrepancy_name self.state['round'] = 0 self._populations = [] self._rejection = None self._round_random_state = None def set_objective(self, n_samples, thresholds): """Set the objective of the inference.""" self.objective.update( dict( n_samples=n_samples, n_batches=self.max_parallel_batches, round=len(thresholds) - 1, thresholds=thresholds)) self._init_new_round() def extract_result(self): """Extract the result from the current state. Returns ------- SmcSample """ # Extract information from the population pop = self._extract_population() self._populations.append(pop) return SmcSample( outputs=pop.outputs, populations=self._populations.copy(), weights=pop.weights, threshold=pop.threshold, **self._extract_result_kwargs()) def update(self, batch, batch_index): """Update the inference state with a new batch. Parameters ---------- batch : dict dict with `self.outputs` as keys and the corresponding outputs for the batch as values batch_index : int """ super(SMC, self).update(batch, batch_index) self._rejection.update(batch, batch_index) if self._rejection.finished: self.batches.cancel_pending() if self.state['round'] < self.objective['round']: self._populations.append(self._extract_population()) self.state['round'] += 1 self._init_new_round() self._update_objective() def prepare_new_batch(self, batch_index): """Prepare values for a new batch. Parameters ---------- batch_index : int next batch_index to be submitted Returns ------- batch : dict or None Keys should match to node names in the model. These values will override any default values or operations in those nodes. """ if self.state['round'] == 0: # Use the actual prior return # Sample from the proposal, condition on actual prior params = GMDistribution.rvs(*self._gm_params, size=self.batch_size, prior_logpdf=self._prior.logpdf, random_state=self._round_random_state) batch = arr2d_to_batch(params, self.parameter_names) return batch def _init_new_round(self): round = self.state['round'] reinit_msg = 'ABC-SMC Round {0} / {1}'.format( round + 1, self.objective['round'] + 1) self.progress_bar.reinit_progressbar( scaling=(self.state['n_batches']), reinit_msg=reinit_msg) dashes = '-' * 16 logger.info('%s Starting round %d %s' % (dashes, round, dashes)) # Get a subseed for this round for ensuring consistent results for the round seed = self.seed if round == 0 else get_sub_seed(self.seed, round) self._round_random_state = np.random.RandomState(seed) self._rejection = Rejection( self.model, discrepancy_name=self.discrepancy_name, output_names=self.output_names, batch_size=self.batch_size, seed=seed, max_parallel_batches=self.max_parallel_batches) self._rejection.set_objective( self.objective['n_samples'], threshold=self.current_population_threshold) def _extract_population(self): sample = self._rejection.extract_result() # Append the sample object sample.method_name = "Rejection within SMC-ABC" w, cov = self._compute_weights_and_cov(sample) sample.weights = w sample.meta['cov'] = cov return sample def _compute_weights_and_cov(self, pop): params = np.column_stack( tuple([pop.outputs[p] for p in self.parameter_names])) if self._populations: q_logpdf = GMDistribution.logpdf(params, *self._gm_params) p_logpdf = self._prior.logpdf(params) w = np.exp(p_logpdf - q_logpdf) else: w = np.ones(pop.n_samples) if np.count_nonzero(w) == 0: raise RuntimeError("All sample weights are zero. If you are using a prior " "with a bounded support, this may be caused by specifying " "a too small sample size.") # New covariance cov = 2 * np.diag(weighted_var(params, w)) if not np.all(np.isfinite(cov)): logger.warning("Could not estimate the sample covariance. This is often " "caused by majority of the sample weights becoming zero." "Falling back to using unit covariance.") cov = np.diag(np.ones(params.shape[1])) return w, cov def _update_objective(self): """Update the objective n_batches.""" n_batches = sum([pop.n_batches for pop in self._populations]) self.objective['n_batches'] = n_batches + \ self._rejection.objective['n_batches'] @property def _gm_params(self): sample = self._populations[-1] params = sample.samples_array return params, sample.cov, sample.weights @property def current_population_threshold(self): """Return the threshold for current population.""" return self.objective['thresholds'][self.state['round']] class AdaptiveDistanceSMC(SMC): """SMC-ABC sampler with adaptive threshold and distance function. Notes ----- Algorithm 5 in Prangle (2017) References ---------- <NAME> (2017). Adapting the ABC Distance Function. Bayesian Analysis 12(1):289-309, 2017. https://projecteuclid.org/euclid.ba/1460641065 """ def __init__(self, model, discrepancy_name=None, output_names=None, **kwargs): """Initialize the adaptive distance SMC-ABC sampler. Parameters ---------- model : ElfiModel or NodeReference discrepancy_name : str, NodeReference, optional Only needed if model is an ElfiModel output_names : list, optional Additional outputs from the model to be included in the inference result, e.g. corresponding summaries to the acquired samples kwargs: See InferenceMethod """ model, discrepancy_name = self._resolve_model(model, discrepancy_name) if not isinstance(model[discrepancy_name], AdaptiveDistance): raise TypeError('This method requires an adaptive distance node.') # Initialise adaptive distance node model[discrepancy_name].init_state() # Add summaries in additional outputs as these are needed to update the distance node sums = [sumstat.name for sumstat in model[discrepancy_name].parents] if output_names is None: output_names = sums else: for k in sums: if k not in output_names: output_names.append(k) super(AdaptiveDistanceSMC, self).__init__(model, discrepancy_name, output_names=output_names, **kwargs) def set_objective(self, n_samples, rounds, quantile=0.5): """Set objective for adaptive distance ABC-SMC inference. Parameters ---------- n_samples : int Number of samples to generate rounds : int, optional Number of populations to sample quantile : float, optional Selection quantile used to determine the adaptive threshold """ self.state['round'] = len(self._populations) rounds = rounds + self.state['round'] self.objective.update( dict( n_samples=n_samples, n_batches=self.max_parallel_batches, round=rounds-1 )) self.quantile = quantile self._init_new_round() def _init_new_round(self): round = self.state['round'] reinit_msg = 'ABC-SMC Round {0} / {1}'.format(round + 1, self.objective['round'] + 1) self.progress_bar.reinit_progressbar(scaling=(self.state['n_batches']), reinit_msg=reinit_msg) dashes = '-' * 16 logger.info('%s Starting round %d %s' % (dashes, round, dashes)) # Get a subseed for this round for ensuring consistent results for the round seed = self.seed if round == 0 else get_sub_seed(self.seed, round) self._round_random_state = np.random.RandomState(seed) self._rejection = Rejection( self.model, discrepancy_name=self.discrepancy_name, output_names=self.output_names, batch_size=self.batch_size, seed=seed, max_parallel_batches=self.max_parallel_batches) # Update adaptive threshold if round == 0: rejection_thd = None # do not use a threshold on the first round else: rejection_thd = self.current_population_threshold self._rejection.set_objective(ceil(self.objective['n_samples']/self.quantile), threshold=rejection_thd, quantile=1) self._update_objective() def _extract_population(self): # Extract population and metadata based on rejection sample rejection_sample = self._rejection.extract_result() outputs = dict() for k in self.output_names: outputs[k] = rejection_sample.outputs[k][:self.objective['n_samples']] meta = rejection_sample.meta meta['threshold'] = max(outputs[self.discrepancy_name]) meta['accept_rate'] = self.objective['n_samples']/meta['n_sim'] method_name = "Rejection within SMC-ABC" sample = Sample(method_name, outputs, self.parameter_names, **meta) # Append the sample object w, cov = self._compute_weights_and_cov(sample) sample.weights = w sample.meta['cov'] = cov return sample @property def current_population_threshold(self): """Return the threshold for current population.""" return [np.inf] + [pop.threshold for pop in self._populations] class BayesianOptimization(ParameterInference): """Bayesian Optimization of an unknown target function.""" def __init__(self, model, target_name=None, bounds=None, initial_evidence=None, update_interval=10, target_model=None, acquisition_method=None, acq_noise_var=0, exploration_rate=10, batch_size=1, batches_per_acquisition=None, async_acq=False, **kwargs): """Initialize Bayesian optimization. Parameters ---------- model : ElfiModel or NodeReference target_name : str or NodeReference Only needed if model is an ElfiModel bounds : dict, optional The region where to estimate the posterior for each parameter in model.parameters: dict('parameter_name':(lower, upper), ... )`. Not used if custom target_model is given. initial_evidence : int, dict, optional Number of initial evidence or a precomputed batch dict containing parameter and discrepancy values. Default value depends on the dimensionality. update_interval : int, optional How often to update the GP hyperparameters of the target_model target_model : GPyRegression, optional acquisition_method : Acquisition, optional Method of acquiring evidence points. Defaults to LCBSC. acq_noise_var : float or np.array, optional Variance(s) of the noise added in the default LCBSC acquisition method. If an array, should be 1d specifying the variance for each dimension. exploration_rate : float, optional Exploration rate of the acquisition method batch_size : int, optional Elfi batch size. Defaults to 1. batches_per_acquisition : int, optional How many batches will be requested from the acquisition function at one go. Defaults to max_parallel_batches. async_acq : bool, optional Allow acquisitions to be made asynchronously, i.e. do not wait for all the results from the previous acquisition before making the next. This can be more efficient with a large amount of workers (e.g. in cluster environments) but forgoes the guarantee for the exactly same result with the same initial conditions (e.g. the seed). Default False. **kwargs """ model, target_name = self._resolve_model(model, target_name) output_names = [target_name] + model.parameter_names super(BayesianOptimization, self).__init__( model, output_names, batch_size=batch_size, **kwargs) target_model = target_model or GPyRegression( self.model.parameter_names, bounds=bounds) self.target_name = target_name self.target_model = target_model n_precomputed = 0 n_initial, precomputed = self._resolve_initial_evidence( initial_evidence) if precomputed is not None: params = batch_to_arr2d(precomputed, self.parameter_names) n_precomputed = len(params) self.target_model.update(params, precomputed[target_name]) self.batches_per_acquisition = batches_per_acquisition or self.max_parallel_batches self.acquisition_method = acquisition_method or LCBSC(self.target_model, prior=ModelPrior( self.model), noise_var=acq_noise_var, exploration_rate=exploration_rate, seed=self.seed) self.n_initial_evidence = n_initial self.n_precomputed_evidence = n_precomputed self.update_interval = update_interval self.async_acq = async_acq self.state['n_evidence'] = self.n_precomputed_evidence self.state['last_GP_update'] = self.n_initial_evidence self.state['acquisition'] = [] def _resolve_initial_evidence(self, initial_evidence): # Some sensibility limit for starting GP regression precomputed = None n_required = max(10, 2**self.target_model.input_dim + 1) n_required = ceil_to_batch_size(n_required, self.batch_size) if initial_evidence is None: n_initial_evidence = n_required elif isinstance(initial_evidence, (int, np.int, float)): n_initial_evidence = int(initial_evidence) else: precomputed = initial_evidence n_initial_evidence = len(precomputed[self.target_name]) if n_initial_evidence < 0: raise ValueError('Number of initial evidence must be positive or zero ' '(was {})'.format(initial_evidence)) elif n_initial_evidence < n_required: logger.warning('We recommend having at least {} initialization points for ' 'the initialization (now {})'.format(n_required, n_initial_evidence)) if precomputed is None and (n_initial_evidence % self.batch_size != 0): logger.warning('Number of initial_evidence %d is not divisible by ' 'batch_size %d. Rounding it up...' % (n_initial_evidence, self.batch_size)) n_initial_evidence = ceil_to_batch_size( n_initial_evidence, self.batch_size) return n_initial_evidence, precomputed @property def n_evidence(self): """Return the number of acquired evidence points.""" return self.state.get('n_evidence', 0) @property def acq_batch_size(self): """Return the total number of acquisition per iteration.""" return self.batch_size * self.batches_per_acquisition def set_objective(self, n_evidence=None): """Set objective for inference. You can continue BO by giving a larger n_evidence. Parameters ---------- n_evidence : int Number of total evidence for the GP fitting. This includes any initial evidence. """ if n_evidence is None: n_evidence = self.objective.get('n_evidence', self.n_evidence) if n_evidence < self.n_evidence: logger.warning( 'Requesting less evidence than there already exists') self.objective['n_evidence'] = n_evidence self.objective['n_sim'] = n_evidence - self.n_precomputed_evidence def extract_result(self): """Extract the result from the current state. Returns ------- OptimizationResult """ x_min, _ = stochastic_optimization( self.target_model.predict_mean, self.target_model.bounds, seed=self.seed) batch_min = arr2d_to_batch(x_min, self.parameter_names) outputs = arr2d_to_batch(self.target_model.X, self.parameter_names) outputs[self.target_name] = self.target_model.Y return OptimizationResult( x_min=batch_min, outputs=outputs, **self._extract_result_kwargs()) def update(self, batch, batch_index): """Update the GP regression model of the target node with a new batch. Parameters ---------- batch : dict dict with `self.outputs` as keys and the corresponding outputs for the batch as values batch_index : int """ super(BayesianOptimization, self).update(batch, batch_index) self.state['n_evidence'] += self.batch_size params = batch_to_arr2d(batch, self.parameter_names) self._report_batch(batch_index, params, batch[self.target_name]) optimize = self._should_optimize() self.target_model.update(params, batch[self.target_name], optimize) if optimize: self.state['last_GP_update'] = self.target_model.n_evidence def prepare_new_batch(self, batch_index): """Prepare values for a new batch. Parameters ---------- batch_index : int next batch_index to be submitted Returns ------- batch : dict or None Keys should match to node names in the model. These values will override any default values or operations in those nodes. """ t = self._get_acquisition_index(batch_index) # Check if we still should take initial points from the prior if t < 0: return # Take the next batch from the acquisition_batch acquisition = self.state['acquisition'] if len(acquisition) == 0: acquisition = self.acquisition_method.acquire( self.acq_batch_size, t=t) batch = arr2d_to_batch( acquisition[:self.batch_size], self.parameter_names) self.state['acquisition'] = acquisition[self.batch_size:] return batch def _get_acquisition_index(self, batch_index): acq_batch_size = self.batch_size * self.batches_per_acquisition initial_offset = self.n_initial_evidence - self.n_precomputed_evidence starting_sim_index = self.batch_size * batch_index t = (starting_sim_index - initial_offset) // acq_batch_size return t # TODO: use state dict @property def _n_submitted_evidence(self): return self.batches.total * self.batch_size def _allow_submit(self, batch_index): if not super(BayesianOptimization, self)._allow_submit(batch_index): return False if self.async_acq: return True # Allow submitting freely as long we are still submitting initial evidence t = self._get_acquisition_index(batch_index) if t < 0: return True # Do not allow acquisition until previous acquisitions are ready (as well # as all initial acquisitions) acquisitions_left = len(self.state['acquisition']) if acquisitions_left == 0 and self.batches.has_pending: return False return True def _should_optimize(self): current = self.target_model.n_evidence + self.batch_size next_update = self.state['last_GP_update'] + self.update_interval return current >= self.n_initial_evidence and current >= next_update def _report_batch(self, batch_index, params, distances): str = "Received batch {}:\n".format(batch_index) fill = 6 * ' ' for i in range(self.batch_size): str += "{}{} at {}\n".format(fill, distances[i].item(), params[i]) logger.debug(str) def plot_state(self, **options): """Plot the GP surface. This feature is still experimental and currently supports only 2D cases. """ f = plt.gcf() if len(f.axes) < 2: f, _ = plt.subplots(1, 2, figsize=( 13, 6), sharex='row', sharey='row') gp = self.target_model # Draw the GP surface visin.draw_contour( gp.predict_mean, gp.bounds, self.parameter_names, title='GP target surface', points=gp.X, axes=f.axes[0], **options) # Draw the latest acquisitions if options.get('interactive'): point = gp.X[-1, :] if len(gp.X) > 1: f.axes[1].scatter(*point, color='red') displays = [gp._gp] if options.get('interactive'): from IPython import display displays.insert( 0, display.HTML('<span><b>Iteration {}:</b> Acquired {} at {}</span>'.format( len(gp.Y), gp.Y[-1][0], point))) # Update visin._update_interactive(displays, options) def acq(x): return self.acquisition_method.evaluate(x, len(gp.X)) # Draw the acquisition surface visin.draw_contour( acq, gp.bounds, self.parameter_names, title='Acquisition surface', points=None, axes=f.axes[1], **options) if options.get('close'): plt.close() def plot_discrepancy(self, axes=None, **kwargs): """Plot acquired parameters vs. resulting discrepancy. Parameters ---------- axes : plt.Axes or arraylike of plt.Axes Return ------ axes : np.array of plt.Axes """ return vis.plot_discrepancy(self.target_model, self.parameter_names, axes=axes, **kwargs) def plot_gp(self, axes=None, resol=50, const=None, bounds=None, true_params=None, **kwargs): """Plot pairwise relationships as a matrix with parameters vs. discrepancy. Parameters ---------- axes : matplotlib.axes.Axes, optional resol : int, optional Resolution of the plotted grid. const : np.array, optional Values for parameters in plots where held constant. Defaults to minimum evidence. bounds: list of tuples, optional List of tuples for axis boundaries. true_params : dict, optional Dictionary containing parameter names with corresponding true parameter values. Returns ------- axes : np.array of plt.Axes """ return vis.plot_gp(self.target_model, self.parameter_names, axes, resol, const, bounds, true_params, **kwargs) class BOLFI(BayesianOptimization): """Bayesian Optimization for Likelihood-Free Inference (BOLFI). Approximates the discrepancy function by a stochastic regression model. Discrepancy model is fit by sampling the discrepancy function at points decided by the acquisition function. The method implements the framework introduced in Gutmann & Corander, 2016. References ---------- <NAME>, <NAME> (2016). Bayesian Optimization for Likelihood-Free Inference of Simulator-Based Statistical Models. JMLR 17(125):1−47, 2016. http://jmlr.org/papers/v17/15-017.html """ def fit(self, n_evidence, threshold=None, bar=True): """Fit the surrogate model. Generates a regression model for the discrepancy given the parameters. Currently only Gaussian processes are supported as surrogate models. Parameters ---------- n_evidence : int, required Number of evidence for fitting threshold : float, optional Discrepancy threshold for creating the posterior (log with log discrepancy). bar : bool, optional Flag to remove (False) the progress bar from output. """ logger.info("BOLFI: Fitting the surrogate model...") if n_evidence is None: raise ValueError( 'You must specify the number of evidence (n_evidence) for the fitting') self.infer(n_evidence, bar=bar) return self.extract_posterior(threshold) def extract_posterior(self, threshold=None): """Return an object representing the approximate posterior. The approximation is based on surrogate model regression. Parameters ---------- threshold: float, optional Discrepancy threshold for creating the posterior (log with log discrepancy). Returns ------- posterior : elfi.methods.posteriors.BolfiPosterior """ if self.state['n_evidence'] == 0: raise ValueError( 'Model is not fitted yet, please see the `fit` method.') return BolfiPosterior(self.target_model, threshold=threshold, prior=ModelPrior(self.model)) def sample(self, n_samples, warmup=None, n_chains=4, threshold=None, initials=None, algorithm='nuts', sigma_proposals=None, n_evidence=None, **kwargs): r"""Sample the posterior distribution of BOLFI. Here the likelihood is defined through the cumulative density function of the standard normal distribution: L(\theta) \propto F((h-\mu(\theta)) / \sigma(\theta)) where h is the threshold, and \mu(\theta) and \sigma(\theta) are the posterior mean and (noisy) standard deviation of the associated Gaussian process. The sampling is performed with an MCMC sampler (the No-U-Turn Sampler, NUTS). Parameters ---------- n_samples : int Number of requested samples from the posterior for each chain. This includes warmup, and note that the effective sample size is usually considerably smaller. warmpup : int, optional Length of warmup sequence in MCMC sampling. Defaults to n_samples//2. n_chains : int, optional Number of independent chains. threshold : float, optional The threshold (bandwidth) for posterior (give as log if log discrepancy). initials : np.array of shape (n_chains, n_params), optional Initial values for the sampled parameters for each chain. Defaults to best evidence points. algorithm : string, optional Sampling algorithm to use. Currently 'nuts'(default) and 'metropolis' are supported. sigma_proposals : np.array Standard deviations for Gaussian proposals of each parameter for Metropolis Markov Chain sampler. n_evidence : int If the regression model is not fitted yet, specify the amount of evidence Returns ------- BolfiSample """ if self.state['n_batches'] == 0: self.fit(n_evidence) # TODO: add more MCMC algorithms if algorithm not in ['nuts', 'metropolis']: raise ValueError("Unknown posterior sampler.") posterior = self.extract_posterior(threshold) warmup = warmup or n_samples // 2 # Unless given, select the evidence points with smallest discrepancy if initials is not None: if np.asarray(initials).shape != (n_chains, self.target_model.input_dim): raise ValueError( "The shape of initials must be (n_chains, n_params).") else: inds = np.argsort(self.target_model.Y[:, 0]) initials = np.asarray(self.target_model.X[inds]) self.target_model.is_sampling = True # enables caching for default RBF kernel tasks_ids = [] ii_initial = 0 if algorithm == 'metropolis': if sigma_proposals is None: raise ValueError("Gaussian proposal standard deviations " "have to be provided for Metropolis-sampling.") elif sigma_proposals.shape[0] != self.target_model.input_dim: raise ValueError("The length of Gaussian proposal standard " "deviations must be n_params.") # sampling is embarrassingly parallel, so depending on self.client this may parallelize for ii in range(n_chains): seed = get_sub_seed(self.seed, ii) # discard bad initialization points while np.isinf(posterior.logpdf(initials[ii_initial])): ii_initial += 1 if ii_initial == len(inds): raise ValueError( "BOLFI.sample: Cannot find enough acceptable initialization points!") if algorithm == 'nuts': tasks_ids.append( self.client.apply( mcmc.nuts, n_samples, initials[ii_initial], posterior.logpdf, posterior.gradient_logpdf, n_adapt=warmup, seed=seed, **kwargs)) elif algorithm == 'metropolis': tasks_ids.append( self.client.apply( mcmc.metropolis, n_samples, initials[ii_initial], posterior.logpdf, sigma_proposals, warmup, seed=seed, **kwargs)) ii_initial += 1 # get results from completed tasks or run sampling (client-specific) chains = [] for id in tasks_ids: chains.append(self.client.get_result(id)) chains = np.asarray(chains) print( "{} chains of {} iterations acquired. Effective sample size and Rhat for each " "parameter:".format(n_chains, n_samples)) for ii, node in enumerate(self.parameter_names): print(node, mcmc.eff_sample_size(chains[:, :, ii]), mcmc.gelman_rubin(chains[:, :, ii])) self.target_model.is_sampling = False return BolfiSample( method_name='BOLFI', chains=chains, parameter_names=self.parameter_names, warmup=warmup, threshold=float(posterior.threshold), n_sim=self.state['n_sim'], seed=self.seed) class BoDetereministic: """Base class for applying Bayesian Optimisation to a deterministic objective function. This class (a) optimizes the determinstic function and (b) fits a surrogate model in the area around the optimal point. This class follows the structure of BayesianOptimization replacing the stochastic elfi Model with a deterministic function. """ def __init__(self, objective, prior, parameter_names, n_evidence, target_name=None, bounds=None, initial_evidence=None, update_interval=10, target_model=None, acquisition_method=None, acq_noise_var=0, exploration_rate=10, batch_size=1, async_acq=False, seed=None, **kwargs): """Initialize Bayesian optimization. Parameters ---------- objective : Callable(np.ndarray) -> float The objective function prior : ModelPrior The prior distribution parameter_names : List[str] names of the parameters of interest n_evidence : int number of evidence points needed for the optimisation process to terminate target_name : str, optional the name of the output node of the deterministic function bounds : dict, optional The region where to estimate the posterior for each parameter in model.parameters: dict('parameter_name':(lower, upper), ... )`. If not passed, the range [0,1] is passed initial_evidence : int, dict, optional Number of initial evidence needed or a precomputed batch dict containing parameter and discrepancy values. Default value depends on the dimensionality. update_interval : int, optional How often to update the GP hyperparameters of the target_model target_model : GPyRegression, optional acquisition_method : Acquisition, optional Method of acquiring evidence points. Defaults to LCBSC. acq_noise_var : float or np.array, optional Variance(s) of the noise added in the default LCBSC acquisition method. If an array, should be 1d specifying the variance for each dimension. exploration_rate : float, optional Exploration rate of the acquisition method batch_size : int, optional Elfi batch size. Defaults to 1. batches_per_acquisition : int, optional How many batches will be requested from the acquisition function at one go. Defaults to max_parallel_batches. async_acq : bool, optional Allow acquisitions to be made asynchronously, i.e. do not wait for all the results from the previous acquisition before making the next. This can be more efficient with a large amount of workers (e.g. in cluster environments) but forgoes the guarantee for the exactly same result with the same initial conditions (e.g. the seed). Default False. seed : int, optional seed for making the process reproducible **kwargs """ self.det_func = objective self.prior = prior self.bounds = bounds self.batch_size = batch_size self.parameter_names = parameter_names self.seed = seed self.target_name = target_name self.target_model = target_model n_precomputed = 0 n_initial, precomputed = self._resolve_initial_evidence( initial_evidence) if precomputed is not None: params = batch_to_arr2d(precomputed, self.parameter_names) n_precomputed = len(params) self.target_model.update(params, precomputed[target_name]) self.batches_per_acquisition = 1 self.acquisition_method = acquisition_method or LCBSC(self.target_model, prior=self.prior, noise_var=acq_noise_var, exploration_rate=exploration_rate, seed=self.seed) self.n_initial_evidence = n_initial self.n_precomputed_evidence = n_precomputed self.update_interval = update_interval self.async_acq = async_acq self.state = {'n_evidence': self.n_precomputed_evidence, 'last_GP_update': self.n_initial_evidence, 'acquisition': [], 'n_sim': 0, 'n_batches': 0} self.set_objective(n_evidence) def _resolve_initial_evidence(self, initial_evidence): # Some sensibility limit for starting GP regression precomputed = None n_required = max(10, 2 ** self.target_model.input_dim + 1) n_required = ceil_to_batch_size(n_required, self.batch_size) if initial_evidence is None: n_initial_evidence = n_required elif isinstance(initial_evidence, (int, np.int, float)): n_initial_evidence = int(initial_evidence) else: precomputed = initial_evidence n_initial_evidence = len(precomputed[self.target_name]) if n_initial_evidence < 0: raise ValueError('Number of initial evidence must be positive or zero ' '(was {})'.format(initial_evidence)) elif n_initial_evidence < n_required: logger.warning('We recommend having at least {} initialization points for ' 'the initialization (now {})'.format(n_required, n_initial_evidence)) if precomputed is None and (n_initial_evidence % self.batch_size != 0): logger.warning('Number of initial_evidence %d is not divisible by ' 'batch_size %d. Rounding it up...' % (n_initial_evidence, self.batch_size)) n_initial_evidence = ceil_to_batch_size( n_initial_evidence, self.batch_size) return n_initial_evidence, precomputed @property def n_evidence(self): """Return the number of acquired evidence points.""" return self.state.get('n_evidence', 0) @property def acq_batch_size(self): """Return the total number of acquisition per iteration.""" return self.batch_size * self.batches_per_acquisition def set_objective(self, n_evidence=None): """Set objective for inference. You can continue BO by giving a larger n_evidence. Parameters ---------- n_evidence : int Number of total evidence for the GP fitting. This includes any initial evidence. """ if n_evidence is None: n_evidence = self.objective.get('n_evidence', self.n_evidence) if n_evidence < self.n_evidence: logger.warning( 'Requesting less evidence than there already exists') self.objective = {'n_evidence': n_evidence, 'n_sim': n_evidence - self.n_precomputed_evidence} def _extract_result_kwargs(self): """Extract common arguments for the ParameterInferenceResult object.""" return { 'method_name': self.__class__.__name__, 'parameter_names': self.parameter_names, 'seed': self.seed, 'n_sim': self.state['n_sim'], 'n_batches': self.state['n_batches'] } def extract_result(self): """Extract the result from the current state. Returns ------- OptimizationResult """ x_min, _ = stochastic_optimization( self.target_model.predict_mean, self.target_model.bounds, seed=self.seed) batch_min = arr2d_to_batch(x_min, self.parameter_names) outputs = arr2d_to_batch(self.target_model.X, self.parameter_names) outputs[self.target_name] = self.target_model.Y return OptimizationResult( x_min=batch_min, outputs=outputs, **self._extract_result_kwargs()) def update(self, batch, batch_index): """Update the GP regression model of the target node with a new batch. Parameters ---------- batch : dict dict with `self.outputs` as keys and the corresponding outputs for the batch as values batch_index : int """ # super(BayesianOptimization, self).update(batch, batch_index) self.state['n_evidence'] += self.batch_size params = batch_to_arr2d(batch, self.parameter_names) self._report_batch(batch_index, params, batch[self.target_name]) optimize = self._should_optimize() self.target_model.update(params, batch[self.target_name], optimize) if optimize: self.state['last_GP_update'] = self.target_model.n_evidence def prepare_new_batch(self, batch_index): """Prepare values for a new batch. Parameters ---------- batch_index : int next batch_index to be submitted Returns ------- batch : dict or None Keys should match to node names in the model. These values will override any default values or operations in those nodes. """ t = self._get_acquisition_index(batch_index) # Check if we still should take initial points from the prior if t < 0: return None, None # Take the next batch from the acquisition_batch acquisition = self.state['acquisition'] if len(acquisition) == 0: acquisition = self.acquisition_method.acquire( self.acq_batch_size, t=t) batch = arr2d_to_batch( acquisition[:self.batch_size], self.parameter_names) self.state['acquisition'] = acquisition[self.batch_size:] return acquisition, batch def _get_acquisition_index(self, batch_index): acq_batch_size = self.batch_size * self.batches_per_acquisition initial_offset = self.n_initial_evidence - self.n_precomputed_evidence starting_sim_index = self.batch_size * batch_index t = (starting_sim_index - initial_offset) // acq_batch_size return t def fit(self): for ii in range(self.objective["n_sim"]): inp, next_batch = self.prepare_new_batch(ii) if inp is None: inp = self.prior.rvs(size=1) if inp.ndim == 1: inp = np.expand_dims(inp, -1) next_batch = arr2d_to_batch(inp, self.parameter_names) y = np.array([self.det_func(np.squeeze(inp, 0))]) next_batch[self.target_name] = y self.update(next_batch, ii) self.state['n_batches'] += 1 self.state['n_sim'] += 1 self.result = self.extract_result() def _should_optimize(self): current = self.target_model.n_evidence + self.batch_size next_update = self.state['last_GP_update'] + self.update_interval return current >= self.n_initial_evidence and current >= next_update def _report_batch(self, batch_index, params, distances): str = "Received batch {}:\n".format(batch_index) fill = 6 * ' ' for i in range(self.batch_size): str += "{}{} at {}\n".format(fill, distances[i].item(), params[i]) logger.debug(str) def plot_state(self, **options): """Plot the GP surface. This feature is still experimental and currently supports only 2D cases. """ f = plt.gcf() if len(f.axes) < 2: f, _ = plt.subplots(1, 2, figsize=( 13, 6), sharex='row', sharey='row') gp = self.target_model # Draw the GP surface visin.draw_contour( gp.predict_mean, gp.bounds, self.parameter_names, title='GP target surface', points=gp.X, axes=f.axes[0], **options) # Draw the latest acquisitions if options.get('interactive'): point = gp.X[-1, :] if len(gp.X) > 1: f.axes[1].scatter(*point, color='red') displays = [gp._gp] if options.get('interactive'): from IPython import display displays.insert( 0, display.HTML('<span><b>Iteration {}:</b> Acquired {} at {}</span>'.format( len(gp.Y), gp.Y[-1][0], point))) # Update visin._update_interactive(displays, options) def acq(x): return self.acquisition_method.evaluate(x, len(gp.X)) # Draw the acquisition surface visin.draw_contour( acq, gp.bounds, self.parameter_names, title='Acquisition surface', points=None, axes=f.axes[1], **options) if options.get('close'): plt.close() def plot_discrepancy(self, axes=None, **kwargs): """Plot acquired parameters vs. resulting discrepancy. Parameters ---------- axes : plt.Axes or arraylike of plt.Axes Return ------ axes : np.array of plt.Axes """ return vis.plot_discrepancy(self.target_model, self.parameter_names, axes=axes, **kwargs) def plot_gp(self, axes=None, resol=50, const=None, bounds=None, true_params=None, **kwargs): """Plot pairwise relationships as a matrix with parameters vs. discrepancy. Parameters ---------- axes : matplotlib.axes.Axes, optional resol : int, optional Resolution of the plotted grid. const : np.array, optional Values for parameters in plots where held constant. Defaults to minimum evidence. bounds: list of tuples, optional List of tuples for axis boundaries. true_params : dict, optional Dictionary containing parameter names with corresponding true parameter values. Returns ------- axes : np.array of plt.Axes """ return vis.plot_gp(self.target_model, self.parameter_names, axes, resol, const, bounds, true_params, **kwargs) class ROMC(ParameterInference): """Robust Optimisation Monte Carlo inference method. <NAME>., & <NAME>. (2019). Robust Optimisation Monte Carlo. http://arxiv.org/abs/1904.00670 """ def __init__(self, model, bounds=None, discrepancy_name=None, output_names=None, custom_optim_class=None, parallelize=False, **kwargs): """Class constructor. Parameters ---------- model: Model or NodeReference the elfi model or the output node of the graph bounds: List[(start,stop), ...] bounds of the n-dim bounding box area containing the mass of the posterior discrepancy_name: string, optional the name of the output node (obligatory, only if Model is passed as model) output_names: List[string] which node values to store during inference kwargs: Dict other named parameters """ # define model, output names asked by the romc method model, discrepancy_name = self._resolve_model(model, discrepancy_name) output_names = [discrepancy_name] + \ model.parameter_names + (output_names or []) # setter self.discrepancy_name = discrepancy_name self.model = model self.model_prior = ModelPrior(model) self.dim = self.model_prior.dim self.bounds = bounds self.left_lim = np.array([bound[0] for bound in bounds], dtype=np.float) if bounds is not None else None self.right_lim = np.array([bound[1] for bound in bounds], dtype=np.float) if bounds is not None else None # holds the state of the inference process self.inference_state = {"_has_gen_nuisance": False, "_has_defined_problems": False, "_has_solved_problems": False, "_has_fitted_surrogate_model": False, "_has_filtered_solutions": False, "_has_fitted_local_models": False, "_has_estimated_regions": False, "_has_defined_posterior": False, "_has_drawn_samples": False, "attempted": None, "solved": None, "accepted": None, "computed_BB": None} # inputs passed during inference are passed here self.inference_args = {"parallelize": parallelize} # user-defined OptimisationClass self.custom_optim_class = custom_optim_class # objects stored during inference; they are all lists of the same dimension (n1) self.nuisance = None # List of integers self.optim_problems = None # List of OptimisationProblem objects # output objects self.posterior = None # RomcPosterior object # np.ndarray: (#accepted,n2,D), Samples drawn from RomcPosterior self.samples = None # np.ndarray: (#accepted,n2): weights of the samples self.weights = None # np.ndarray: (#accepted,n2): distances of the samples self.distances = None self.result = None # RomcSample object self.progress_bar = ProgressBar() super(ROMC, self).__init__(model, output_names, **kwargs) def _sample_nuisance(self, n1, seed=None): """Draw n1 nuisance variables (i.e. seeds). Parameters ---------- n1: int nof nuisance samples seed: int (optional) the seed used for sampling the nuisance variables """ assert isinstance(n1, int) # main part # It can sample at most 4x1E09 unique numbers # TODO fix to work with subseeds to remove the limit of 4x1E09 numbers up_lim = 2**32 - 1 nuisance = ss.randint(low=1, high=up_lim).rvs( size=n1, random_state=seed) # update state self.inference_state["_has_gen_nuisance"] = True self.nuisance = nuisance self.inference_args["N1"] = n1 self.inference_args["initial_seed"] = seed def _define_objectives(self): """Define n1 deterministic optimisation problems, by freezing the seed of the generator.""" # getters nuisance = self.nuisance dim = self.dim param_names = self.parameter_names bounds = self.bounds model_prior = self.model_prior n1 = self.inference_args["N1"] target_name = self.discrepancy_name # main optim_problems = [] for ind, nuisance in enumerate(nuisance): objective = self._freeze_seed(nuisance) if self.custom_optim_class is None: optim_prob = OptimisationProblem(ind, nuisance, param_names, target_name, objective, dim, model_prior, n1, bounds) else: optim_prob = self.custom_optim_class(ind=ind, nuisance=nuisance, parameter_names=param_names, target_name=target_name, objective=objective, dim=dim, prior=model_prior, n1=n1, bounds=bounds) optim_problems.append(optim_prob) # update state self.optim_problems = optim_problems self.inference_state["_has_defined_problems"] = True def _det_generator(self, theta, seed): model = self.model dim = self.dim output_node = self.discrepancy_name assert theta.ndim == 1 assert theta.shape[0] == dim # Map flattened array of parameters to parameter names with correct shape param_dict = flat_array_to_dict(model.parameter_names, theta) dict_outputs = model.generate( batch_size=1, outputs=[output_node], with_values=param_dict, seed=int(seed)) return float(dict_outputs[output_node]) ** 2 def _freeze_seed(self, seed): """Freeze the model.generate with a specific seed. Parameters __________ seed: int the seed passed to model.generate Returns ------- Callable: the deterministic generator """ return partial(self._det_generator, seed=seed) def _worker_solve_gradients(self, args): optim_prob, kwargs = args is_solved = optim_prob.solve_gradients(**kwargs) return optim_prob, is_solved def _worker_build_region(self, args): optim_prob, accepted, kwargs = args if accepted: is_built = optim_prob.build_region(**kwargs) else: is_built = False return optim_prob, is_built def _worker_fit_model(self, args): optim_prob, accepted, kwargs = args if accepted: optim_prob.fit_local_surrogate(**kwargs) return optim_prob def _solve_gradients(self, **kwargs): """Attempt to solve all defined optimization problems with a gradient-based optimiser. Parameters ---------- kwargs: Dict all the keyword-arguments that will be passed to the optimiser None is obligatory, Optionals in the current implementation: * seed: for making the process reproducible * all valid arguments for scipy.optimize.minimize (e.g. method, jac) """ assert self.inference_state["_has_defined_problems"] parallelize = self.inference_args["parallelize"] assert isinstance(parallelize, bool) # getters n1 = self.inference_args["N1"] optim_probs = self.optim_problems # main part solved = [False for _ in range(n1)] attempted = [False for _ in range(n1)] tic = timeit.default_timer() if parallelize is False: for i in range(n1): self.progress_bar.update_progressbar(i, n1) attempted[i] = True is_solved = optim_probs[i].solve_gradients(**kwargs) solved[i] = is_solved else: # parallel part pool = Pool() args = ((optim_probs[i], kwargs) for i in range(n1)) new_list = pool.map(self._worker_solve_gradients, args) pool.close() pool.join() # return objects solved = [new_list[i][1] for i in range(n1)] self.optim_problems = [new_list[i][0] for i in range(n1)] toc = timeit.default_timer() logger.info("Time: %.3f sec" % (toc - tic)) # update state self.inference_state["solved"] = solved self.inference_state["attempted"] = attempted self.inference_state["_has_solved_problems"] = True def _solve_bo(self, **kwargs): """Attempt to solve all defined optimization problems with Bayesian Optimisation. Parameters ---------- kwargs: Dict * all the keyword-arguments that will be passed to the optimiser. None is obligatory. Optional, in the current implementation:, * "n_evidence": number of points for the process to terminate (default is 20) * "acq_noise_var": added noise at every query point (default is 0.1) """ assert self.inference_state["_has_defined_problems"] # getters n1 = self.inference_args["N1"] optim_problems = self.optim_problems # main part attempted = [] solved = [] tic = timeit.default_timer() for i in range(n1): self.progress_bar.update_progressbar(i, n1) attempted.append(True) is_solved = optim_problems[i].solve_bo(**kwargs) solved.append(is_solved) toc = timeit.default_timer() logger.info("Time: %.3f sec" % (toc - tic)) # update state self.inference_state["attempted"] = attempted self.inference_state["solved"] = solved self.inference_state["_has_solved_problems"] = True self.inference_state["_has_fitted_surrogate_model"] = True def compute_eps(self, quantile): """Return the quantile distance, out of all optimal distance. Parameters ---------- quantile: value in [0,1] Returns ------- float """ assert self.inference_state["_has_solved_problems"] assert isinstance(quantile, float) assert 0 <= quantile <= 1 opt_probs = self.optim_problems dist = [] for i in range(len(opt_probs)): if opt_probs[i].state["solved"]: dist.append(opt_probs[i].result.f_min) eps = np.quantile(dist, quantile) return eps def _filter_solutions(self, eps_filter): """Filter out the solutions over eps threshold. Parameters ---------- eps_filter: float the threshold for filtering out solutions """ # checks assert self.inference_state["_has_solved_problems"] # getters n1 = self.inference_args["N1"] solved = self.inference_state["solved"] optim_problems = self.optim_problems accepted = [] for i in range(n1): if solved[i] and (optim_problems[i].result.f_min < eps_filter): accepted.append(True) else: accepted.append(False) # update status self.inference_args["eps_filter"] = eps_filter self.inference_state["accepted"] = accepted self.inference_state["_has_filtered_solutions"] = True def _build_boxes(self, **kwargs): """Estimate a bounding box for all accepted solutions. Parameters ---------- kwargs: all the keyword-arguments that will be passed to the RegionConstructor. None is obligatory. Optionals, * eps_region, if not passed the eps for used in filtering will be used * use_surrogate, if not passed it will be set based on the optimisation method (gradients or bo) * step, the step size along the search direction, default 0.05 * lim, max translation along the search direction, default 100 """ # getters optim_problems = self.optim_problems accepted = self.inference_state["accepted"] n1 = self.inference_args["N1"] parallelize = self.inference_args["parallelize"] assert isinstance(parallelize, bool) # main computed_bb = [False for _ in range(n1)] if parallelize is False: for i in range(n1): self.progress_bar.update_progressbar(i, n1) if accepted[i]: is_built = optim_problems[i].build_region(**kwargs) computed_bb.append(is_built) else: computed_bb.append(False) else: # parallel part pool = Pool() args = ((optim_problems[i], accepted[i], kwargs) for i in range(n1)) new_list = pool.map(self._worker_build_region, args) pool.close() pool.join() # return objects computed_bb = [new_list[i][1] for i in range(n1)] self.optim_problems = [new_list[i][0] for i in range(n1)] # update status self.inference_state["computed_BB"] = computed_bb self.inference_state["_has_estimated_regions"] = True def _fit_models(self, **kwargs): # getters optim_problems = self.optim_problems accepted = self.inference_state["accepted"] n1 = self.inference_args["N1"] parallelize = self.inference_args["parallelize"] assert isinstance(parallelize, bool) # main if parallelize is False: for i in range(n1): self.progress_bar.update_progressbar(i, n1) if accepted[i]: optim_problems[i].fit_local_surrogate(**kwargs) else: # parallel part pool = Pool() args = ((optim_problems[i], accepted[i], kwargs) for i in range(n1)) new_list = pool.map(self._worker_fit_model, args) pool.close() pool.join() # return objects self.optim_problems = [new_list[i] for i in range(n1)] # update status self.inference_state["_has_fitted_local_models"] = True def _define_posterior(self, eps_cutoff): """Collect all computed regions and define the RomcPosterior. Returns ------- RomcPosterior """ problems = self.optim_problems prior = self.model_prior eps_filter = self.inference_args["eps_filter"] eps_region = self.inference_args["eps_region"] left_lim = self.left_lim right_lim = self.right_lim use_surrogate = self.inference_state["_has_fitted_surrogate_model"] use_local = self.inference_state["_has_fitted_local_models"] parallelize = self.inference_args["parallelize"] # collect all constructed regions regions = [] funcs = [] funcs_unique = [] nuisance = [] for i, prob in enumerate(problems): if prob.state["region"]: for jj in range(len(prob.regions)): nuisance.append(prob.nuisance) regions.append(prob.regions[jj]) if not use_local: if use_surrogate: assert prob.surrogate is not None funcs.append(prob.surrogate) else: funcs.append(prob.objective) else: assert prob.local_surrogate is not None funcs.append(prob.local_surrogate[jj]) if not use_local: if use_surrogate: funcs_unique.append(prob.surrogate) else: funcs_unique.append(prob.objective) else: funcs_unique.append(prob.local_surrogate[0]) self.posterior = RomcPosterior(regions, funcs, nuisance, funcs_unique, prior, left_lim, right_lim, eps_filter, eps_region, eps_cutoff, parallelize) self.inference_state["_has_defined_posterior"] = True # Training routines def fit_posterior(self, n1, eps_filter, use_bo=False, quantile=None, optimizer_args=None, region_args=None, fit_models=False, fit_models_args=None, seed=None, eps_region=None, eps_cutoff=None): """Execute all training steps. Parameters ---------- n1: integer nof deterministic optimisation problems use_bo: Boolean whether to use Bayesian Optimisation eps_filter: Union[float, str] threshold for filtering solution or "auto" if defined by through quantile quantile: Union[None, float], optional quantile of optimal distances to set as eps if eps="auto" optimizer_args: Union[None, Dict] keyword-arguments that will be passed to the optimiser region_args: Union[None, Dict] keyword-arguments that will be passed to the regionConstructor seed: Union[None, int] seed definition for making the training process reproducible """ assert isinstance(n1, int) assert isinstance(use_bo, bool) assert eps_filter == "auto" or isinstance(eps_filter, (int, float)) if eps_filter == "auto": assert isinstance(quantile, (int, float)) quantile = float(quantile) # (i) define and solve problems self.solve_problems(n1=n1, use_bo=use_bo, optimizer_args=optimizer_args, seed=seed) # (ii) compute eps if isinstance(eps_filter, (int, float)): eps_filter = float(eps_filter) elif eps_filter == "auto": eps_filter = self.compute_eps(quantile) # (iii) estimate regions self.estimate_regions( eps_filter=eps_filter, use_surrogate=use_bo, region_args=region_args, fit_models=fit_models, fit_models_args=fit_models_args, eps_region=eps_region, eps_cutoff=eps_cutoff) # print summary of fitting logger.info("NOF optimisation problems : %d " % np.sum(self.inference_state["attempted"])) logger.info("NOF solutions obtained : %d " % np.sum(self.inference_state["solved"])) logger.info("NOF accepted solutions : %d " % np.sum(self.inference_state["accepted"])) def solve_problems(self, n1, use_bo=False, optimizer_args=None, seed=None): """Define and solve n1 optimisation problems. Parameters ---------- n1: integer number of deterministic optimisation problems to solve use_bo: Boolean, default: False whether to use Bayesian Optimisation. If False, gradients are used. optimizer_args: Union[None, Dict], default None keyword-arguments that will be passed to the optimiser. The argument "seed" is automatically appended to the dict. In the current implementation, all arguments are optional. seed: Union[None, int] """ assert isinstance(n1, int) assert isinstance(use_bo, bool) if optimizer_args is None: optimizer_args = {} if "seed" not in optimizer_args: optimizer_args["seed"] = seed self._sample_nuisance(n1=n1, seed=seed) self._define_objectives() if not use_bo: logger.info("### Solving problems using a gradient-based method ###") tic = timeit.default_timer() self._solve_gradients(**optimizer_args) toc = timeit.default_timer() logger.info("Time: %.3f sec" % (toc - tic)) elif use_bo: logger.info("### Solving problems using Bayesian optimisation ###") tic = timeit.default_timer() self._solve_bo(**optimizer_args) toc = timeit.default_timer() logger.info("Time: %.3f sec" % (toc - tic)) def estimate_regions(self, eps_filter, use_surrogate=None, region_args=None, fit_models=False, fit_models_args=None, eps_region=None, eps_cutoff=None): """Filter solutions and build the N-Dimensional bounding box around the optimal point. Parameters ---------- eps_filter: float threshold for filtering the solutions use_surrogate: Union[None, bool] whether to use the surrogate model for bulding the bounding box. if None, it will be set based on which optimisation scheme has been used. region_args: Union[None, Dict] keyword-arguments that will be passed to the regionConstructor. The arguments "eps_region" and "use_surrogate" are automatically appended, if not defined explicitly. fit_models: bool whether to fit a helping model around the optimal point fit_models_args: Union[None, Dict] arguments passed for fitting the helping models eps_region: Union[None, float] threshold for the bounding box limits. If None, it will be equal to eps_filter. eps_cutoff: Union[None, float] threshold for the indicator function. If None, it will be equal to eps_filter. """ assert self.inference_state["_has_solved_problems"], "You have firstly to " \ "solve the optimization problems." if region_args is None: region_args = {} if fit_models_args is None: fit_models_args = {} if eps_cutoff is None: eps_cutoff = eps_filter if eps_region is None: eps_region = eps_filter if use_surrogate is None: use_surrogate = True if self.inference_state["_has_fitted_surrogate_model"] else False if "use_surrogate" not in region_args: region_args["use_surrogate"] = use_surrogate if "eps_region" not in region_args: region_args["eps_region"] = eps_region self.inference_args["eps_region"] = eps_region self.inference_args["eps_cutoff"] = eps_cutoff self._filter_solutions(eps_filter) nof_solved = int(np.sum(self.inference_state["solved"])) nof_accepted = int(np.sum(self.inference_state["accepted"])) logger.info("Total solutions: %d, Accepted solutions after filtering: %d" % (nof_solved, nof_accepted)) logger.info("### Estimating regions ###\n") tic = timeit.default_timer() self._build_boxes(**region_args) toc = timeit.default_timer() logger.info("Time: %.3f sec \n" % (toc - tic)) if fit_models: logger.info("### Fitting local models ###\n") tic = timeit.default_timer() self._fit_models(**fit_models_args) toc = timeit.default_timer() logger.info("Time: %.3f sec \n" % (toc - tic)) self._define_posterior(eps_cutoff=eps_cutoff) # Inference Routines def sample(self, n2, seed=None): """Get samples from the posterior. Parameters ---------- n2: int number of samples seed: int, seed of the sampling procedure """ assert self.inference_state["_has_defined_posterior"], "You must train first" # set the general seed # np.random.seed(seed) # draw samples logger.info("### Getting Samples from the posterior ###\n") tic = timeit.default_timer() self.samples, self.weights, self.distances = self.posterior.sample( n2, seed=None) toc = timeit.default_timer() logger.info("Time: %.3f sec \n" % (toc - tic)) self.inference_state["_has_drawn_samples"] = True # define result class self.result = self.extract_result() def eval_unnorm_posterior(self, theta): """Evaluate the unnormalized posterior. The operation is NOT vectorized. Parameters ---------- theta: np.ndarray (BS, D) the position to evaluate Returns ------- np.array: (BS,) """ # if nothing has been done, apply all steps assert self.inference_state["_has_defined_posterior"], "You must train first" # eval posterior assert theta.ndim == 2 assert theta.shape[1] == self.dim tic = timeit.default_timer() result = self.posterior.pdf_unnorm_batched(theta) toc = timeit.default_timer() logger.info("Time: %.3f sec \n" % (toc - tic)) return result def eval_posterior(self, theta): """Evaluate the normalized posterior. The operation is NOT vectorized. Parameters ---------- theta: np.ndarray (BS, D) Returns ------- np.array: (BS,) """ assert self.inference_state["_has_defined_posterior"], "You must train first" assert self.bounds is not None, "You have to set the bounds in order " \ "to approximate the partition function" # eval posterior assert theta.ndim == 2 assert theta.shape[1] == self.dim tic = timeit.default_timer() result = self.posterior.pdf(theta) toc = timeit.default_timer() logger.info("Time: %.3f sec \n" % (toc - tic)) return result def compute_expectation(self, h): """Compute an expectation, based on h. Parameters ---------- h: Callable Returns ------- float or np.array, depending on the return value of the Callable h """ assert self.inference_state["_has_drawn_samples"], "Draw samples first" return self.posterior.compute_expectation(h, self.samples, self.weights) # Evaluation Routines def compute_ess(self): """Compute the Effective Sample Size. Returns ------- float The effective sample size. """ assert self.inference_state["_has_drawn_samples"] return compute_ess(self.result.weights) def compute_divergence(self, gt_posterior, bounds=None, step=0.1, distance="Jensen-Shannon"): """Compute divergence between ROMC posterior and ground-truth. Parameters ---------- gt_posterior: Callable, ground-truth posterior, must accepted input in a batched fashion (np.ndarray with shape: (BS,D)) bounds: List[(start, stop)] if bounds are not passed at the ROMC constructor, they can be passed here step: float distance: str which distance to use. must be in ["Jensen-Shannon", "KL-Divergence"] Returns ------- float: The computed divergence between the distributions """ assert self.inference_state["_has_defined_posterior"] assert distance in ["Jensen-Shannon", "KL-Divergence"] if bounds is None: assert self.bounds is not None, "You have to define the prior's " \ "limits in order to compute the divergence" # compute limits left_lim = self.left_lim right_lim = self.right_lim limits = tuple([(left_lim[i], right_lim[i]) for i in range(len(left_lim))]) p = self.eval_posterior q = gt_posterior dim = len(limits) assert dim > 0 assert distance in ["KL-Divergence", "Jensen-Shannon"] if dim == 1: left = limits[0][0] right = limits[0][1] nof_points = int((right - left) / step) x = np.linspace(left, right, nof_points) x = np.expand_dims(x, -1) p_points = np.squeeze(p(x)) q_points = np.squeeze(q(x)) elif dim == 2: left = limits[0][0] right = limits[0][1] nof_points = int((right - left) / step) x = np.linspace(left, right, nof_points) left = limits[1][0] right = limits[1][1] nof_points = int((right - left) / step) y = np.linspace(left, right, nof_points) x, y = np.meshgrid(x, y) inp = np.stack((x.flatten(), y.flatten()), -1) p_points = np.squeeze(p(inp)) q_points = np.squeeze(q(inp)) else: logger.info("Computational approximation of KL Divergence on D > 2 is intractable.") return None # compute distance if distance == "KL-Divergence": return ss.entropy(p_points, q_points) elif distance == "Jensen-Shannon": return spatial.distance.jensenshannon(p_points, q_points) def extract_result(self): """Extract the result from the current state. Returns ------- result : Sample """ if self.samples is None: raise ValueError('Nothing to extract') method_name = "ROMC" parameter_names = self.model.parameter_names discrepancy_name = self.discrepancy_name weights = self.weights.flatten() outputs = {} for i, name in enumerate(self.model.parameter_names): outputs[name] = self.samples[:, :, i].flatten() outputs[discrepancy_name] = self.distances.flatten() return RomcSample(method_name=method_name, outputs=outputs, parameter_names=parameter_names, discrepancy_name=discrepancy_name, weights=weights) # Inspection Routines def visualize_region(self, i, savefig=False): """Plot the acceptance area of the i-th optimisation problem. Parameters ---------- i: int, index of the problem savefig: None or path """ assert self.inference_state["_has_estimated_regions"] self.posterior.visualize_region(i, samples=self.samples, savefig=savefig) def distance_hist(self, savefig=False, **kwargs): """Plot a histogram of the distances at the optimal point. Parameters ---------- savefig: False or str, if str it must be the path to save the figure kwargs: Dict with arguments to be passed to the plt.hist() """ assert self.inference_state["_has_solved_problems"] # collect all optimal distances opt_probs = self.optim_problems dist = [] for i in range(len(opt_probs)): if opt_probs[i].state["solved"]: d = opt_probs[i].result.f_min if opt_probs[i].result.f_min > 0 else 0 dist.append(d) plt.figure() plt.title("Histogram of distances") plt.ylabel("number of problems") plt.xlabel("distance") plt.hist(dist, **kwargs) # if savefig=path, save to the appropriate location if savefig: plt.savefig(savefig, bbox_inches='tight') plt.show(block=False) class OptimisationProblem: """Base class for a deterministic optimisation problem.""" def __init__(self, ind, nuisance, parameter_names, target_name, objective, dim, prior, n1, bounds): """Class constructor. Parameters ---------- ind: int, index of the optimisation problem, must be unique nuisance: int, the seed used for defining the objective parameter_names: List[str] names of the parameters target_name: str name of the output node objective: Callable(np.ndarray) -> float the objective function dim: int the dimensionality of the problem prior: ModelPrior prior distribution of the inference n1: int number of optimisation problems defined bounds: List[(start, stop)] bounds of the optimisation problem """ self.ind = ind self.nuisance = nuisance self.objective = objective self.dim = dim self.bounds = bounds self.parameter_names = parameter_names self.target_name = target_name self.prior = prior self.n1 = n1 # state of the optimization problems self.state = {"attempted": False, "solved": False, "has_fit_surrogate": False, "has_fit_local_surrogates": False, "region": False} # store as None as values self.surrogate = None self.local_surrogate = None self.result = None self.regions = None self.eps_region = None self.initial_point = None def solve_gradients(self, **kwargs): """Solve the optimisation problem using the scipy.optimise. Parameters ---------- **kwargs: all input arguments to the optimiser. In the current implementation the arguments used if defined are: ["seed", "x0", "method", "jac"]. All the rest will be ignored. Returns ------- Boolean, whether the optimisation reached an end point """ # prepare inputs seed = kwargs["seed"] if "seed" in kwargs else None if "x0" not in kwargs: x0 = self.prior.rvs(size=self.n1, random_state=seed)[self.ind] else: x0 = kwargs["x0"] method = "L-BFGS-B" if "method" not in kwargs else kwargs["method"] jac = kwargs["jac"] if "jac" in kwargs else None fun = self.objective self.state["attempted"] = True try: res = optim.minimize(fun=fun, x0=x0, method=method, jac=jac) if res.success: self.state["solved"] = True jac = res.jac if hasattr(res, "jac") else None hess_inv = res.hess_inv.todense() if hasattr(res, "hess_inv") else None self.result = RomcOpimisationResult( res.x, res.fun, jac, hess_inv) self.initial_point = x0 return True else: self.state["solved"] = False return False except ValueError: self.state["solved"] = False return False def solve_bo(self, **kwargs): """Solve the optimisation problem using the BoDeterministic. Parameters ---------- **kwargs: all input arguments to the optimiser. In the current implementation the arguments used if defined are: ["n_evidence", "acq_noise_var"]. All the rest will be ignored. Returns ------- Boolean, whether the optimisation reached an end point """ if self.bounds is not None: bounds = {k: self.bounds[i] for (i, k) in enumerate(self.parameter_names)} else: bounds = None # prepare_inputs n_evidence = 20 if "n_evidence" not in kwargs else kwargs["n_evidence"] acq_noise_var = .1 if "acq_noise_var" not in kwargs else kwargs["acq_noise_var"] def create_surrogate_objective(trainer): def surrogate_objective(theta): return trainer.target_model.predict_mean(np.atleast_2d(theta)).item() return surrogate_objective target_model = GPyRegression(parameter_names=self.parameter_names, bounds=bounds) trainer = BoDetereministic(objective=self.objective, prior=self.prior, parameter_names=self.parameter_names, n_evidence=n_evidence, target_name=self.target_name, bounds=bounds, target_model=target_model, acq_noise_var=acq_noise_var) trainer.fit() # self.gp = trainer self.surrogate = create_surrogate_objective(trainer) param_names = self.parameter_names x = batch_to_arr2d(trainer.result.x_min, param_names) x = np.squeeze(x, 0) x_min = x self.result = RomcOpimisationResult( x_min, self.surrogate(x_min)) self.state["attempted"] = True self.state["solved"] = True self.state["has_fit_surrogate"] = True return True def build_region(self, **kwargs): """Compute the n-dimensional Bounding Box. Parameters ---------- kwargs: all input arguments to the regionConstructor. Returns ------- boolean, whether the region construction was successful """ assert self.state["solved"] if "use_surrogate" in kwargs: use_surrogate = kwargs["use_surrogate"] else: use_surrogate = True if self.state["_has_fit_surrogate"] else False if use_surrogate: assert self.surrogate is not None, \ "You have to first fit a surrogate model, in order to use it." func = self.surrogate if use_surrogate else self.objective step = 0.05 if "step" not in kwargs else kwargs["step"] lim = 100 if "lim" not in kwargs else kwargs["lim"] assert "eps_region" in kwargs, \ "In the current build region implementation, kwargs must contain eps_region" eps_region = kwargs["eps_region"] self.eps_region = eps_region # construct region constructor = RegionConstructor( self.result, func, self.dim, eps_region=eps_region, lim=lim, step=step) self.regions = constructor.build() # update the state self.state["region"] = True return True def _local_surrogate(self, theta, model_scikit): assert theta.ndim == 1 theta = np.expand_dims(theta, 0) return float(model_scikit.predict(theta)) def _create_local_surrogate(self, model): return partial(self._local_surrogate, model_scikit=model) def fit_local_surrogate(self, **kwargs): """Fit a local quadratic model around the optimal distance. Parameters ---------- kwargs: all keyword arguments use_surrogate: bool whether to use the surrogate model fitted with Bayesian Optimisation nof_samples: int number of sampled points to be used for fitting the model Returns ------- Callable, The fitted model """ nof_samples = 20 if "nof_samples" not in kwargs else kwargs["nof_samples"] if "use_surrogate" not in kwargs: objective = self.surrogate if self.state["has_fit_surrogate"] else self.objective else: objective = self.surrogate if kwargs["use_surrogate"] else self.objective # def create_local_surrogate(model): # def local_surrogate(theta): # assert theta.ndim == 1 # # theta = np.expand_dims(theta, 0) # return float(model.predict(theta)) # return local_surrogate local_surrogates = [] for i in range(len(self.regions)): # prepare dataset x = self.regions[i].sample(nof_samples) y = np.array([objective(ii) for ii in x]) model = Pipeline([('poly', PolynomialFeatures(degree=2)), ('linear', LinearRegression(fit_intercept=False))]) model = model.fit(x, y) # local_surrogates.append(create_local_surrogate(model)) local_surrogates.append(self._create_local_surrogate(model)) self.local_surrogate = local_surrogates self.state["local_surrogates"] = True class RomcOpimisationResult: """Base class for the optimisation result of the ROMC method.""" def __init__(self, x_min, f_min, jac=None, hess=None, hess_inv=None): """Class constructor. Parameters ---------- x_min: np.ndarray (D,) or float f_min: float jac: np.ndarray (D,) hess_inv: np.ndarray (DxD) """ self.x_min = np.atleast_1d(x_min) self.f_min = f_min self.jac = jac self.hess = hess self.hess_inv = hess_inv class RegionConstructor: """Class for constructing an n-dim bounding box region.""" def __init__(self, result: RomcOpimisationResult, func, dim, eps_region, lim, step): """Class constructor. Parameters ---------- result: object of RomcOptimisationResult func: Callable(np.ndarray) -> float dim: int eps_region: threshold lim: float, largets translation along the search direction step: float, step along the search direction """ self.res = result self.func = func self.dim = dim self.eps_region = eps_region self.lim = lim self.step = step def build(self): """Build the bounding box. Returns ------- List[NDimBoundingBox] """ res = self.res func = self.func dim = self.dim eps = self.eps_region lim = self.lim step = self.step theta_0 = np.array(res.x_min, dtype=np.float) if res.hess is not None: hess_appr = res.hess elif res.hess_inv is not None: # TODO add check for inverse if np.linalg.matrix_rank(res.hess_inv) != dim: hess_appr = np.eye(dim) else: hess_appr = np.linalg.inv(res.hess_inv) else: h = 1e-5 grad_vec = optim.approx_fprime(theta_0, func, h) grad_vec = np.expand_dims(grad_vec, -1) hess_appr = np.dot(grad_vec, grad_vec.T) if np.isnan(np.sum(hess_appr)) or np.isinf(np.sum(hess_appr)): hess_appr = np.eye(dim) assert hess_appr.shape[0] == dim assert hess_appr.shape[1] == dim if np.isnan(np.sum(hess_appr)) or np.isinf(np.sum(hess_appr)): logger.info("Eye matrix return as rotation.") hess_appr = np.eye(dim) eig_val, eig_vec = np.linalg.eig(hess_appr) # if extreme values appear, return the I matrix if np.isnan(np.sum(eig_vec)) or np.isinf(np.sum(eig_vec)) or (eig_vec.dtype == np.complex): logger.info("Eye matrix return as rotation.") eig_vec = np.eye(dim) if np.linalg.matrix_rank(eig_vec) < dim: eig_vec = np.eye(dim) rotation = eig_vec # compute limits nof_points = int(lim / step) bounding_box = [] for j in range(dim): bounding_box.append([]) vect = eig_vec[:, j] # right side point = theta_0.copy() v_right = 0 for i in range(1, nof_points + 1): point += step * vect if func(point) > eps: v_right = i * step - step / 2 break if i == nof_points: v_right = (i - 1) * step # left side point = theta_0.copy() v_left = 0 for i in range(1, nof_points + 1): point -= step * vect if func(point) > eps: v_left = -i * step + step / 2 break if i == nof_points: v_left = - (i - 1) * step if v_left == 0: v_left = -step / 2 if v_right == 0: v_right = step / 2 bounding_box[j].append(v_left) bounding_box[j].append(v_right) bounding_box = np.array(bounding_box) assert bounding_box.ndim == 2 assert bounding_box.shape[0] == dim assert bounding_box.shape[1] == 2 bb = [NDimBoundingBox(rotation, theta_0, bounding_box, eps)] return bb
[ "logging.getLogger", "numpy.linalg.matrix_rank", "sklearn.preprocessing.PolynomialFeatures", "matplotlib.pyplot.hist", "elfi.visualization.visualization.ProgressBar", "matplotlib.pyplot.ylabel", "numpy.eye", "elfi.methods.utils.ceil_to_batch_size", "elfi.methods.utils.compute_ess", "numpy.argsort"...
[((1499, 1526), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1516, 1526), False, 'import logging\n'), ((4330, 4393), 'elfi.model.elfi_model.ComputationContext', 'ComputationContext', ([], {'batch_size': 'batch_size', 'seed': 'seed', 'pool': 'pool'}), '(batch_size=batch_size, seed=seed, pool=pool)\n', (4348, 4393), False, 'from elfi.model.elfi_model import AdaptiveDistance, ComputationContext, ElfiModel, NodeReference\n'), ((5375, 5461), 'elfi.visualization.visualization.ProgressBar', 'ProgressBar', ([], {'prefix': '"""Progress"""', 'suffix': '"""Complete"""', 'decimals': '(1)', 'length': '(50)', 'fill': '"""="""'}), "(prefix='Progress', suffix='Complete', decimals=1, length=50,\n fill='=')\n", (5386, 5461), False, 'from elfi.visualization.visualization import ProgressBar\n'), ((21395, 21420), 'numpy.argsort', 'np.argsort', (['sort_distance'], {}), '(sort_distance)\n', (21405, 21420), True, 'import numpy as np\n'), ((23584, 23609), 'numpy.argsort', 'np.argsort', (['sort_distance'], {}), '(sort_distance)\n', (23594, 23609), True, 'import numpy as np\n'), ((24335, 24469), 'elfi.visualization.interactive.plot_sample', 'visin.plot_sample', (["self.state['samples']"], {'nodes': 'self.parameter_names', 'n': "self.objective['n_samples']", 'displays': 'displays'}), "(self.state['samples'], nodes=self.parameter_names, n=self\n .objective['n_samples'], displays=displays, **options)\n", (24352, 24469), True, 'import elfi.visualization.interactive as visin\n'), ((25415, 25437), 'elfi.methods.utils.ModelPrior', 'ModelPrior', (['self.model'], {}), '(self.model)\n', (25425, 25437), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((27809, 27944), 'elfi.methods.utils.GMDistribution.rvs', 'GMDistribution.rvs', (['*self._gm_params'], {'size': 'self.batch_size', 'prior_logpdf': 'self._prior.logpdf', 'random_state': 'self._round_random_state'}), '(*self._gm_params, size=self.batch_size, prior_logpdf=\n self._prior.logpdf, random_state=self._round_random_state)\n', (27827, 27944), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((28029, 28073), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['params', 'self.parameter_names'], {}), '(params, self.parameter_names)\n', (28043, 28073), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((28682, 28709), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (28703, 28709), True, 'import numpy as np\n'), ((34296, 34323), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (34317, 34323), True, 'import numpy as np\n'), ((35562, 35620), 'elfi.methods.results.Sample', 'Sample', (['method_name', 'outputs', 'self.parameter_names'], {}), '(method_name, outputs, self.parameter_names, **meta)\n', (35568, 35620), False, 'from elfi.methods.results import BolfiSample, OptimizationResult, RomcSample, Sample, SmcSample\n'), ((40530, 40577), 'elfi.methods.utils.ceil_to_batch_size', 'ceil_to_batch_size', (['n_required', 'self.batch_size'], {}), '(n_required, self.batch_size)\n', (40548, 40577), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((43007, 43109), 'elfi.methods.bo.utils.stochastic_optimization', 'stochastic_optimization', (['self.target_model.predict_mean', 'self.target_model.bounds'], {'seed': 'self.seed'}), '(self.target_model.predict_mean, self.target_model.\n bounds, seed=self.seed)\n', (43030, 43109), False, 'from elfi.methods.bo.utils import stochastic_optimization\n'), ((43139, 43182), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['x_min', 'self.parameter_names'], {}), '(x_min, self.parameter_names)\n', (43153, 43182), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((43201, 43258), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['self.target_model.X', 'self.parameter_names'], {}), '(self.target_model.X, self.parameter_names)\n', (43215, 43258), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((43901, 43944), 'elfi.methods.utils.batch_to_arr2d', 'batch_to_arr2d', (['batch', 'self.parameter_names'], {}), '(batch, self.parameter_names)\n', (43915, 43944), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((45071, 45138), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['acquisition[:self.batch_size]', 'self.parameter_names'], {}), '(acquisition[:self.batch_size], self.parameter_names)\n', (45085, 45138), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((47099, 47108), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (47106, 47108), True, 'import matplotlib.pyplot as plt\n'), ((47308, 47448), 'elfi.visualization.interactive.draw_contour', 'visin.draw_contour', (['gp.predict_mean', 'gp.bounds', 'self.parameter_names'], {'title': '"""GP target surface"""', 'points': 'gp.X', 'axes': 'f.axes[0]'}), "(gp.predict_mean, gp.bounds, self.parameter_names, title=\n 'GP target surface', points=gp.X, axes=f.axes[0], **options)\n", (47326, 47448), True, 'import elfi.visualization.interactive as visin\n'), ((48052, 48096), 'elfi.visualization.interactive._update_interactive', 'visin._update_interactive', (['displays', 'options'], {}), '(displays, options)\n', (48077, 48096), True, 'import elfi.visualization.interactive as visin\n'), ((48232, 48362), 'elfi.visualization.interactive.draw_contour', 'visin.draw_contour', (['acq', 'gp.bounds', 'self.parameter_names'], {'title': '"""Acquisition surface"""', 'points': 'None', 'axes': 'f.axes[1]'}), "(acq, gp.bounds, self.parameter_names, title=\n 'Acquisition surface', points=None, axes=f.axes[1], **options)\n", (48250, 48362), True, 'import elfi.visualization.interactive as visin\n'), ((48801, 48888), 'elfi.visualization.visualization.plot_discrepancy', 'vis.plot_discrepancy', (['self.target_model', 'self.parameter_names'], {'axes': 'axes'}), '(self.target_model, self.parameter_names, axes=axes, **\n kwargs)\n', (48821, 48888), True, 'import elfi.visualization.visualization as vis\n'), ((49669, 49776), 'elfi.visualization.visualization.plot_gp', 'vis.plot_gp', (['self.target_model', 'self.parameter_names', 'axes', 'resol', 'const', 'bounds', 'true_params'], {}), '(self.target_model, self.parameter_names, axes, resol, const,\n bounds, true_params, **kwargs)\n', (49680, 49776), True, 'import elfi.visualization.visualization as vis\n'), ((56940, 56958), 'numpy.asarray', 'np.asarray', (['chains'], {}), '(chains)\n', (56950, 56958), True, 'import numpy as np\n'), ((62702, 62749), 'elfi.methods.utils.ceil_to_batch_size', 'ceil_to_batch_size', (['n_required', 'self.batch_size'], {}), '(n_required, self.batch_size)\n', (62720, 62749), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((65556, 65658), 'elfi.methods.bo.utils.stochastic_optimization', 'stochastic_optimization', (['self.target_model.predict_mean', 'self.target_model.bounds'], {'seed': 'self.seed'}), '(self.target_model.predict_mean, self.target_model.\n bounds, seed=self.seed)\n', (65579, 65658), False, 'from elfi.methods.bo.utils import stochastic_optimization\n'), ((65688, 65731), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['x_min', 'self.parameter_names'], {}), '(x_min, self.parameter_names)\n', (65702, 65731), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((65750, 65807), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['self.target_model.X', 'self.parameter_names'], {}), '(self.target_model.X, self.parameter_names)\n', (65764, 65807), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((66452, 66495), 'elfi.methods.utils.batch_to_arr2d', 'batch_to_arr2d', (['batch', 'self.parameter_names'], {}), '(batch, self.parameter_names)\n', (66466, 66495), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((67633, 67700), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['acquisition[:self.batch_size]', 'self.parameter_names'], {}), '(acquisition[:self.batch_size], self.parameter_names)\n', (67647, 67700), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((69503, 69512), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (69510, 69512), True, 'import matplotlib.pyplot as plt\n'), ((69712, 69852), 'elfi.visualization.interactive.draw_contour', 'visin.draw_contour', (['gp.predict_mean', 'gp.bounds', 'self.parameter_names'], {'title': '"""GP target surface"""', 'points': 'gp.X', 'axes': 'f.axes[0]'}), "(gp.predict_mean, gp.bounds, self.parameter_names, title=\n 'GP target surface', points=gp.X, axes=f.axes[0], **options)\n", (69730, 69852), True, 'import elfi.visualization.interactive as visin\n'), ((70456, 70500), 'elfi.visualization.interactive._update_interactive', 'visin._update_interactive', (['displays', 'options'], {}), '(displays, options)\n', (70481, 70500), True, 'import elfi.visualization.interactive as visin\n'), ((70636, 70766), 'elfi.visualization.interactive.draw_contour', 'visin.draw_contour', (['acq', 'gp.bounds', 'self.parameter_names'], {'title': '"""Acquisition surface"""', 'points': 'None', 'axes': 'f.axes[1]'}), "(acq, gp.bounds, self.parameter_names, title=\n 'Acquisition surface', points=None, axes=f.axes[1], **options)\n", (70654, 70766), True, 'import elfi.visualization.interactive as visin\n'), ((71205, 71292), 'elfi.visualization.visualization.plot_discrepancy', 'vis.plot_discrepancy', (['self.target_model', 'self.parameter_names'], {'axes': 'axes'}), '(self.target_model, self.parameter_names, axes=axes, **\n kwargs)\n', (71225, 71292), True, 'import elfi.visualization.visualization as vis\n'), ((72073, 72180), 'elfi.visualization.visualization.plot_gp', 'vis.plot_gp', (['self.target_model', 'self.parameter_names', 'axes', 'resol', 'const', 'bounds', 'true_params'], {}), '(self.target_model, self.parameter_names, axes, resol, const,\n bounds, true_params, **kwargs)\n', (72084, 72180), True, 'import elfi.visualization.visualization as vis\n'), ((73511, 73528), 'elfi.methods.utils.ModelPrior', 'ModelPrior', (['model'], {}), '(model)\n', (73521, 73528), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((75592, 75605), 'elfi.visualization.visualization.ProgressBar', 'ProgressBar', ([], {}), '()\n', (75603, 75605), False, 'from elfi.visualization.visualization import ProgressBar\n'), ((78075, 78123), 'elfi.methods.utils.flat_array_to_dict', 'flat_array_to_dict', (['model.parameter_names', 'theta'], {}), '(model.parameter_names, theta)\n', (78093, 78123), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((78621, 78660), 'functools.partial', 'partial', (['self._det_generator'], {'seed': 'seed'}), '(self._det_generator, seed=seed)\n', (78628, 78660), False, 'from functools import partial\n'), ((80160, 80182), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (80180, 80182), False, 'import timeit\n'), ((80873, 80895), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (80893, 80895), False, 'import timeit\n'), ((81890, 81912), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (81910, 81912), False, 'import timeit\n'), ((82145, 82167), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (82165, 82167), False, 'import timeit\n'), ((83063, 83090), 'numpy.quantile', 'np.quantile', (['dist', 'quantile'], {}), '(dist, quantile)\n', (83074, 83090), True, 'import numpy as np\n'), ((88645, 88779), 'elfi.methods.posteriors.RomcPosterior', 'RomcPosterior', (['regions', 'funcs', 'nuisance', 'funcs_unique', 'prior', 'left_lim', 'right_lim', 'eps_filter', 'eps_region', 'eps_cutoff', 'parallelize'], {}), '(regions, funcs, nuisance, funcs_unique, prior, left_lim,\n right_lim, eps_filter, eps_region, eps_cutoff, parallelize)\n', (88658, 88779), False, 'from elfi.methods.posteriors import BolfiPosterior, RomcPosterior\n'), ((95410, 95432), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (95430, 95432), False, 'import timeit\n'), ((95488, 95510), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (95508, 95510), False, 'import timeit\n'), ((96409, 96431), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (96429, 96431), False, 'import timeit\n'), ((96549, 96571), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (96569, 96571), False, 'import timeit\n'), ((97318, 97340), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (97338, 97340), False, 'import timeit\n'), ((97413, 97435), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (97433, 97435), False, 'import timeit\n'), ((98134, 98156), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (98154, 98156), False, 'import timeit\n'), ((98214, 98236), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (98234, 98236), False, 'import timeit\n'), ((99011, 99043), 'elfi.methods.utils.compute_ess', 'compute_ess', (['self.result.weights'], {}), '(self.result.weights)\n', (99022, 99043), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((102322, 102464), 'elfi.methods.results.RomcSample', 'RomcSample', ([], {'method_name': 'method_name', 'outputs': 'outputs', 'parameter_names': 'parameter_names', 'discrepancy_name': 'discrepancy_name', 'weights': 'weights'}), '(method_name=method_name, outputs=outputs, parameter_names=\n parameter_names, discrepancy_name=discrepancy_name, weights=weights)\n', (102332, 102464), False, 'from elfi.methods.results import BolfiSample, OptimizationResult, RomcSample, Sample, SmcSample\n'), ((103762, 103774), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (103772, 103774), True, 'import matplotlib.pyplot as plt\n'), ((103783, 103818), 'matplotlib.pyplot.title', 'plt.title', (['"""Histogram of distances"""'], {}), "('Histogram of distances')\n", (103792, 103818), True, 'import matplotlib.pyplot as plt\n'), ((103827, 103859), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""number of problems"""'], {}), "('number of problems')\n", (103837, 103859), True, 'import matplotlib.pyplot as plt\n'), ((103868, 103890), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""distance"""'], {}), "('distance')\n", (103878, 103890), True, 'import matplotlib.pyplot as plt\n'), ((103899, 103923), 'matplotlib.pyplot.hist', 'plt.hist', (['dist'], {}), '(dist, **kwargs)\n', (103907, 103923), True, 'import matplotlib.pyplot as plt\n'), ((104067, 104088), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (104075, 104088), True, 'import matplotlib.pyplot as plt\n'), ((108454, 108520), 'elfi.methods.bo.gpy_regression.GPyRegression', 'GPyRegression', ([], {'parameter_names': 'self.parameter_names', 'bounds': 'bounds'}), '(parameter_names=self.parameter_names, bounds=bounds)\n', (108467, 108520), False, 'from elfi.methods.bo.gpy_regression import GPyRegression\n'), ((109212, 109261), 'elfi.methods.utils.batch_to_arr2d', 'batch_to_arr2d', (['trainer.result.x_min', 'param_names'], {}), '(trainer.result.x_min, param_names)\n', (109226, 109261), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((109274, 109290), 'numpy.squeeze', 'np.squeeze', (['x', '(0)'], {}), '(x, 0)\n', (109284, 109290), True, 'import numpy as np\n'), ((111008, 111032), 'numpy.expand_dims', 'np.expand_dims', (['theta', '(0)'], {}), '(theta, 0)\n', (111022, 111032), True, 'import numpy as np\n'), ((111145, 111195), 'functools.partial', 'partial', (['self._local_surrogate'], {'model_scikit': 'model'}), '(self._local_surrogate, model_scikit=model)\n', (111152, 111195), False, 'from functools import partial\n'), ((113324, 113344), 'numpy.atleast_1d', 'np.atleast_1d', (['x_min'], {}), '(x_min)\n', (113337, 113344), True, 'import numpy as np\n'), ((114452, 114487), 'numpy.array', 'np.array', (['res.x_min'], {'dtype': 'np.float'}), '(res.x_min, dtype=np.float)\n', (114460, 114487), True, 'import numpy as np\n'), ((115401, 115425), 'numpy.linalg.eig', 'np.linalg.eig', (['hess_appr'], {}), '(hess_appr)\n', (115414, 115425), True, 'import numpy as np\n'), ((116941, 116963), 'numpy.array', 'np.array', (['bounding_box'], {}), '(bounding_box)\n', (116949, 116963), True, 'import numpy as np\n'), ((17360, 17386), 'math.ceil', 'ceil', (['(n_samples / quantile)'], {}), '(n_samples / quantile)\n', (17364, 17386), False, 'from math import ceil\n'), ((17471, 17500), 'math.ceil', 'ceil', (['(n_sim / self.batch_size)'], {}), '(n_sim / self.batch_size)\n', (17475, 17500), False, 'from math import ceil\n'), ((20959, 20975), 'numpy.sum', 'np.sum', (['accepted'], {}), '(accepted)\n', (20965, 20975), True, 'import numpy as np\n'), ((22911, 22926), 'math.ceil', 'ceil', (['n_batches'], {}), '(n_batches)\n', (22915, 22926), False, 'from math import ceil\n'), ((28616, 28646), 'elfi.loader.get_sub_seed', 'get_sub_seed', (['self.seed', 'round'], {}), '(self.seed, round)\n', (28628, 28646), False, 'from elfi.loader import get_sub_seed\n'), ((29632, 29679), 'elfi.methods.utils.GMDistribution.logpdf', 'GMDistribution.logpdf', (['params', '*self._gm_params'], {}), '(params, *self._gm_params)\n', (29653, 29679), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((29746, 29773), 'numpy.exp', 'np.exp', (['(p_logpdf - q_logpdf)'], {}), '(p_logpdf - q_logpdf)\n', (29752, 29773), True, 'import numpy as np\n'), ((29804, 29826), 'numpy.ones', 'np.ones', (['pop.n_samples'], {}), '(pop.n_samples)\n', (29811, 29826), True, 'import numpy as np\n'), ((29839, 29858), 'numpy.count_nonzero', 'np.count_nonzero', (['w'], {}), '(w)\n', (29855, 29858), True, 'import numpy as np\n'), ((34230, 34260), 'elfi.loader.get_sub_seed', 'get_sub_seed', (['self.seed', 'round'], {}), '(self.seed, round)\n', (34242, 34260), False, 'from elfi.loader import get_sub_seed\n'), ((34858, 34907), 'math.ceil', 'ceil', (["(self.objective['n_samples'] / self.quantile)"], {}), "(self.objective['n_samples'] / self.quantile)\n", (34862, 34907), False, 'from math import ceil\n'), ((38866, 38922), 'elfi.methods.bo.gpy_regression.GPyRegression', 'GPyRegression', (['self.model.parameter_names'], {'bounds': 'bounds'}), '(self.model.parameter_names, bounds=bounds)\n', (38879, 38922), False, 'from elfi.methods.bo.gpy_regression import GPyRegression\n'), ((39196, 39245), 'elfi.methods.utils.batch_to_arr2d', 'batch_to_arr2d', (['precomputed', 'self.parameter_names'], {}), '(precomputed, self.parameter_names)\n', (39210, 39245), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((41684, 41739), 'elfi.methods.utils.ceil_to_batch_size', 'ceil_to_batch_size', (['n_initial_evidence', 'self.batch_size'], {}), '(n_initial_evidence, self.batch_size)\n', (41702, 41739), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((47156, 47219), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(13, 6)', 'sharex': '"""row"""', 'sharey': '"""row"""'}), "(1, 2, figsize=(13, 6), sharex='row', sharey='row')\n", (47168, 47219), True, 'import matplotlib.pyplot as plt\n'), ((48489, 48500), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (48498, 48500), True, 'import matplotlib.pyplot as plt\n'), ((54672, 54709), 'numpy.argsort', 'np.argsort', (['self.target_model.Y[:, 0]'], {}), '(self.target_model.Y[:, 0])\n', (54682, 54709), True, 'import numpy as np\n'), ((54733, 54770), 'numpy.asarray', 'np.asarray', (['self.target_model.X[inds]'], {}), '(self.target_model.X[inds])\n', (54743, 54770), True, 'import numpy as np\n'), ((55506, 55533), 'elfi.loader.get_sub_seed', 'get_sub_seed', (['self.seed', 'ii'], {}), '(self.seed, ii)\n', (55518, 55533), False, 'from elfi.loader import get_sub_seed\n'), ((61422, 61471), 'elfi.methods.utils.batch_to_arr2d', 'batch_to_arr2d', (['precomputed', 'self.parameter_names'], {}), '(precomputed, self.parameter_names)\n', (61436, 61471), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((61681, 61803), 'elfi.methods.bo.acquisition.LCBSC', 'LCBSC', (['self.target_model'], {'prior': 'self.prior', 'noise_var': 'acq_noise_var', 'exploration_rate': 'exploration_rate', 'seed': 'self.seed'}), '(self.target_model, prior=self.prior, noise_var=acq_noise_var,\n exploration_rate=exploration_rate, seed=self.seed)\n', (61686, 61803), False, 'from elfi.methods.bo.acquisition import LCBSC\n'), ((63856, 63911), 'elfi.methods.utils.ceil_to_batch_size', 'ceil_to_batch_size', (['n_initial_evidence', 'self.batch_size'], {}), '(n_initial_evidence, self.batch_size)\n', (63874, 63911), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((69560, 69623), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(13, 6)', 'sharex': '"""row"""', 'sharey': '"""row"""'}), "(1, 2, figsize=(13, 6), sharex='row', sharey='row')\n", (69572, 69623), True, 'import matplotlib.pyplot as plt\n'), ((70893, 70904), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (70902, 70904), True, 'import matplotlib.pyplot as plt\n'), ((73622, 73678), 'numpy.array', 'np.array', (['[bound[0] for bound in bounds]'], {'dtype': 'np.float'}), '([bound[0] for bound in bounds], dtype=np.float)\n', (73630, 73678), True, 'import numpy as np\n'), ((73769, 73825), 'numpy.array', 'np.array', (['[bound[1] for bound in bounds]'], {'dtype': 'np.float'}), '([bound[1] for bound in bounds], dtype=np.float)\n', (73777, 73825), True, 'import numpy as np\n'), ((80512, 80518), 'multiprocessing.Pool', 'Pool', ([], {}), '()\n', (80516, 80518), False, 'from multiprocessing import Pool\n'), ((85340, 85346), 'multiprocessing.Pool', 'Pool', ([], {}), '()\n', (85344, 85346), False, 'from multiprocessing import Pool\n'), ((86465, 86471), 'multiprocessing.Pool', 'Pool', ([], {}), '()\n', (86469, 86471), False, 'from multiprocessing import Pool\n'), ((92363, 92385), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (92383, 92385), False, 'import timeit\n'), ((92456, 92478), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (92476, 92478), False, 'import timeit\n'), ((95109, 95147), 'numpy.sum', 'np.sum', (["self.inference_state['solved']"], {}), "(self.inference_state['solved'])\n", (95115, 95147), True, 'import numpy as np\n'), ((95176, 95216), 'numpy.sum', 'np.sum', (["self.inference_state['accepted']"], {}), "(self.inference_state['accepted'])\n", (95182, 95216), True, 'import numpy as np\n'), ((95666, 95688), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (95686, 95688), False, 'import timeit\n'), ((95755, 95777), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (95775, 95777), False, 'import timeit\n'), ((100622, 100658), 'numpy.linspace', 'np.linspace', (['left', 'right', 'nof_points'], {}), '(left, right, nof_points)\n', (100633, 100658), True, 'import numpy as np\n'), ((100675, 100696), 'numpy.expand_dims', 'np.expand_dims', (['x', '(-1)'], {}), '(x, -1)\n', (100689, 100696), True, 'import numpy as np\n'), ((101546, 101576), 'scipy.stats.entropy', 'ss.entropy', (['p_points', 'q_points'], {}), '(p_points, q_points)\n', (101556, 101576), True, 'import scipy.stats as ss\n'), ((104017, 104058), 'matplotlib.pyplot.savefig', 'plt.savefig', (['savefig'], {'bbox_inches': '"""tight"""'}), "(savefig, bbox_inches='tight')\n", (104028, 104058), True, 'import matplotlib.pyplot as plt\n'), ((106742, 106796), 'scipy.optimize.minimize', 'optim.minimize', ([], {'fun': 'fun', 'x0': 'x0', 'method': 'method', 'jac': 'jac'}), '(fun=fun, x0=x0, method=method, jac=jac)\n', (106756, 106796), True, 'import scipy.optimize as optim\n'), ((115361, 115372), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (115367, 115372), True, 'import numpy as np\n'), ((115663, 115674), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (115669, 115674), True, 'import numpy as np\n'), ((115686, 115716), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['eig_vec'], {}), '(eig_vec)\n', (115707, 115716), True, 'import numpy as np\n'), ((115746, 115757), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (115752, 115757), True, 'import numpy as np\n'), ((117103, 117156), 'elfi.methods.utils.NDimBoundingBox', 'NDimBoundingBox', (['rotation', 'theta_0', 'bounding_box', 'eps'], {}), '(rotation, theta_0, bounding_box, eps)\n', (117118, 117156), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((11843, 11890), 'math.ceil', 'ceil', (["(self.objective['n_sim'] / self.batch_size)"], {}), "(self.objective['n_sim'] / self.batch_size)\n", (11847, 11890), False, 'from math import ceil\n'), ((19522, 19538), 'elfi.utils.is_array', 'is_array', (['nbatch'], {}), '(nbatch)\n', (19530, 19538), False, 'from elfi.utils import is_array\n'), ((20155, 20183), 'numpy.empty', 'np.empty', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (20163, 20183), True, 'import numpy as np\n'), ((21325, 21369), 'numpy.transpose', 'np.transpose', (['samples[self.discrepancy_name]'], {}), '(samples[self.discrepancy_name])\n', (21337, 21369), True, 'import numpy as np\n'), ((23542, 23558), 'numpy.transpose', 'np.transpose', (['ds'], {}), '(ds)\n', (23554, 23558), True, 'import numpy as np\n'), ((30155, 30178), 'elfi.methods.utils.weighted_var', 'weighted_var', (['params', 'w'], {}), '(params, w)\n', (30167, 30178), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((30203, 30219), 'numpy.isfinite', 'np.isfinite', (['cov'], {}), '(cov)\n', (30214, 30219), True, 'import numpy as np\n'), ((30488, 30512), 'numpy.ones', 'np.ones', (['params.shape[1]'], {}), '(params.shape[1])\n', (30495, 30512), True, 'import numpy as np\n'), ((51986, 52008), 'elfi.methods.utils.ModelPrior', 'ModelPrior', (['self.model'], {}), '(self.model)\n', (51996, 52008), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((57201, 57239), 'elfi.methods.mcmc.eff_sample_size', 'mcmc.eff_sample_size', (['chains[:, :, ii]'], {}), '(chains[:, :, ii])\n', (57221, 57239), True, 'import elfi.methods.mcmc as mcmc\n'), ((57259, 57294), 'elfi.methods.mcmc.gelman_rubin', 'mcmc.gelman_rubin', (['chains[:, :, ii]'], {}), '(chains[:, :, ii])\n', (57276, 57294), True, 'import elfi.methods.mcmc as mcmc\n'), ((68477, 68518), 'elfi.methods.utils.arr2d_to_batch', 'arr2d_to_batch', (['inp', 'self.parameter_names'], {}), '(inp, self.parameter_names)\n', (68491, 68518), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((76200, 76230), 'scipy.stats.randint', 'ss.randint', ([], {'low': '(1)', 'high': 'up_lim'}), '(low=1, high=up_lim)\n', (76210, 76230), True, 'import scipy.stats as ss\n'), ((90972, 91013), 'numpy.sum', 'np.sum', (["self.inference_state['attempted']"], {}), "(self.inference_state['attempted'])\n", (90978, 91013), True, 'import numpy as np\n'), ((91085, 91123), 'numpy.sum', 'np.sum', (["self.inference_state['solved']"], {}), "(self.inference_state['solved'])\n", (91091, 91123), True, 'import numpy as np\n'), ((91195, 91235), 'numpy.sum', 'np.sum', (["self.inference_state['accepted']"], {}), "(self.inference_state['accepted'])\n", (91201, 91235), True, 'import numpy as np\n'), ((92654, 92676), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (92674, 92676), False, 'import timeit\n'), ((92740, 92762), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (92760, 92762), False, 'import timeit\n'), ((100935, 100971), 'numpy.linspace', 'np.linspace', (['left', 'right', 'nof_points'], {}), '(left, right, nof_points)\n', (100946, 100971), True, 'import numpy as np\n'), ((101105, 101141), 'numpy.linspace', 'np.linspace', (['left', 'right', 'nof_points'], {}), '(left, right, nof_points)\n', (101116, 101141), True, 'import numpy as np\n'), ((101162, 101179), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (101173, 101179), True, 'import numpy as np\n'), ((101639, 101689), 'scipy.spatial.distance.jensenshannon', 'spatial.distance.jensenshannon', (['p_points', 'q_points'], {}), '(p_points, q_points)\n', (101669, 101689), True, 'import scipy.spatial as spatial\n'), ((114866, 114903), 'scipy.optimize.approx_fprime', 'optim.approx_fprime', (['theta_0', 'func', 'h'], {}), '(theta_0, func, h)\n', (114885, 114903), True, 'import scipy.optimize as optim\n'), ((114927, 114955), 'numpy.expand_dims', 'np.expand_dims', (['grad_vec', '(-1)'], {}), '(grad_vec, -1)\n', (114941, 114955), True, 'import numpy as np\n'), ((114980, 115008), 'numpy.dot', 'np.dot', (['grad_vec', 'grad_vec.T'], {}), '(grad_vec, grad_vec.T)\n', (114986, 115008), True, 'import numpy as np\n'), ((115228, 115245), 'numpy.sum', 'np.sum', (['hess_appr'], {}), '(hess_appr)\n', (115234, 115245), True, 'import numpy as np\n'), ((115259, 115276), 'numpy.sum', 'np.sum', (['hess_appr'], {}), '(hess_appr)\n', (115265, 115276), True, 'import numpy as np\n'), ((115503, 115518), 'numpy.sum', 'np.sum', (['eig_vec'], {}), '(eig_vec)\n', (115509, 115518), True, 'import numpy as np\n'), ((115532, 115547), 'numpy.sum', 'np.sum', (['eig_vec'], {}), '(eig_vec)\n', (115538, 115547), True, 'import numpy as np\n'), ((20068, 20095), 'numpy.ones', 'np.ones', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (20075, 20095), True, 'import numpy as np\n'), ((20899, 20921), 'numpy.transpose', 'np.transpose', (['accepted'], {}), '(accepted)\n', (20911, 20921), True, 'import numpy as np\n'), ((39599, 39621), 'elfi.methods.utils.ModelPrior', 'ModelPrior', (['self.model'], {}), '(self.model)\n', (39609, 39621), False, 'from elfi.methods.utils import GMDistribution, ModelPrior, NDimBoundingBox, arr2d_to_batch, batch_to_arr2d, ceil_to_batch_size, compute_ess, flat_array_to_dict, weighted_var\n'), ((54459, 54479), 'numpy.asarray', 'np.asarray', (['initials'], {}), '(initials)\n', (54469, 54479), True, 'import numpy as np\n'), ((68424, 68447), 'numpy.expand_dims', 'np.expand_dims', (['inp', '(-1)'], {}), '(inp, -1)\n', (68438, 68447), True, 'import numpy as np\n'), ((114650, 114685), 'numpy.linalg.matrix_rank', 'np.linalg.matrix_rank', (['res.hess_inv'], {}), '(res.hess_inv)\n', (114671, 114685), True, 'import numpy as np\n'), ((114722, 114733), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (114728, 114733), True, 'import numpy as np\n'), ((114780, 114807), 'numpy.linalg.inv', 'np.linalg.inv', (['res.hess_inv'], {}), '(res.hess_inv)\n', (114793, 114807), True, 'import numpy as np\n'), ((115112, 115123), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (115118, 115123), True, 'import numpy as np\n'), ((22264, 22286), 'numpy.transpose', 'np.transpose', (['accepted'], {}), '(accepted)\n', (22276, 22286), True, 'import numpy as np\n'), ((68560, 68578), 'numpy.squeeze', 'np.squeeze', (['inp', '(0)'], {}), '(inp, 0)\n', (68570, 68578), True, 'import numpy as np\n'), ((112533, 112561), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': '(2)'}), '(degree=2)\n', (112551, 112561), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((112605, 112642), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'fit_intercept': '(False)'}), '(fit_intercept=False)\n', (112621, 112642), False, 'from sklearn.linear_model import LinearRegression\n'), ((115033, 115050), 'numpy.sum', 'np.sum', (['hess_appr'], {}), '(hess_appr)\n', (115039, 115050), True, 'import numpy as np\n'), ((115064, 115081), 'numpy.sum', 'np.sum', (['hess_appr'], {}), '(hess_appr)\n', (115070, 115081), True, 'import numpy as np\n'), ((108361, 108381), 'numpy.atleast_2d', 'np.atleast_2d', (['theta'], {}), '(theta)\n', (108374, 108381), True, 'import numpy as np\n')]
''' Created on 19.07.2021 @author: kai ''' import scipy.io from numpy import array import random def GetCorrelation(data,LOCALE_IDX): resultCount = 0 FILENAME="cor_fac.mat" FOLDER_LOCALE=["db/de-DE/","db/de-DE-s/","db/en-US/"] annots = scipy.io.loadmat(FOLDER_LOCALE[LOCALE_IDX]+FILENAME)['CorrelationFactors'] array_container=annots name = array(data[0][0]) ingredients = array(data[0][1]) link = array(data[0][2]) instructions = array(data[0][3]) randManNum = data[2] while resultCount < 5: if randManNum > 0: rand = randManNum else: rand = random.randrange(0, len(name), 1) seed = array_container[rand] index = array(seed) > data[1] i = 0 indices = [] while i < len(index): if index[i] == True: indices.append(i) i += 1 result = [name[indices], array(indices), ingredients[indices], link[indices], rand, instructions[indices]] if randManNum > 0: resultCount = 5 else: resultCount = len(result[0]) data = None return result
[ "numpy.array" ]
[((389, 406), 'numpy.array', 'array', (['data[0][0]'], {}), '(data[0][0])\n', (394, 406), False, 'from numpy import array\n'), ((425, 442), 'numpy.array', 'array', (['data[0][1]'], {}), '(data[0][1])\n', (430, 442), False, 'from numpy import array\n'), ((454, 471), 'numpy.array', 'array', (['data[0][2]'], {}), '(data[0][2])\n', (459, 471), False, 'from numpy import array\n'), ((491, 508), 'numpy.array', 'array', (['data[0][3]'], {}), '(data[0][3])\n', (496, 508), False, 'from numpy import array\n'), ((752, 763), 'numpy.array', 'array', (['seed'], {}), '(seed)\n', (757, 763), False, 'from numpy import array\n'), ((980, 994), 'numpy.array', 'array', (['indices'], {}), '(indices)\n', (985, 994), False, 'from numpy import array\n')]
#dependencies import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import VotingClassifier from sklearn.model_selection import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.ensemble import AdaBoostClassifier from sklearn.metrics import confusion_matrix from sklearn import svm from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import normalize import itertools import matplotlib.pyplot as plt import pandas as pd #function defination to plot the confusion matrix 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] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) 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 = '.2f' 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_data = pd.read_csv('criminal_train.csv') y_train = train_data['Criminal'] X_train = train_data.drop(['PERID','Criminal'],axis = 1).values X_train = normalize(X_train, axis = 0) test_data = pd.read_csv('criminal_test.csv') X_test = test_data.drop(['PERID'],axis = 1).values X_test = normalize(X_test, axis = 0) #model structure model = VotingClassifier( estimators=[ ( 'gb',GradientBoostingClassifier(n_estimators=500,verbose =1,max_depth = 6 )), ('rf', RandomForestClassifier(n_estimators=1000, verbose = 1))], voting='soft') model = AdaBoostClassifier(base_estimator= model, n_estimators =10 ) #training the model print('training the model: ') model.fit(X_train, y_train) print('model trained: ') model.score(X_train,y_train) X_train, X_test, y_train, y_test = train_test_split(X_train ,y_train, train_size = .9) model.fit(X_train, y_train) model.score(X_test, y_test) ##################################################### #predicting values on test file df = pd.read_csv('criminal_test.csv') predicted = model.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_old.csv', index = False) ############################################################### print(model.score(X_train, y_train)) # predicted value predicted_y = model.predict(X_train) #plot the confusion matrix cnf_matrix = confusion_matrix(y_train, predicted_y) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix plt.figure() plot_confusion_matrix(cnf_matrix, classes=[0,1], title='Confusion matrix, without normalization') # Plot normalized confusion matrix plt.figure() plot_confusion_matrix(cnf_matrix, classes=[0,1], normalize=True, title='Normalized confusion matrix') plt.show() ################################################3 #input file df = pd.read_csv('criminal_train.csv') # KNN classifier model_knn =KNeighborsClassifier(n_neighbors= 5, weights='distance', n_jobs = 4) model_knn.fit(X_train, y_train) model_knn.score(X_train,y_train) predicted = model_knn.predict(X_train) df = pd.read_csv('criminal_train.csv') frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_knn.csv', index = False) ## random forest classifier model_rf =RandomForestClassifier(n_estimators=1000, verbose = 1) model_rf.fit(X_train, y_train) df = pd.read_csv('criminal_train.csv') predicted = model_rf.predict(X_train) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_rf.csv', index = False) # ada boosting clssifier model_ab = AdaBoostClassifier(n_estimators=500) model_ab.fit(X_train, y_train) df = pd.read_csv('criminal_train.csv') X_test = df.drop(['PERID'],axis =1).values predicted = model_ab.predict(X_train) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_ab.csv', index = False) ### gradient boosting classifier model_gb = GradientBoostingClassifier(n_estimators=500,verbose =1,max_depth = 6 ) model_gb.fit(X_train, y_train) df = pd.read_csv('criminal_train.csv') X_test = df.drop(['PERID'],axis =1).values predicted = model_gb.predict(X_train) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_gb.csv', index = False) #logistic regression model_lr =LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=.3) model_lr.fit(X_train, y_train) predicted = model_lr.predict(X_train) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_lr.csv', index = False) ## support vector machines model_svm =svm.SVC(C=.75, verbose = True) model_svm.fit(X_train, y_train) predicted = model_svm.predict(X_train) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('input_svm.csv', index = False) ############################################## ### output file test_data = pd.read_csv('criminal_test.csv') X_test = test_data.drop(['PERID'],axis = 1).values X_test = normalize(X_test, axis = 0) # KNN classifier predicted = model_knn.predict(X_test) df = pd.read_csv('criminal_test.csv') frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_knn.csv', index = False) ## random forest classifier predicted = model_rf.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_rf.csv', index = False) # ada boosting clssifier predicted = model_ab.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_ab.csv', index = False) ### gradient boosting classifier predicted = model_gb.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_gb.csv', index = False) ### gradient logistic regression classifier predicted = model_lr.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_lr.csv', index = False) ## support vector machines predicted = model_svm.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output_svm.csv', index = False) #################################################### ### WRITING THE ACCURACY print('Knn score: ', model_knn.score(X_train, y_train)) print('gaussian nb score: ', model_gb.score(X_train, y_train)) print('ada boost score: ', model_ab.score(X_train, y_train)) print('random forest score: ', model_rf.score(X_train, y_train)) print('logistic regression: ',model_lr.score(X_train, y_train)) print('support vector machines:',model_svm.score(X_train, y_train)) ############################################################## df = pd.read_csv('criminal_test.csv') test_data = pd.read_csv('criminal_test.csv') X_test = test_data.drop(['PERID'],axis = 1).values X_test = normalize(X_test, axis = 0) predicted = model.predict(X_test) frame = pd.DataFrame() frame['PERID'] = df['PERID'] frame['Criminal'] = predicted frame.to_csv('output.csv', index = False)
[ "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.ensemble.AdaBoostClassifier", "sklearn.neighbors.KNeighborsClassifier", "matplotlib.pyplot.imshow", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks", "pandas.DataFrame", "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.xticks", ...
[((2018, 2051), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (2029, 2051), True, 'import pandas as pd\n'), ((2162, 2188), 'sklearn.preprocessing.normalize', 'normalize', (['X_train'], {'axis': '(0)'}), '(X_train, axis=0)\n', (2171, 2188), False, 'from sklearn.preprocessing import normalize\n'), ((2206, 2238), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (2217, 2238), True, 'import pandas as pd\n'), ((2301, 2326), 'sklearn.preprocessing.normalize', 'normalize', (['X_test'], {'axis': '(0)'}), '(X_test, axis=0)\n', (2310, 2326), False, 'from sklearn.preprocessing import normalize\n'), ((2609, 2666), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'base_estimator': 'model', 'n_estimators': '(10)'}), '(base_estimator=model, n_estimators=10)\n', (2627, 2666), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((2845, 2895), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X_train', 'y_train'], {'train_size': '(0.9)'}), '(X_train, y_train, train_size=0.9)\n', (2861, 2895), False, 'from sklearn.model_selection import train_test_split\n'), ((3049, 3081), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (3060, 3081), True, 'import pandas as pd\n'), ((3126, 3140), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3138, 3140), True, 'import pandas as pd\n'), ((3456, 3494), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_train', 'predicted_y'], {}), '(y_train, predicted_y)\n', (3472, 3494), False, 'from sklearn.metrics import confusion_matrix\n'), ((3496, 3528), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (3515, 3528), True, 'import numpy as np\n'), ((3572, 3584), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3582, 3584), True, 'import matplotlib.pyplot as plt\n'), ((3746, 3758), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3756, 3758), True, 'import matplotlib.pyplot as plt\n'), ((3888, 3898), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3896, 3898), True, 'import matplotlib.pyplot as plt\n'), ((3971, 4004), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (3982, 4004), True, 'import pandas as pd\n'), ((4038, 4103), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(5)', 'weights': '"""distance"""', 'n_jobs': '(4)'}), "(n_neighbors=5, weights='distance', n_jobs=4)\n", (4058, 4103), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((4220, 4253), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (4231, 4253), True, 'import pandas as pd\n'), ((4263, 4277), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4275, 4277), True, 'import pandas as pd\n'), ((4427, 4479), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(1000)', 'verbose': '(1)'}), '(n_estimators=1000, verbose=1)\n', (4449, 4479), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((4520, 4553), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (4531, 4553), True, 'import pandas as pd\n'), ((4602, 4616), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4614, 4616), True, 'import pandas as pd\n'), ((4765, 4801), 'sklearn.ensemble.AdaBoostClassifier', 'AdaBoostClassifier', ([], {'n_estimators': '(500)'}), '(n_estimators=500)\n', (4783, 4801), False, 'from sklearn.ensemble import AdaBoostClassifier\n'), ((4840, 4873), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (4851, 4873), True, 'import pandas as pd\n'), ((4968, 4982), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4980, 4982), True, 'import pandas as pd\n'), ((5137, 5205), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'n_estimators': '(500)', 'verbose': '(1)', 'max_depth': '(6)'}), '(n_estimators=500, verbose=1, max_depth=6)\n', (5163, 5205), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((5248, 5281), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_train.csv"""'], {}), "('criminal_train.csv')\n", (5259, 5281), True, 'import pandas as pd\n'), ((5376, 5390), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5388, 5390), True, 'import pandas as pd\n'), ((5533, 5596), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'penalty': '"""l2"""', 'dual': '(False)', 'tol': '(0.0001)', 'C': '(0.3)'}), "(penalty='l2', dual=False, tol=0.0001, C=0.3)\n", (5551, 5596), False, 'from sklearn.linear_model import LogisticRegression\n'), ((5676, 5690), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5688, 5690), True, 'import pandas as pd\n'), ((5840, 5869), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': '(0.75)', 'verbose': '(True)'}), '(C=0.75, verbose=True)\n', (5847, 5869), False, 'from sklearn import svm\n'), ((5953, 5967), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5965, 5967), True, 'import pandas as pd\n'), ((6159, 6191), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (6170, 6191), True, 'import pandas as pd\n'), ((6254, 6279), 'sklearn.preprocessing.normalize', 'normalize', (['X_test'], {'axis': '(0)'}), '(X_test, axis=0)\n', (6263, 6279), False, 'from sklearn.preprocessing import normalize\n'), ((6350, 6382), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (6361, 6382), True, 'import pandas as pd\n'), ((6392, 6406), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6404, 6406), True, 'import pandas as pd\n'), ((6593, 6607), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6605, 6607), True, 'import pandas as pd\n'), ((6792, 6806), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6804, 6806), True, 'import pandas as pd\n'), ((6997, 7011), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7009, 7011), True, 'import pandas as pd\n'), ((7215, 7229), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7227, 7229), True, 'import pandas as pd\n'), ((7415, 7429), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (7427, 7429), True, 'import pandas as pd\n'), ((8075, 8107), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (8086, 8107), True, 'import pandas as pd\n'), ((8121, 8153), 'pandas.read_csv', 'pd.read_csv', (['"""criminal_test.csv"""'], {}), "('criminal_test.csv')\n", (8132, 8153), True, 'import pandas as pd\n'), ((8216, 8241), 'sklearn.preprocessing.normalize', 'normalize', (['X_test'], {'axis': '(0)'}), '(X_test, axis=0)\n', (8225, 8241), False, 'from sklearn.preprocessing import normalize\n'), ((8290, 8304), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (8302, 8304), True, 'import pandas as pd\n'), ((1380, 1430), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cm'], {'interpolation': '"""nearest"""', 'cmap': 'cmap'}), "(cm, interpolation='nearest', cmap=cmap)\n", (1390, 1430), True, 'import matplotlib.pyplot as plt\n'), ((1436, 1452), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1445, 1452), True, 'import matplotlib.pyplot as plt\n'), ((1458, 1472), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1470, 1472), True, 'import matplotlib.pyplot as plt\n'), ((1520, 1564), 'matplotlib.pyplot.xticks', 'plt.xticks', (['tick_marks', 'classes'], {'rotation': '(45)'}), '(tick_marks, classes, rotation=45)\n', (1530, 1564), True, 'import matplotlib.pyplot as plt\n'), ((1570, 1601), 'matplotlib.pyplot.yticks', 'plt.yticks', (['tick_marks', 'classes'], {}), '(tick_marks, classes)\n', (1580, 1601), True, 'import matplotlib.pyplot as plt\n'), ((1916, 1934), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1932, 1934), True, 'import matplotlib.pyplot as plt\n'), ((1940, 1964), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True label"""'], {}), "('True label')\n", (1950, 1964), True, 'import matplotlib.pyplot as plt\n'), ((1970, 1999), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted label"""'], {}), "('Predicted label')\n", (1980, 1999), True, 'import matplotlib.pyplot as plt\n'), ((2420, 2488), 'sklearn.ensemble.GradientBoostingClassifier', 'GradientBoostingClassifier', ([], {'n_estimators': '(500)', 'verbose': '(1)', 'max_depth': '(6)'}), '(n_estimators=500, verbose=1, max_depth=6)\n', (2446, 2488), False, 'from sklearn.ensemble import GradientBoostingClassifier\n'), ((2518, 2570), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(1000)', 'verbose': '(1)'}), '(n_estimators=1000, verbose=1)\n', (2540, 2570), False, 'from sklearn.ensemble import RandomForestClassifier\n')]
# import torch import os import numpy import cv2 # def generate_triplets(bags): # triplets = [] for i in range(0, len(bags)): for j in range(i+1, len(bags)): if bags[i][1] == bags[j][1]: # compare labels # negbags = [] # for k in range(0, 6): # stop = False while not stop: q = numpy.random.randint(0, len(bags)) if bags[i][1] != bags[q][1]: stop = True # negbags.append(bags[q][0]) # usehardnegs = True if usehardnegs: triplets.append([ bags[i][0], bags[j][0], negbags ]) else: for negbag in negbags: triplets.append([ bags[i][0], bags[j][0], negbag ]) # return triplets # def extract_patches(img, keypoints, npix, size): # patches = [] for x, y, s, a in keypoints: # s = size*s/npix cos = numpy.cos(a*numpy.pi/180.0) sin = numpy.sin(a*numpy.pi/180.0) # M = numpy.matrix([ [+s*cos, -s*sin, (-s*cos+s*sin)*npix/2.0 + x], [+s*sin, +s*cos, (-s*sin-s*cos)*npix/2.0 + y] ]) # p = cv2.warpAffine(img, M, (npix, npix), flags=cv2.WARP_INVERSE_MAP+cv2.INTER_CUBIC+cv2.WARP_FILL_OUTLIERS) patches.append( torch.from_numpy(p).permute(2, 0, 1) ) # if len(patches) < 16: return None else: return torch.stack(patches) # def load_keypoint_bags(imgpaths, prob): # orb = cv2.ORB_create(nfeatures=512, patchSize=16) #surf = cv2.xfeatures2d.SURF_create(1024, 4, 2, True, False) # number of features detected per image varies drastically (in our experiments we used binary search over the hess parameter value to obtain the desired number of keypoints <- slow!) def get_keypoints(img): keypoints = [] keypoints.extend(orb.detect(img, None)) #keypoints.extend(surf.detect(img, None)) return [(kp.pt[0], kp.pt[1], kp.size, kp.angle) for kp in keypoints] # bags = [] for imgpath in imgpaths: if numpy.random.random()<=prob: # #print('* processing ' + imgpath.split('/')[-1]) img = cv2.imread(imgpath) keypoints = get_keypoints(img) patches = extract_patches(img, keypoints, 32, 1.5) # label = int(imgpath.split('/')[-1][7:12])//4 # if patches is not None: bags.append( [patches, label] ) # return bags def init(folder='datasets/ukbench'): # trn = [] vld = [] for root, dirnames, filenames in os.walk(folder): for filename in filenames: if filename.endswith('.jpg'): if int(filename[7:12])//4<300: vld.append(os.path.join(root, filename)) else: trn.append(os.path.join(root, filename)) # return (lambda: generate_triplets(load_keypoint_bags(trn, 0.33))), (lambda: generate_triplets(load_keypoint_bags(vld, 1.00))) # ''' a, b = init('ukbench') import time start = time.time() trn = a() print('* elapsed time: %f [s]' % (time.time()-start)) print(len(trn)) '''
[ "cv2.warpAffine", "numpy.random.random", "torch.stack", "os.path.join", "torch.from_numpy", "cv2.ORB_create", "numpy.cos", "numpy.sin", "numpy.matrix", "cv2.imread", "os.walk" ]
[((1350, 1393), 'cv2.ORB_create', 'cv2.ORB_create', ([], {'nfeatures': '(512)', 'patchSize': '(16)'}), '(nfeatures=512, patchSize=16)\n', (1364, 1393), False, 'import cv2\n'), ((2318, 2333), 'os.walk', 'os.walk', (['folder'], {}), '(folder)\n', (2325, 2333), False, 'import os\n'), ((856, 887), 'numpy.cos', 'numpy.cos', (['(a * numpy.pi / 180.0)'], {}), '(a * numpy.pi / 180.0)\n', (865, 887), False, 'import numpy\n'), ((892, 923), 'numpy.sin', 'numpy.sin', (['(a * numpy.pi / 180.0)'], {}), '(a * numpy.pi / 180.0)\n', (901, 923), False, 'import numpy\n'), ((930, 1070), 'numpy.matrix', 'numpy.matrix', (['[[+s * cos, -s * sin, (-s * cos + s * sin) * npix / 2.0 + x], [+s * sin, +s *\n cos, (-s * sin - s * cos) * npix / 2.0 + y]]'], {}), '([[+s * cos, -s * sin, (-s * cos + s * sin) * npix / 2.0 + x],\n [+s * sin, +s * cos, (-s * sin - s * cos) * npix / 2.0 + y]])\n', (942, 1070), False, 'import numpy\n'), ((1059, 1171), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'M', '(npix, npix)'], {'flags': '(cv2.WARP_INVERSE_MAP + cv2.INTER_CUBIC + cv2.WARP_FILL_OUTLIERS)'}), '(img, M, (npix, npix), flags=cv2.WARP_INVERSE_MAP + cv2.\n INTER_CUBIC + cv2.WARP_FILL_OUTLIERS)\n', (1073, 1171), False, 'import cv2\n'), ((1276, 1296), 'torch.stack', 'torch.stack', (['patches'], {}), '(patches)\n', (1287, 1296), False, 'import torch\n'), ((1883, 1904), 'numpy.random.random', 'numpy.random.random', ([], {}), '()\n', (1902, 1904), False, 'import numpy\n'), ((1978, 1997), 'cv2.imread', 'cv2.imread', (['imgpath'], {}), '(imgpath)\n', (1988, 1997), False, 'import cv2\n'), ((1181, 1200), 'torch.from_numpy', 'torch.from_numpy', (['p'], {}), '(p)\n', (1197, 1200), False, 'import torch\n'), ((2448, 2476), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (2460, 2476), False, 'import os\n'), ((2504, 2532), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (2516, 2532), False, 'import os\n')]
##### test 버전 만들 때 주의 사항 #### #### 1. test 시나리오 파일로 변경 #### 2. phase_txt 파일 만들기 위한 init 함수, step 함수 변경 import gym import shutil import uuid from gym import error, spaces, utils from gym.utils import seeding import sys import os import numpy as np from xml.etree.ElementTree import parse import collections import math from config import TRAIN_CONFIG print(TRAIN_CONFIG) sys.path.append(TRAIN_CONFIG['libsalt_dir']) import libsalt state_weight = 1 reward_weight = 1 addTime = 1 control_cycle = 3 IS_DOCKERIZE = True if IS_DOCKERIZE: import json import platform def getScenarioRelatedFilePath(args): abs_scenario_file_path = '{}/{}'.format(os.getcwd(), args.scenario_file_path) input_file_path = os.path.dirname(abs_scenario_file_path) if platform.system() == 'Windows': # one of { Windows, Linux , Darwin } dir_delimiter = "\\" else: dir_delimiter = "/" with open(abs_scenario_file_path, 'r') as json_file: json_data = json.load(json_file) node_file = json_data["scenario"]["input"]["node"] edge_file = json_data["scenario"]["input"]["link"] tss_file = json_data["scenario"]["input"]["trafficLightSystem"] node_file_path = input_file_path + dir_delimiter + node_file edge_file_path = input_file_path + dir_delimiter + edge_file tss_file_path = input_file_path + dir_delimiter + tss_file return abs_scenario_file_path, node_file_path, edge_file_path, tss_file_path def getScenarioRelatedBeginEndTime(scenario_file_path): abs_scenario_file_path = '{}/{}'.format(os.getcwd(), scenario_file_path) with open(abs_scenario_file_path, 'r') as json_file: json_data = json.load(json_file) begin_time = json_data["scenario"]["time"]["begin"] end_time = json_data["scenario"]["time"]["end"] return begin_time, end_time def H(s): probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()] e_x = [-p_x*math.log(p_x,2) for p_x in probabilities] return sum(e_x) class SALT_doan_multi_PSA(gym.Env): metadata = {'render.modes': ['human']} def __init__(self, args): self.state_weight = state_weight self.reward_weight = reward_weight self.addTime = addTime self.reward_func = args.reward_func self.actionT = args.action_t self.logprint = args.logprint if IS_DOCKERIZE: scenario_begin, scenario_end = getScenarioRelatedBeginEndTime(args.scenario_file_path) # self.startStep = args.trainStartTime if args.trainStartTime > scenario_begin else scenario_begin # self.endStep = args.trainEndTime if args.trainEndTime < scenario_end else scenario_end self.startStep = args.start_time if args.start_time > scenario_begin else scenario_begin self.endStep = args.end_time if args.end_time < scenario_end else scenario_end else: self.startStep = args.trainStartTime self.endStep = args.trainEndTime self.dir_path = os.path.dirname(os.path.realpath(__file__)) self.uid = str(uuid.uuid4()) if IS_DOCKERIZE: abs_scenario_file_path = '{}/{}'.format(os.getcwd(), args.scenario_file_path) self.src_dir = os.path.dirname(abs_scenario_file_path) self.dest_dir = os.path.split(self.src_dir)[0] self.dest_dir = '{}/data/{}/'.format(self.dest_dir, self.uid) os.makedirs(self.dest_dir, exist_ok=True) else: self.src_dir = os.getcwd() + "/data/envs/salt/doan" self.dest_dir = os.getcwd() + "/data/envs/salt/data/" + self.uid + "/" os.mkdir(self.dest_dir) src_files = os.listdir(self.src_dir) for file_name in src_files: full_file_name = os.path.join(self.src_dir, file_name) if os.path.isfile(full_file_name): shutil.copy(full_file_name, self.dest_dir) if IS_DOCKERIZE: scenario_file_name = args.scenario_file_path.split('/')[-1] self.salt_scenario = "{}/{}".format(self.dest_dir, scenario_file_name) if 0: _, _, edge_file_path, tss_file_path = getScenarioRelatedFilePath(args) else: edge_file_path = "magic/doan_20210401.edg.xml" tss_file_path = "magic/doan(without dan).tss.xml" tree = parse(tss_file_path) else: # self.salt_scenario = self.dest_dir + 'doan_2021_actionT{}.scenario.json'.format(self.actionT) self.salt_scenario = self.dest_dir + 'doan_2021.scenario.json' tree = parse(os.getcwd() + '/data/envs/salt/doan/doan(without dan).tss.xml') root = tree.getroot() trafficSignal = root.findall("trafficSignal") self.target_tl_obj = {} self.phase_numbers = [] i=0 if IS_DOCKERIZE: self.targetList_input = args.target_TL.split(',') else: self.targetList_input = args.targetTL.split(',') self.targetList_input2 = [] for tl_i in self.targetList_input: self.targetList_input2.append(tl_i) ## ex. SA 101 self.targetList_input2.append(tl_i.split(" ")[1]) ## ex.101 self.targetList_input2.append(tl_i.replace(" ", "")) ## ex. SA101 for x in trafficSignal: if x.attrib['signalGroup'] in self.targetList_input2: self.target_tl_obj[x.attrib['nodeID']] = {} self.target_tl_obj[x.attrib['nodeID']]['crossName'] = x.attrib['crossName'] self.target_tl_obj[x.attrib['nodeID']]['signalGroup'] = x.attrib['signalGroup'] self.target_tl_obj[x.attrib['nodeID']]['offset'] = int(x.find('schedule').attrib['offset']) self.target_tl_obj[x.attrib['nodeID']]['minDur'] = [int(y.attrib['minDur']) if 'minDur' in y.attrib else int(y.attrib['duration']) for y in x.findall("schedule/phase")] self.target_tl_obj[x.attrib['nodeID']]['maxDur'] = [int(y.attrib['maxDur']) if 'maxDur' in y.attrib else int(y.attrib['duration']) for y in x.findall("schedule/phase")] self.target_tl_obj[x.attrib['nodeID']]['cycle'] = np.sum([int(y.attrib['duration']) for y in x.findall("schedule/phase")]) self.target_tl_obj[x.attrib['nodeID']]['duration'] = [int(y.attrib['duration']) for y in x.findall("schedule/phase")] tmp_duration_list = np.array([int(y.attrib['duration']) for y in x.findall("schedule/phase")]) # self.target_tl_obj[x.attrib['nodeID']]['green_idx'] = np.where(tmp_duration_list > 5) self.target_tl_obj[x.attrib['nodeID']]['green_idx'] = np.where(np.array(self.target_tl_obj[x.attrib['nodeID']]['minDur'])!=np.array(self.target_tl_obj[x.attrib['nodeID']]['maxDur'])) # print(self.target_tl_obj[x.attrib['nodeID']]['green_idx']) self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'] = np.where(tmp_duration_list==np.max(tmp_duration_list)) self.target_tl_obj[x.attrib['nodeID']]['sub_green_idx'] = list(set(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]) - set(np.where(tmp_duration_list==np.max(tmp_duration_list))[0])) self.target_tl_obj[x.attrib['nodeID']]['tl_idx'] = i self.target_tl_obj[x.attrib['nodeID']]['remain'] = self.target_tl_obj[x.attrib['nodeID']]['cycle'] - np.sum(self.target_tl_obj[x.attrib['nodeID']]['minDur']) #print(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]), self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0]) self.target_tl_obj[x.attrib['nodeID']]['max_phase'] = np.where(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0]) # self.target_tl_obj[x.attrib['nodeID']]['action_list'] = getActionList(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]), self.target_tl_obj[x.attrib['nodeID']]['max_phase'][0][0]) # # self.target_tl_obj[x.attrib['nodeID']]['action_space'] = ((len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0])-1)*2) + 1 # self.target_tl_obj[x.attrib['nodeID']]['action_space'] = len(self.target_tl_obj[x.attrib['nodeID']]['action_list']) self.target_tl_obj[x.attrib['nodeID']]['action_space'] = len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]) self.phase_numbers.append(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0])) i+=1 self.max_phase_length = int(np.max(self.phase_numbers)) self.target_tl_id_list = list(self.target_tl_obj.keys()) self.agent_num = len(self.target_tl_id_list) self.action_mask = np.zeros(self.agent_num) self.control_cycle = control_cycle print('target tl obj {}'.format(self.target_tl_obj)) print('target tl id list {}'.format(self.target_tl_id_list)) print('number of target tl {}'.format(len(self.target_tl_id_list))) if IS_DOCKERIZE: tree = parse(edge_file_path) else: tree = parse(os.getcwd() + '/data/envs/salt/doan/doan_20210401.edg.xml') root = tree.getroot() edge = root.findall("edge") self.near_tl_obj = {} for i in self.target_tl_id_list: self.near_tl_obj[i] = {} self.near_tl_obj[i]['in_edge_list'] = [] self.near_tl_obj[i]['in_edge_list_0'] = [] self.near_tl_obj[i]['in_edge_list_1'] = [] # self.near_tl_obj[i]['near_length_list'] = [] for x in edge: if x.attrib['to'] in self.target_tl_id_list: self.near_tl_obj[x.attrib['to']]['in_edge_list'].append(x.attrib['id']) self.near_tl_obj[x.attrib['to']]['in_edge_list_0'].append(x.attrib['id']) _edge_len = [] for n in self.near_tl_obj: _tmp_in_edge_list = self.near_tl_obj[n]['in_edge_list'] _tmp_near_juction_list = [] for x in edge: if x.attrib['id'] in _tmp_in_edge_list: _tmp_near_juction_list.append(x.attrib['from']) for x in edge: if x.attrib['to'] in _tmp_near_juction_list: self.near_tl_obj[n]['in_edge_list'].append(x.attrib['id']) self.near_tl_obj[n]['in_edge_list_1'].append(x.attrib['id']) self.target_tl_obj[n]['in_edge_list'] = self.near_tl_obj[n]['in_edge_list'] self.target_tl_obj[n]['in_edge_list_0'] = self.near_tl_obj[n]['in_edge_list_0'] self.target_tl_obj[n]['in_edge_list_1'] = self.near_tl_obj[n]['in_edge_list_1'] _edge_len.append(len(self.near_tl_obj[n]['in_edge_list'])) self.max_edge_length = int(np.max(_edge_len)) print(self.target_tl_obj) print(self.max_edge_length) self.done = False libsalt.start(self.salt_scenario) libsalt.setCurrentStep(self.startStep) print("init", [libsalt.trafficsignal.getTLSConnectedLinkID(x) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(x) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID(x) for x in self.target_tl_id_list]) print("init", [len(libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(x).myPhaseVector) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(x).myPhaseVector[0][1] for x in self.target_tl_id_list]) _lane_len = [] for target in self.target_tl_obj: _lane_list = [] _lane_list_0 = [] for edge in self.target_tl_obj[target]['in_edge_list_0']: for lane in range(libsalt.link.getNumLane(edge)): _lane_id = "{}_{}".format(edge, lane) _lane_list.append(_lane_id) _lane_list_0.append((_lane_id)) # print(_lane_id, libsalt.lane.getLength(_lane_id)) self.target_tl_obj[target]['in_lane_list_0'] = _lane_list_0 _lane_list_1 = [] for edge in self.target_tl_obj[target]['in_edge_list_1']: for lane in range(libsalt.link.getNumLane(edge)): _lane_id = "{}_{}".format(edge, lane) _lane_list.append(_lane_id) _lane_list_1.append((_lane_id)) # print(_lane_id, libsalt.lane.getLength(_lane_id)) self.target_tl_obj[target]['in_lane_list_1'] = _lane_list_1 self.target_tl_obj[target]['in_lane_list'] = _lane_list self.target_tl_obj[target]['state_space'] = len(_lane_list) + 1 _lane_len.append(len(_lane_list)) self.max_lane_length = np.max(_lane_len) print(self.target_tl_obj) print(np.max(_lane_len)) self._observation = [] # for i in range(len(self.min_green)): # self._observation = np.append(self._observation, self.get_state(self.ts_ids[0])) self._observation = np.append(self._observation, self.get_state(self.target_tl_id_list[0])) self.obs_len = len(self._observation) self.observations = [] self.lane_passed = [] for target in self.target_tl_obj: self.observations.append([0]*self.target_tl_obj[target]['state_space']) self.lane_passed.append([]) # print("self.lane_passed", self.lane_passed) # print(observations) self.rewards = np.zeros(self.agent_num) self.before_action = np.zeros(self.agent_num) libsalt.close() # print('{} traci closed\n'.format(self.uid)) self.simulationSteps = 0 def step(self, actions): self.done = False # print('step') currentStep = libsalt.getCurrentStep() self.simulationSteps = currentStep ### change to yellow or keep current green phase for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] scheduleID = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(tlid) phase_length = len(self.target_tl_obj[tlid]['duration']) green_idx = self.target_tl_obj[tlid]['green_idx'][0] action_phase = green_idx[int(self.before_action[i])] yPhase = (action_phase + 1) % phase_length if self.target_tl_obj[tlid]['duration'][yPhase] > 5: yPhase = (action_phase + 2) % phase_length # print("tl_name {} before action {} current action {}".format(self.target_tl_obj[tlid]['crossName'], self.before_action[i], actions[i])) if self.before_action[i] == actions[i]: libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(action_phase)) else: libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(yPhase)) # currentPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) # if self.target_tl_obj[tlid]['crossName'] == '진터네거리': # print("step {} tl_name {} before_actions {} action_phase {} getCurrPhaseYellow {} rewards {}".format( # self.simulationSteps, self.target_tl_obj[tlid]['crossName'], self.before_action[i], action_phase, # currentPhase, np.round(self.rewards[i], 2))) for i in range(3): libsalt.simulationStep() currentStep = libsalt.getCurrentStep() self.simulationSteps = currentStep setPhaseStep = currentStep action_phase_list = [] current_phase_list = [] for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] scheduleID = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(tlid) # currentPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) green_idx = self.target_tl_obj[tlid]['green_idx'][0] action_phase = green_idx[actions[i]] action_phase_list = np.append(action_phase_list, int(action_phase)) libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(action_phase)) currPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) current_phase_list = np.append(current_phase_list, currPhase) self.observations[i] = self.get_state(tlid) # self.lane_passed[i] = [] for i in range(self.actionT): libsalt.simulationStep() self.simulationSteps = libsalt.getCurrentStep() for i in range(len(self.target_tl_id_list)): link_list_0 = self.target_tl_obj[self.target_tl_id_list[i]]['in_edge_list_0'] lane_list_0 = self.target_tl_obj[self.target_tl_id_list[i]]['in_lane_list_0'] link_list_1 = self.target_tl_obj[self.target_tl_id_list[i]]['in_edge_list_1'] lane_list_1 = self.target_tl_obj[self.target_tl_id_list[i]]['in_lane_list_1'] if self.reward_func=='pn': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getSumPassed(l)) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getSumPassed(l) * reward_weight) self.rewards[i] = np.sum(self.lane_passed[i]) if self.reward_func=='wt': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_max': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT * reward_weight) self.rewards[i] = -np.max(self.lane_passed[i]) if self.reward_func=='wq': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingQLength(l)) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingQLength(l) * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_SBV': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_SBV_max': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.max(self.lane_passed[i]) if self.reward_func=='wt_ABV': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentAverageWaitingTimeBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentAverageWaitingTimeBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) self.lane_passed[i] = [] self.simulationSteps = libsalt.getCurrentStep() if self.logprint: for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] print("step {} tl_name {} actions {} action_phase {} getCurrPhaseGreen {} reward {}".format( setPhaseStep, self.target_tl_obj[tlid]['crossName'], np.round(actions[i], 3), action_phase_list[i], current_phase_list[i], np.round(self.rewards[i], 2))) if self.simulationSteps > self.endStep: self.done = True print("self.done step {}".format(self.simulationSteps)) libsalt.close() info = {} # print(self.before_action, actions) self.before_action = actions.copy() return self.observations, self.rewards, self.done, info def reset(self): libsalt.start(self.salt_scenario) libsalt.setCurrentStep(self.startStep) self.simulationSteps = libsalt.getCurrentStep() observations = [] self.lane_passed = [] for target in self.target_tl_obj: print(target, self.get_state(target)) observations.append(self.get_state(target)) self.lane_passed.append([]) # # print("reset", observations) # print(observations.shape) return observations def get_state(self, tsid): densityMatrix = [] passedMatrix = [] tlMatrix = [] link_list = self.target_tl_obj[tsid]['in_lane_list'] link_list_0 = self.target_tl_obj[tsid]['in_lane_list_0'] link_list_1 = self.target_tl_obj[tsid]['in_lane_list_1'] # tl_s = libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(tsid).myPhaseVector[0][1] #print("tl_s {}".format(tl_s)) for link in link_list_0: densityMatrix = np.append(densityMatrix, libsalt.lane.getAverageDensity(link)) # passedMatrix = np.append(passedMatrix, libsalt.lane.getNumVehPassed(link)) for link in link_list_1: densityMatrix = np.append(densityMatrix, libsalt.lane.getAverageDensity(link) * self.state_weight) # passedMatrix = np.append(passedMatrix, libsalt.lane.getNumVehPassed(link) * self.state_weight) tlMatrix = np.append(tlMatrix, libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tsid)) #print(lightMatrix) # obs = np.append(densityMatrix, passedMatrix) obs = np.append(densityMatrix, tlMatrix) # print(densityMatrix) # print(passedMatrix) return obs def render(self, mode='human'): pass # print(self.reward) def close(self): libsalt.close() print('close') ### state -> link to lane 1-hop, passedNum, density(fundamental diagram) ### action -> add or sub to sub phase from max phase with changed phase(every 5 cycle) ### reward -> lane waitingQLength, penalty if phase_sum is not equal to cycle ### reward -> get each 10 step and sum class SALT_doan_multi_PSA_test(gym.Env): metadata = {'render.modes': ['human']} def __init__(self, args): self.state_weight = state_weight self.reward_weight = reward_weight self.addTime = addTime self.reward_func = args.reward_func self.actionT = args.action_t if IS_DOCKERIZE: scenario_begin, scenario_end = getScenarioRelatedBeginEndTime(args.scenario_file_path) # self.startStep = args.testStartTime if args.testStartTime > scenario_begin else scenario_begin # self.endStep = args.testEndTime if args.testEndTime < scenario_end else scenario_end self.startStep = args.start_time if args.start_time > scenario_begin else scenario_begin self.endStep = args.end_time if args.end_time < scenario_end else scenario_end self.args = args else: self.startStep = args.testStartTime self.endStep = args.testEndTime self.args = args self.dir_path = os.path.dirname(os.path.realpath(__file__)) self.uid = str(uuid.uuid4()) if IS_DOCKERIZE: abs_scenario_file_path = '{}/{}'.format(os.getcwd(), self.args.scenario_file_path) self.src_dir = os.path.dirname(abs_scenario_file_path) self.dest_dir = os.path.split(self.src_dir)[0] self.dest_dir = '{}/data/{}/'.format(self.dest_dir, self.uid) os.makedirs(self.dest_dir, exist_ok=True) else: self.src_dir = os.getcwd() + "/data/envs/salt/doan" self.dest_dir = os.getcwd() + "/data/envs/salt/data/" + self.uid + "/" os.mkdir(self.dest_dir) src_files = os.listdir(self.src_dir) for file_name in src_files: full_file_name = os.path.join(self.src_dir, file_name) if os.path.isfile(full_file_name): shutil.copy(full_file_name, self.dest_dir) if IS_DOCKERIZE: scenario_file_name = self.args.scenario_file_path.split('/')[-1] self.salt_scenario = "{}/{}".format(self.dest_dir, scenario_file_name) if 0: _, _, edge_file_path, tss_file_path = getScenarioRelatedFilePath(args) else: edge_file_path = "magic/doan_20210401.edg.xml" tss_file_path = "magic/doan(without dan).tss.xml" tree = parse(tss_file_path) else: self.salt_scenario = self.dest_dir + 'doan_2021_test.scenario.json' tree = parse(os.getcwd() + '/data/envs/salt/doan/doan(without dan).tss.xml') root = tree.getroot() trafficSignal = root.findall("trafficSignal") self.target_tl_obj = {} self.phase_numbers = [] i=0 if IS_DOCKERIZE: self.targetList_input = args.target_TL.split(',') else: self.targetList_input = args.targetTL.split(',') self.targetList_input2 = [] for tl_i in self.targetList_input: self.targetList_input2.append(tl_i) ## ex. SA 101 self.targetList_input2.append(tl_i.split(" ")[1]) ## ex.101 self.targetList_input2.append(tl_i.replace(" ", "")) ## ex. SA101 for x in trafficSignal: if x.attrib['signalGroup'] in self.targetList_input2: self.target_tl_obj[x.attrib['nodeID']] = {} self.target_tl_obj[x.attrib['nodeID']]['crossName'] = x.attrib['crossName'] self.target_tl_obj[x.attrib['nodeID']]['signalGroup'] = x.attrib['signalGroup'] self.target_tl_obj[x.attrib['nodeID']]['offset'] = int(x.find('schedule').attrib['offset']) self.target_tl_obj[x.attrib['nodeID']]['minDur'] = [int(y.attrib['minDur']) if 'minDur' in y.attrib else int(y.attrib['duration']) for y in x.findall("schedule/phase")] self.target_tl_obj[x.attrib['nodeID']]['maxDur'] = [int(y.attrib['maxDur']) if 'maxDur' in y.attrib else int(y.attrib['duration']) for y in x.findall("schedule/phase")] self.target_tl_obj[x.attrib['nodeID']]['cycle'] = np.sum([int(y.attrib['duration']) for y in x.findall("schedule/phase")]) self.target_tl_obj[x.attrib['nodeID']]['duration'] = [int(y.attrib['duration']) for y in x.findall("schedule/phase")] tmp_duration_list = np.array([int(y.attrib['duration']) for y in x.findall("schedule/phase")]) # self.target_tl_obj[x.attrib['nodeID']]['green_idx'] = np.where(tmp_duration_list > 5) self.target_tl_obj[x.attrib['nodeID']]['green_idx'] = np.where(np.array(self.target_tl_obj[x.attrib['nodeID']]['minDur'])!=np.array(self.target_tl_obj[x.attrib['nodeID']]['maxDur'])) # print(self.target_tl_obj[x.attrib['nodeID']]['green_idx']) self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'] = np.where(tmp_duration_list==np.max(tmp_duration_list)) self.target_tl_obj[x.attrib['nodeID']]['sub_green_idx'] = list(set(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]) - set(np.where(tmp_duration_list==np.max(tmp_duration_list))[0])) self.target_tl_obj[x.attrib['nodeID']]['tl_idx'] = i self.target_tl_obj[x.attrib['nodeID']]['remain'] = self.target_tl_obj[x.attrib['nodeID']]['cycle'] - np.sum(self.target_tl_obj[x.attrib['nodeID']]['minDur']) #print(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]), self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0]) self.target_tl_obj[x.attrib['nodeID']]['max_phase'] = np.where(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0]) # self.target_tl_obj[x.attrib['nodeID']]['action_list'] = getActionList(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]), self.target_tl_obj[x.attrib['nodeID']]['max_phase'][0][0]) # # self.target_tl_obj[x.attrib['nodeID']]['action_space'] = ((len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0])-1)*2) + 1 # self.target_tl_obj[x.attrib['nodeID']]['action_space'] = len(self.target_tl_obj[x.attrib['nodeID']]['action_list']) self.target_tl_obj[x.attrib['nodeID']]['action_space'] = len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0]) self.phase_numbers.append(len(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0])) i+=1 self.max_phase_length = int(np.max(self.phase_numbers)) self.target_tl_id_list = list(self.target_tl_obj.keys()) self.agent_num = len(self.target_tl_id_list) self.action_mask = np.zeros(self.agent_num) self.control_cycle = control_cycle print('target tl obj {}'.format(self.target_tl_obj)) print('target tl id list {}'.format(self.target_tl_id_list)) print('number of target tl {}'.format(len(self.target_tl_id_list))) if IS_DOCKERIZE: tree = parse(edge_file_path) else: tree = parse(os.getcwd() + '/data/envs/salt/doan/doan_20210401.edg.xml') root = tree.getroot() edge = root.findall("edge") self.near_tl_obj = {} if IS_DOCKERIZE: if self.args.mode=='test': self.fn_rl_phase_reward_output = "{}/output/test/rl_phase_reward_output.txt".format(args.io_home) f = open(self.fn_rl_phase_reward_output, mode='w+', buffering=-1, encoding='utf-8', errors=None, newline=None, closefd=True, opener=None) f.write('step,tl_name,actions,phase,reward\n') f.close() else: if self.args.mode=='test': f = open("output/test/rl_phase_reward_output.txt", mode='w+', buffering=-1, encoding='utf-8', errors=None, newline=None, closefd=True, opener=None) f.write('step,tl_name,actions,phase,reward\n') f.close() for i in self.target_tl_id_list: self.near_tl_obj[i] = {} self.near_tl_obj[i]['in_edge_list'] = [] self.near_tl_obj[i]['in_edge_list_0'] = [] self.near_tl_obj[i]['in_edge_list_1'] = [] # self.near_tl_obj[i]['near_length_list'] = [] for x in edge: if x.attrib['to'] in self.target_tl_id_list: self.near_tl_obj[x.attrib['to']]['in_edge_list'].append(x.attrib['id']) self.near_tl_obj[x.attrib['to']]['in_edge_list_0'].append(x.attrib['id']) _edge_len = [] for n in self.near_tl_obj: _tmp_in_edge_list = self.near_tl_obj[n]['in_edge_list'] _tmp_near_juction_list = [] for x in edge: if x.attrib['id'] in _tmp_in_edge_list: _tmp_near_juction_list.append(x.attrib['from']) for x in edge: if x.attrib['to'] in _tmp_near_juction_list: self.near_tl_obj[n]['in_edge_list'].append(x.attrib['id']) self.near_tl_obj[n]['in_edge_list_1'].append(x.attrib['id']) self.target_tl_obj[n]['in_edge_list'] = self.near_tl_obj[n]['in_edge_list'] self.target_tl_obj[n]['in_edge_list_0'] = self.near_tl_obj[n]['in_edge_list_0'] self.target_tl_obj[n]['in_edge_list_1'] = self.near_tl_obj[n]['in_edge_list_1'] _edge_len.append(len(self.near_tl_obj[n]['in_edge_list'])) self.max_edge_length = int(np.max(_edge_len)) print(self.target_tl_obj) print(self.max_edge_length) self.done = False libsalt.start(self.salt_scenario) libsalt.setCurrentStep(self.startStep) print("init", [libsalt.trafficsignal.getTLSConnectedLinkID(x) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(x) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID(x) for x in self.target_tl_id_list]) print("init", [len(libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(x).myPhaseVector) for x in self.target_tl_id_list]) print("init", [libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(x).myPhaseVector[0][1] for x in self.target_tl_id_list]) _lane_len = [] for target in self.target_tl_obj: _lane_list = [] _lane_list_0 = [] for edge in self.target_tl_obj[target]['in_edge_list_0']: for lane in range(libsalt.link.getNumLane(edge)): _lane_id = "{}_{}".format(edge, lane) _lane_list.append(_lane_id) _lane_list_0.append((_lane_id)) # print(_lane_id, libsalt.lane.getLength(_lane_id)) self.target_tl_obj[target]['in_lane_list_0'] = _lane_list_0 _lane_list_1 = [] for edge in self.target_tl_obj[target]['in_edge_list_1']: for lane in range(libsalt.link.getNumLane(edge)): _lane_id = "{}_{}".format(edge, lane) _lane_list.append(_lane_id) _lane_list_1.append((_lane_id)) # print(_lane_id, libsalt.lane.getLength(_lane_id)) self.target_tl_obj[target]['in_lane_list_1'] = _lane_list_1 self.target_tl_obj[target]['in_lane_list'] = _lane_list self.target_tl_obj[target]['state_space'] = len(_lane_list) + 1 _lane_len.append(len(_lane_list)) self.max_lane_length = np.max(_lane_len) print(self.target_tl_obj) print(np.max(_lane_len)) self._observation = [] # for i in range(len(self.min_green)): # self._observation = np.append(self._observation, self.get_state(self.ts_ids[0])) self._observation = np.append(self._observation, self.get_state(self.target_tl_id_list[0])) self.obs_len = len(self._observation) self.observations = [] self.lane_passed = [] for target in self.target_tl_obj: self.observations.append([0]*self.target_tl_obj[target]['state_space']) self.lane_passed.append([]) print("self.lane_passed", self.lane_passed) # print(observations) self.rewards = np.zeros(self.agent_num) self.before_action = np.zeros(self.agent_num) libsalt.close() print('{} traci closed\n'.format(self.uid)) self.simulationSteps = 0 def step(self, actions): self.done = False # print('step') currentStep = libsalt.getCurrentStep() self.simulationSteps = currentStep ### change to yellow or keep current green phase for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] scheduleID = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(tlid) phase_length = len(self.target_tl_obj[tlid]['duration']) green_idx = self.target_tl_obj[tlid]['green_idx'][0] action_phase = green_idx[int(self.before_action[i])] yPhase = (action_phase + 1) % phase_length if self.target_tl_obj[tlid]['duration'][yPhase] > 5: yPhase = (action_phase + 2) % phase_length # print("tl_name {} before action {} current action {}".format(self.target_tl_obj[tlid]['crossName'], self.before_action[i], actions[i])) if self.before_action[i] == actions[i]: libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(action_phase)) else: libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(yPhase)) # currentPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) # if self.target_tl_obj[tlid]['crossName'] == '진터네거리': # print("step {} tl_name {} before_actions {} action_phase {} getCurrPhaseYellow {} rewards {}".format( # self.simulationSteps, self.target_tl_obj[tlid]['crossName'], self.before_action[i], action_phase, # currentPhase, np.round(self.rewards[i], 2))) for i in range(3): libsalt.simulationStep() currentStep = libsalt.getCurrentStep() self.simulationSteps = currentStep setPhaseStep = currentStep action_phase_list = [] current_phase_list = [] for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] scheduleID = libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID(tlid) # currentPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) green_idx = self.target_tl_obj[tlid]['green_idx'][0] action_phase = green_idx[actions[i]] action_phase_list = np.append(action_phase_list, int(action_phase)) libsalt.trafficsignal.changeTLSPhase(currentStep, tlid, scheduleID, int(action_phase)) currPhase = libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tlid) current_phase_list = np.append(current_phase_list, currPhase) self.observations[i] = self.get_state(tlid) # self.lane_passed[i] = [] for i in range(self.actionT): libsalt.simulationStep() self.simulationSteps = libsalt.getCurrentStep() for i in range(len(self.target_tl_id_list)): link_list_0 = self.target_tl_obj[self.target_tl_id_list[i]]['in_edge_list_0'] link_list_1 = self.target_tl_obj[self.target_tl_id_list[i]]['in_edge_list_1'] if self.reward_func=='pn': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getSumPassed(l)) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getSumPassed(l) * reward_weight) self.rewards[i] = np.sum(self.lane_passed[i]) if self.reward_func=='wt': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_max': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingTime(l)/self.actionT * reward_weight) self.rewards[i] = -np.max(self.lane_passed[i]) if self.reward_func=='wq': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingQLength(l)) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getAverageWaitingQLength(l) * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_SBV': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) if self.reward_func=='wt_SBV_max': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentWaitingTimeSumBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.max(self.lane_passed[i]) if self.reward_func=='wt_ABV': for l in link_list_0: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentAverageWaitingTimeBaseVehicle(l, self.simulationSteps)/1000) for l in link_list_1: self.lane_passed[i] = np.append(self.lane_passed[i], libsalt.link.getCurrentAverageWaitingTimeBaseVehicle(l, self.simulationSteps)/1000 * reward_weight) self.rewards[i] = -np.sum(self.lane_passed[i]) self.lane_passed[i] = [] self.simulationSteps = libsalt.getCurrentStep() if IS_DOCKERIZE: if self.args.mode=='test': f = open(self.fn_rl_phase_reward_output, mode='a+', buffering=-1, encoding='utf-8', errors=None, newline=None, closefd=True, opener=None) for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] f.write("{},{},{},{},{}\n".format(setPhaseStep, self.target_tl_obj[tlid]['crossName'], actions[i], action_phase_list[i], np.round(self.rewards[i], 2))) print("step {} tl_name {} action {} phase {} reward {}\n".format(setPhaseStep, self.target_tl_obj[tlid]['crossName'], actions[i], action_phase_list[i], np.round(self.rewards[i], 2))) f.close() else: if self.args.mode=='test': f = open("output/test/rl_phase_reward_output.txt", mode='a+', buffering=-1, encoding='utf-8', errors=None, newline=None, closefd=True, opener=None) for i in range(len(self.target_tl_id_list)): tlid = self.target_tl_id_list[i] f.write("{},{},{},{},{}\n".format(setPhaseStep, self.target_tl_obj[tlid]['crossName'], actions[i], action_phase_list[i], np.round(self.rewards[i], 2))) print("step {} tl_name {} action {} phase {} reward {}\n".format(setPhaseStep, self.target_tl_obj[tlid]['crossName'], actions[i], action_phase_list[i], np.round(self.rewards[i], 2))) f.close() if self.simulationSteps > self.endStep: self.done = True print("self.done step {}".format(self.simulationSteps)) libsalt.close() info = {} # print(self.before_action, actions) self.before_action = actions.copy() return self.observations, self.rewards, self.done, info def reset(self): self.uid = str(uuid.uuid4()) if IS_DOCKERIZE: self.dest_dir = os.path.split(self.src_dir)[0] self.dest_dir = '{}/data/{}/'.format(self.dest_dir, self.uid) os.makedirs(self.dest_dir, exist_ok=True) else: self.dest_dir = os.getcwd() + "/data/envs/salt/data/" + self.uid + "/" os.mkdir(self.dest_dir) src_files = os.listdir(self.src_dir) for file_name in src_files: full_file_name = os.path.join(self.src_dir, file_name) if os.path.isfile(full_file_name): shutil.copy(full_file_name, self.dest_dir) if IS_DOCKERIZE: scenario_file_name = self.args.scenario_file_path.split('/')[-1] self.salt_scenario = "{}/{}".format(self.dest_dir, scenario_file_name) else: self.salt_scenario = self.dest_dir + 'doan_2021_test.scenario.json' libsalt.start(self.salt_scenario) libsalt.setCurrentStep(self.startStep) self.simulationSteps = libsalt.getCurrentStep() observations = [] self.lane_passed = [] for target in self.target_tl_obj: print(target, self.get_state(target)) observations.append(self.get_state(target)) self.lane_passed.append([]) # # print("reset", observations) # print(observations.shape) return observations def get_state(self, tsid): # densityMatrix = np.zeros(self.max_lane_length) # passedMatrix = np.zeros(self.max_lane_length) # vnumsMatrix = np.zeros(self.max_lane_length) densityMatrix = [] passedMatrix = [] tlMatrix = [] link_list = self.target_tl_obj[tsid]['in_lane_list'] link_list_0 = self.target_tl_obj[tsid]['in_lane_list_0'] link_list_1 = self.target_tl_obj[tsid]['in_lane_list_1'] # tl_s = libsalt.trafficsignal.getCurrentTLSScheduleByNodeID(tsid).myPhaseVector[0][1] #print("tl_s {}".format(tl_s)) for link in link_list_0: densityMatrix = np.append(densityMatrix, libsalt.lane.getAverageDensity(link)) # passedMatrix = np.append(passedMatrix, libsalt.lane.getNumVehPassed(link)) for link in link_list_1: densityMatrix = np.append(densityMatrix, libsalt.lane.getAverageDensity(link) * self.state_weight) # passedMatrix = np.append(passedMatrix, libsalt.lane.getNumVehPassed(link) * self.state_weight) tlMatrix = np.append(tlMatrix, libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID(tsid)) #print(lightMatrix) # obs = np.append(densityMatrix, passedMatrix) obs = np.append(densityMatrix, tlMatrix) # print(densityMatrix) # print(passedMatrix) return obs def render(self, mode='human'): pass # print(self.reward) def close(self): libsalt.close() print('close')
[ "libsalt.simulationStep", "libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID", "math.log", "numpy.array", "libsalt.start", "libsalt.trafficsignal.getTLSConnectedLinkID", "sys.path.append", "os.listdir", "xml.etree.ElementTree.parse", "numpy.where", "libsalt.trafficsignal.getCurrentTLSSc...
[((372, 416), 'sys.path.append', 'sys.path.append', (["TRAIN_CONFIG['libsalt_dir']"], {}), "(TRAIN_CONFIG['libsalt_dir'])\n", (387, 416), False, 'import sys\n'), ((730, 769), 'os.path.dirname', 'os.path.dirname', (['abs_scenario_file_path'], {}), '(abs_scenario_file_path)\n', (745, 769), False, 'import os\n'), ((3787, 3811), 'os.listdir', 'os.listdir', (['self.src_dir'], {}), '(self.src_dir)\n', (3797, 3811), False, 'import os\n'), ((9053, 9077), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (9061, 9077), True, 'import numpy as np\n'), ((11224, 11257), 'libsalt.start', 'libsalt.start', (['self.salt_scenario'], {}), '(self.salt_scenario)\n', (11237, 11257), False, 'import libsalt\n'), ((11266, 11304), 'libsalt.setCurrentStep', 'libsalt.setCurrentStep', (['self.startStep'], {}), '(self.startStep)\n', (11288, 11304), False, 'import libsalt\n'), ((13158, 13175), 'numpy.max', 'np.max', (['_lane_len'], {}), '(_lane_len)\n', (13164, 13175), True, 'import numpy as np\n'), ((13898, 13922), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (13906, 13922), True, 'import numpy as np\n'), ((13952, 13976), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (13960, 13976), True, 'import numpy as np\n'), ((13986, 14001), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (13999, 14001), False, 'import libsalt\n'), ((14193, 14217), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (14215, 14217), False, 'import libsalt\n'), ((15842, 15866), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (15864, 15866), False, 'import libsalt\n'), ((16939, 16963), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (16961, 16963), False, 'import libsalt\n'), ((20689, 20713), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (20711, 20713), False, 'import libsalt\n'), ((21528, 21561), 'libsalt.start', 'libsalt.start', (['self.salt_scenario'], {}), '(self.salt_scenario)\n', (21541, 21561), False, 'import libsalt\n'), ((21570, 21608), 'libsalt.setCurrentStep', 'libsalt.setCurrentStep', (['self.startStep'], {}), '(self.startStep)\n', (21592, 21608), False, 'import libsalt\n'), ((21641, 21665), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (21663, 21665), False, 'import libsalt\n'), ((23124, 23158), 'numpy.append', 'np.append', (['densityMatrix', 'tlMatrix'], {}), '(densityMatrix, tlMatrix)\n', (23133, 23158), True, 'import numpy as np\n'), ((23350, 23365), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (23363, 23365), False, 'import libsalt\n'), ((25370, 25394), 'os.listdir', 'os.listdir', (['self.src_dir'], {}), '(self.src_dir)\n', (25380, 25394), False, 'import os\n'), ((30542, 30566), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (30550, 30566), True, 'import numpy as np\n'), ((33518, 33551), 'libsalt.start', 'libsalt.start', (['self.salt_scenario'], {}), '(self.salt_scenario)\n', (33531, 33551), False, 'import libsalt\n'), ((33560, 33598), 'libsalt.setCurrentStep', 'libsalt.setCurrentStep', (['self.startStep'], {}), '(self.startStep)\n', (33582, 33598), False, 'import libsalt\n'), ((35452, 35469), 'numpy.max', 'np.max', (['_lane_len'], {}), '(_lane_len)\n', (35458, 35469), True, 'import numpy as np\n'), ((36190, 36214), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (36198, 36214), True, 'import numpy as np\n'), ((36244, 36268), 'numpy.zeros', 'np.zeros', (['self.agent_num'], {}), '(self.agent_num)\n', (36252, 36268), True, 'import numpy as np\n'), ((36278, 36293), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (36291, 36293), False, 'import libsalt\n'), ((36484, 36508), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (36506, 36508), False, 'import libsalt\n'), ((38133, 38157), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (38155, 38157), False, 'import libsalt\n'), ((39230, 39254), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (39252, 39254), False, 'import libsalt\n'), ((42799, 42823), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (42821, 42823), False, 'import libsalt\n'), ((45381, 45405), 'os.listdir', 'os.listdir', (['self.src_dir'], {}), '(self.src_dir)\n', (45391, 45405), False, 'import os\n'), ((45904, 45937), 'libsalt.start', 'libsalt.start', (['self.salt_scenario'], {}), '(self.salt_scenario)\n', (45917, 45937), False, 'import libsalt\n'), ((45946, 45984), 'libsalt.setCurrentStep', 'libsalt.setCurrentStep', (['self.startStep'], {}), '(self.startStep)\n', (45968, 45984), False, 'import libsalt\n'), ((46017, 46041), 'libsalt.getCurrentStep', 'libsalt.getCurrentStep', ([], {}), '()\n', (46039, 46041), False, 'import libsalt\n'), ((47669, 47703), 'numpy.append', 'np.append', (['densityMatrix', 'tlMatrix'], {}), '(densityMatrix, tlMatrix)\n', (47678, 47703), True, 'import numpy as np\n'), ((47894, 47909), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (47907, 47909), False, 'import libsalt\n'), ((665, 676), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (674, 676), False, 'import os\n'), ((781, 798), 'platform.system', 'platform.system', ([], {}), '()\n', (796, 798), False, 'import platform\n'), ((1016, 1036), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (1025, 1036), False, 'import json\n'), ((1640, 1651), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1649, 1651), False, 'import os\n'), ((1759, 1779), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (1768, 1779), False, 'import json\n'), ((2047, 2063), 'math.log', 'math.log', (['p_x', '(2)'], {}), '(p_x, 2)\n', (2055, 2063), False, 'import math\n'), ((3134, 3160), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (3150, 3160), False, 'import os\n'), ((3185, 3197), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (3195, 3197), False, 'import uuid\n'), ((3342, 3381), 'os.path.dirname', 'os.path.dirname', (['abs_scenario_file_path'], {}), '(abs_scenario_file_path)\n', (3357, 3381), False, 'import os\n'), ((3527, 3568), 'os.makedirs', 'os.makedirs', (['self.dest_dir'], {'exist_ok': '(True)'}), '(self.dest_dir, exist_ok=True)\n', (3538, 3568), False, 'import os\n'), ((3742, 3765), 'os.mkdir', 'os.mkdir', (['self.dest_dir'], {}), '(self.dest_dir)\n', (3750, 3765), False, 'import os\n'), ((3877, 3914), 'os.path.join', 'os.path.join', (['self.src_dir', 'file_name'], {}), '(self.src_dir, file_name)\n', (3889, 3914), False, 'import os\n'), ((3930, 3960), 'os.path.isfile', 'os.path.isfile', (['full_file_name'], {}), '(full_file_name)\n', (3944, 3960), False, 'import os\n'), ((4473, 4493), 'xml.etree.ElementTree.parse', 'parse', (['tss_file_path'], {}), '(tss_file_path)\n', (4478, 4493), False, 'from xml.etree.ElementTree import parse\n'), ((8878, 8904), 'numpy.max', 'np.max', (['self.phase_numbers'], {}), '(self.phase_numbers)\n', (8884, 8904), True, 'import numpy as np\n'), ((9373, 9394), 'xml.etree.ElementTree.parse', 'parse', (['edge_file_path'], {}), '(edge_file_path)\n', (9378, 9394), False, 'from xml.etree.ElementTree import parse\n'), ((11099, 11116), 'numpy.max', 'np.max', (['_edge_len'], {}), '(_edge_len)\n', (11105, 11116), True, 'import numpy as np\n'), ((13224, 13241), 'numpy.max', 'np.max', (['_lane_len'], {}), '(_lane_len)\n', (13230, 13241), True, 'import numpy as np\n'), ((14441, 14500), 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', (['tlid'], {}), '(tlid)\n', (14494, 14500), False, 'import libsalt\n'), ((15794, 15818), 'libsalt.simulationStep', 'libsalt.simulationStep', ([], {}), '()\n', (15816, 15818), False, 'import libsalt\n'), ((16131, 16190), 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', (['tlid'], {}), '(tlid)\n', (16184, 16190), False, 'import libsalt\n'), ((16600, 16659), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['tlid'], {}), '(tlid)\n', (16653, 16659), False, 'import libsalt\n'), ((16693, 16733), 'numpy.append', 'np.append', (['current_phase_list', 'currPhase'], {}), '(current_phase_list, currPhase)\n', (16702, 16733), True, 'import numpy as np\n'), ((16882, 16906), 'libsalt.simulationStep', 'libsalt.simulationStep', ([], {}), '()\n', (16904, 16906), False, 'import libsalt\n'), ((21308, 21323), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (21321, 21323), False, 'import libsalt\n'), ((22966, 23025), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['tsid'], {}), '(tsid)\n', (23019, 23025), False, 'import libsalt\n'), ((24712, 24738), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (24728, 24738), False, 'import os\n'), ((24763, 24775), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (24773, 24775), False, 'import uuid\n'), ((24925, 24964), 'os.path.dirname', 'os.path.dirname', (['abs_scenario_file_path'], {}), '(abs_scenario_file_path)\n', (24940, 24964), False, 'import os\n'), ((25110, 25151), 'os.makedirs', 'os.makedirs', (['self.dest_dir'], {'exist_ok': '(True)'}), '(self.dest_dir, exist_ok=True)\n', (25121, 25151), False, 'import os\n'), ((25325, 25348), 'os.mkdir', 'os.mkdir', (['self.dest_dir'], {}), '(self.dest_dir)\n', (25333, 25348), False, 'import os\n'), ((25460, 25497), 'os.path.join', 'os.path.join', (['self.src_dir', 'file_name'], {}), '(self.src_dir, file_name)\n', (25472, 25497), False, 'import os\n'), ((25513, 25543), 'os.path.isfile', 'os.path.isfile', (['full_file_name'], {}), '(full_file_name)\n', (25527, 25543), False, 'import os\n'), ((26063, 26083), 'xml.etree.ElementTree.parse', 'parse', (['tss_file_path'], {}), '(tss_file_path)\n', (26068, 26083), False, 'from xml.etree.ElementTree import parse\n'), ((30367, 30393), 'numpy.max', 'np.max', (['self.phase_numbers'], {}), '(self.phase_numbers)\n', (30373, 30393), True, 'import numpy as np\n'), ((30863, 30884), 'xml.etree.ElementTree.parse', 'parse', (['edge_file_path'], {}), '(edge_file_path)\n', (30868, 30884), False, 'from xml.etree.ElementTree import parse\n'), ((33393, 33410), 'numpy.max', 'np.max', (['_edge_len'], {}), '(_edge_len)\n', (33399, 33410), True, 'import numpy as np\n'), ((35518, 35535), 'numpy.max', 'np.max', (['_lane_len'], {}), '(_lane_len)\n', (35524, 35535), True, 'import numpy as np\n'), ((36732, 36791), 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', (['tlid'], {}), '(tlid)\n', (36785, 36791), False, 'import libsalt\n'), ((38085, 38109), 'libsalt.simulationStep', 'libsalt.simulationStep', ([], {}), '()\n', (38107, 38109), False, 'import libsalt\n'), ((38422, 38481), 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleIDByNodeID', (['tlid'], {}), '(tlid)\n', (38475, 38481), False, 'import libsalt\n'), ((38891, 38950), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['tlid'], {}), '(tlid)\n', (38944, 38950), False, 'import libsalt\n'), ((38984, 39024), 'numpy.append', 'np.append', (['current_phase_list', 'currPhase'], {}), '(current_phase_list, currPhase)\n', (38993, 39024), True, 'import numpy as np\n'), ((39173, 39197), 'libsalt.simulationStep', 'libsalt.simulationStep', ([], {}), '()\n', (39195, 39197), False, 'import libsalt\n'), ((44767, 44782), 'libsalt.close', 'libsalt.close', ([], {}), '()\n', (44780, 44782), False, 'import libsalt\n'), ((45001, 45013), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (45011, 45013), False, 'import uuid\n'), ((45185, 45226), 'os.makedirs', 'os.makedirs', (['self.dest_dir'], {'exist_ok': '(True)'}), '(self.dest_dir, exist_ok=True)\n', (45196, 45226), False, 'import os\n'), ((45336, 45359), 'os.mkdir', 'os.mkdir', (['self.dest_dir'], {}), '(self.dest_dir)\n', (45344, 45359), False, 'import os\n'), ((45471, 45508), 'os.path.join', 'os.path.join', (['self.src_dir', 'file_name'], {}), '(self.src_dir, file_name)\n', (45483, 45508), False, 'import os\n'), ((45524, 45554), 'os.path.isfile', 'os.path.isfile', (['full_file_name'], {}), '(full_file_name)\n', (45538, 45554), False, 'import os\n'), ((47511, 47570), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['tsid'], {}), '(tsid)\n', (47564, 47570), False, 'import libsalt\n'), ((3277, 3288), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3286, 3288), False, 'import os\n'), ((3410, 3437), 'os.path.split', 'os.path.split', (['self.src_dir'], {}), '(self.src_dir)\n', (3423, 3437), False, 'import os\n'), ((3610, 3621), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3619, 3621), False, 'import os\n'), ((3978, 4020), 'shutil.copy', 'shutil.copy', (['full_file_name', 'self.dest_dir'], {}), '(full_file_name, self.dest_dir)\n', (3989, 4020), False, 'import shutil\n'), ((7962, 8097), 'numpy.where', 'np.where', (["(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.\n target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0])"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.\n target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0])\n", (7970, 8097), True, 'import numpy as np\n'), ((11329, 11375), 'libsalt.trafficsignal.getTLSConnectedLinkID', 'libsalt.trafficsignal.getTLSConnectedLinkID', (['x'], {}), '(x)\n', (11372, 11375), False, 'import libsalt\n'), ((11433, 11489), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['x'], {}), '(x)\n', (11486, 11489), False, 'import libsalt\n'), ((11547, 11608), 'libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID', 'libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID', (['x'], {}), '(x)\n', (11605, 11608), False, 'import libsalt\n'), ((17748, 17775), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (17754, 17775), True, 'import numpy as np\n'), ((22546, 22582), 'libsalt.lane.getAverageDensity', 'libsalt.lane.getAverageDensity', (['link'], {}), '(link)\n', (22576, 22582), False, 'import libsalt\n'), ((24855, 24866), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (24864, 24866), False, 'import os\n'), ((24993, 25020), 'os.path.split', 'os.path.split', (['self.src_dir'], {}), '(self.src_dir)\n', (25006, 25020), False, 'import os\n'), ((25193, 25204), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (25202, 25204), False, 'import os\n'), ((25561, 25603), 'shutil.copy', 'shutil.copy', (['full_file_name', 'self.dest_dir'], {}), '(full_file_name, self.dest_dir)\n', (25572, 25603), False, 'import shutil\n'), ((29451, 29586), 'numpy.where', 'np.where', (["(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.\n target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0])"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['green_idx'][0] == self.\n target_tl_obj[x.attrib['nodeID']]['main_green_idx'][0][0])\n", (29459, 29586), True, 'import numpy as np\n'), ((33623, 33669), 'libsalt.trafficsignal.getTLSConnectedLinkID', 'libsalt.trafficsignal.getTLSConnectedLinkID', (['x'], {}), '(x)\n', (33666, 33669), False, 'import libsalt\n'), ((33727, 33783), 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', 'libsalt.trafficsignal.getCurrentTLSPhaseIndexByNodeID', (['x'], {}), '(x)\n', (33780, 33783), False, 'import libsalt\n'), ((33841, 33902), 'libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID', 'libsalt.trafficsignal.getLastTLSPhaseSwitchingTimeByNodeID', (['x'], {}), '(x)\n', (33899, 33902), False, 'import libsalt\n'), ((39859, 39886), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (39865, 39886), True, 'import numpy as np\n'), ((45068, 45095), 'os.path.split', 'os.path.split', (['self.src_dir'], {}), '(self.src_dir)\n', (45081, 45095), False, 'import os\n'), ((45572, 45614), 'shutil.copy', 'shutil.copy', (['full_file_name', 'self.dest_dir'], {}), '(full_file_name, self.dest_dir)\n', (45583, 45614), False, 'import shutil\n'), ((47091, 47127), 'libsalt.lane.getAverageDensity', 'libsalt.lane.getAverageDensity', (['link'], {}), '(link)\n', (47121, 47127), False, 'import libsalt\n'), ((1999, 2021), 'collections.Counter', 'collections.Counter', (['s'], {}), '(s)\n', (2018, 2021), False, 'import collections\n'), ((4716, 4727), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4725, 4727), False, 'import os\n'), ((7687, 7743), 'numpy.sum', 'np.sum', (["self.target_tl_obj[x.attrib['nodeID']]['minDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['minDur'])\n", (7693, 7743), True, 'import numpy as np\n'), ((9434, 9445), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (9443, 9445), False, 'import os\n'), ((12135, 12164), 'libsalt.link.getNumLane', 'libsalt.link.getNumLane', (['edge'], {}), '(edge)\n', (12158, 12164), False, 'import libsalt\n'), ((12603, 12632), 'libsalt.link.getNumLane', 'libsalt.link.getNumLane', (['edge'], {}), '(edge)\n', (12626, 12632), False, 'import libsalt\n'), ((18192, 18219), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (18198, 18219), True, 'import numpy as np\n'), ((18640, 18667), 'numpy.max', 'np.max', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (18646, 18667), True, 'import numpy as np\n'), ((19064, 19091), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (19070, 19091), True, 'import numpy as np\n'), ((19568, 19595), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (19574, 19595), True, 'import numpy as np\n'), ((20076, 20103), 'numpy.max', 'np.max', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (20082, 20103), True, 'import numpy as np\n'), ((20588, 20615), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (20594, 20615), True, 'import numpy as np\n'), ((22759, 22795), 'libsalt.lane.getAverageDensity', 'libsalt.lane.getAverageDensity', (['link'], {}), '(link)\n', (22789, 22795), False, 'import libsalt\n'), ((26205, 26216), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (26214, 26216), False, 'import os\n'), ((29176, 29232), 'numpy.sum', 'np.sum', (["self.target_tl_obj[x.attrib['nodeID']]['minDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['minDur'])\n", (29182, 29232), True, 'import numpy as np\n'), ((30924, 30935), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (30933, 30935), False, 'import os\n'), ((34429, 34458), 'libsalt.link.getNumLane', 'libsalt.link.getNumLane', (['edge'], {}), '(edge)\n', (34452, 34458), False, 'import libsalt\n'), ((34897, 34926), 'libsalt.link.getNumLane', 'libsalt.link.getNumLane', (['edge'], {}), '(edge)\n', (34920, 34926), False, 'import libsalt\n'), ((40303, 40330), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (40309, 40330), True, 'import numpy as np\n'), ((40751, 40778), 'numpy.max', 'np.max', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (40757, 40778), True, 'import numpy as np\n'), ((41175, 41202), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (41181, 41202), True, 'import numpy as np\n'), ((41679, 41706), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (41685, 41706), True, 'import numpy as np\n'), ((42187, 42214), 'numpy.max', 'np.max', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (42193, 42214), True, 'import numpy as np\n'), ((42699, 42726), 'numpy.sum', 'np.sum', (['self.lane_passed[i]'], {}), '(self.lane_passed[i])\n', (42705, 42726), True, 'import numpy as np\n'), ((47304, 47340), 'libsalt.lane.getAverageDensity', 'libsalt.lane.getAverageDensity', (['link'], {}), '(link)\n', (47334, 47340), False, 'import libsalt\n'), ((3675, 3686), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3684, 3686), False, 'import os\n'), ((6969, 7027), 'numpy.array', 'np.array', (["self.target_tl_obj[x.attrib['nodeID']]['minDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['minDur'])\n", (6977, 7027), True, 'import numpy as np\n'), ((7029, 7087), 'numpy.array', 'np.array', (["self.target_tl_obj[x.attrib['nodeID']]['maxDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['maxDur'])\n", (7037, 7087), True, 'import numpy as np\n'), ((7269, 7294), 'numpy.max', 'np.max', (['tmp_duration_list'], {}), '(tmp_duration_list)\n', (7275, 7294), True, 'import numpy as np\n'), ((11670, 11724), 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', (['x'], {}), '(x)\n', (11721, 11724), False, 'import libsalt\n'), ((17527, 17555), 'libsalt.link.getSumPassed', 'libsalt.link.getSumPassed', (['l'], {}), '(l)\n', (17552, 17555), False, 'import libsalt\n'), ((18818, 18858), 'libsalt.link.getAverageWaitingQLength', 'libsalt.link.getAverageWaitingQLength', (['l'], {}), '(l)\n', (18855, 18858), False, 'import libsalt\n'), ((21029, 21052), 'numpy.round', 'np.round', (['actions[i]', '(3)'], {}), '(actions[i], 3)\n', (21037, 21052), True, 'import numpy as np\n'), ((21119, 21147), 'numpy.round', 'np.round', (['self.rewards[i]', '(2)'], {}), '(self.rewards[i], 2)\n', (21127, 21147), True, 'import numpy as np\n'), ((25258, 25269), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (25267, 25269), False, 'import os\n'), ((28458, 28516), 'numpy.array', 'np.array', (["self.target_tl_obj[x.attrib['nodeID']]['minDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['minDur'])\n", (28466, 28516), True, 'import numpy as np\n'), ((28518, 28576), 'numpy.array', 'np.array', (["self.target_tl_obj[x.attrib['nodeID']]['maxDur']"], {}), "(self.target_tl_obj[x.attrib['nodeID']]['maxDur'])\n", (28526, 28576), True, 'import numpy as np\n'), ((28758, 28783), 'numpy.max', 'np.max', (['tmp_duration_list'], {}), '(tmp_duration_list)\n', (28764, 28783), True, 'import numpy as np\n'), ((33964, 34018), 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', (['x'], {}), '(x)\n', (34015, 34018), False, 'import libsalt\n'), ((39638, 39666), 'libsalt.link.getSumPassed', 'libsalt.link.getSumPassed', (['l'], {}), '(l)\n', (39663, 39666), False, 'import libsalt\n'), ((40929, 40969), 'libsalt.link.getAverageWaitingQLength', 'libsalt.link.getAverageWaitingQLength', (['l'], {}), '(l)\n', (40966, 40969), False, 'import libsalt\n'), ((45269, 45280), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (45278, 45280), False, 'import os\n'), ((11797, 11851), 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', (['x'], {}), '(x)\n', (11848, 11851), False, 'import libsalt\n'), ((17668, 17696), 'libsalt.link.getSumPassed', 'libsalt.link.getSumPassed', (['l'], {}), '(l)\n', (17693, 17696), False, 'import libsalt\n'), ((17926, 17963), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (17960, 17963), False, 'import libsalt\n'), ((18374, 18411), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (18408, 18411), False, 'import libsalt\n'), ((18971, 19011), 'libsalt.link.getAverageWaitingQLength', 'libsalt.link.getAverageWaitingQLength', (['l'], {}), '(l)\n', (19008, 19011), False, 'import libsalt\n'), ((19246, 19319), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (19294, 19319), False, 'import libsalt\n'), ((19754, 19827), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (19802, 19827), False, 'import libsalt\n'), ((20258, 20335), 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (20310, 20335), False, 'import libsalt\n'), ((34091, 34145), 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', 'libsalt.trafficsignal.getCurrentTLSScheduleByNodeID', (['x'], {}), '(x)\n', (34142, 34145), False, 'import libsalt\n'), ((39779, 39807), 'libsalt.link.getSumPassed', 'libsalt.link.getSumPassed', (['l'], {}), '(l)\n', (39804, 39807), False, 'import libsalt\n'), ((40037, 40074), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (40071, 40074), False, 'import libsalt\n'), ((40485, 40522), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (40519, 40522), False, 'import libsalt\n'), ((41082, 41122), 'libsalt.link.getAverageWaitingQLength', 'libsalt.link.getAverageWaitingQLength', (['l'], {}), '(l)\n', (41119, 41122), False, 'import libsalt\n'), ((41357, 41430), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (41405, 41430), False, 'import libsalt\n'), ((41865, 41938), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (41913, 41938), False, 'import libsalt\n'), ((42369, 42446), 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (42421, 42446), False, 'import libsalt\n'), ((43403, 43431), 'numpy.round', 'np.round', (['self.rewards[i]', '(2)'], {}), '(self.rewards[i], 2)\n', (43411, 43431), True, 'import numpy as np\n'), ((43660, 43688), 'numpy.round', 'np.round', (['self.rewards[i]', '(2)'], {}), '(self.rewards[i], 2)\n', (43668, 43688), True, 'import numpy as np\n'), ((44295, 44323), 'numpy.round', 'np.round', (['self.rewards[i]', '(2)'], {}), '(self.rewards[i], 2)\n', (44303, 44323), True, 'import numpy as np\n'), ((44552, 44580), 'numpy.round', 'np.round', (['self.rewards[i]', '(2)'], {}), '(self.rewards[i], 2)\n', (44560, 44580), True, 'import numpy as np\n'), ((18089, 18126), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (18123, 18126), False, 'import libsalt\n'), ((18537, 18574), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (18571, 18574), False, 'import libsalt\n'), ((19437, 19510), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (19485, 19510), False, 'import libsalt\n'), ((19945, 20018), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (19993, 20018), False, 'import libsalt\n'), ((20453, 20530), 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (20505, 20530), False, 'import libsalt\n'), ((40200, 40237), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (40234, 40237), False, 'import libsalt\n'), ((40648, 40685), 'libsalt.link.getAverageWaitingTime', 'libsalt.link.getAverageWaitingTime', (['l'], {}), '(l)\n', (40682, 40685), False, 'import libsalt\n'), ((41548, 41621), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (41596, 41621), False, 'import libsalt\n'), ((42056, 42129), 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', 'libsalt.link.getCurrentWaitingTimeSumBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (42104, 42129), False, 'import libsalt\n'), ((42564, 42641), 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', 'libsalt.link.getCurrentAverageWaitingTimeBaseVehicle', (['l', 'self.simulationSteps'], {}), '(l, self.simulationSteps)\n', (42616, 42641), False, 'import libsalt\n'), ((7469, 7494), 'numpy.max', 'np.max', (['tmp_duration_list'], {}), '(tmp_duration_list)\n', (7475, 7494), True, 'import numpy as np\n'), ((28958, 28983), 'numpy.max', 'np.max', (['tmp_duration_list'], {}), '(tmp_duration_list)\n', (28964, 28983), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import os import uuid import time import random import tensorflow as tf from tensorflow import keras from tensorflow.keras.layers import LeakyReLU, ReLU import numpy as np from dataset import Dataset from classifier import Classifier from util import map_label import tensorflow.keras.backend as K import logging tf.compat.v1.disable_eager_execution() logging.basicConfig(level=logging.INFO) class CE_GZSL: # optimizers generator_optimizer = None discriminator_optimizer = None # nets embedding_net = None comparator_net = None generator_net = None discriminator_net = None # params discriminator_iterations = None generator_noise = None gp_weight = None instance_weight = None class_weight = None instance_temperature = None class_temperature = None synthetic_number = None gzsl = None visual_size = None def __init__(self, generator_optimizer: keras.optimizers.Optimizer, discriminator_optimizer: keras.optimizers.Optimizer, args: dict, **kwargs): super(CE_GZSL, self).__init__(**kwargs) self.embedding(args["visual_size"], args["embedding_hidden"], args["embedding_size"]) self.comparator(args["embedding_hidden"], args["attribute_size"], args["comparator_hidden"]) self.generator(args["visual_size"], args["attribute_size"], args["generator_noise"], args["generator_hidden"]) self.discriminator(args["visual_size"], args["attribute_size"], args["discriminator_hidden"]) self.generator_optimizer = generator_optimizer self.discriminator_optimizer = discriminator_optimizer self.instance_weight = args["instance_weight"] self.class_weight = args["class_weight"] self.instance_temperature = args["instance_temperature"] self.class_temperature = args["class_temperature"] self.gp_weight = args["gp_weight"] self.synthetic_number = args["synthetic_number"] self.gzsl = args["gzsl"] self.visual_size = args["visual_size"] self.discriminator_iterations = args["discriminator_iterations"] self.generator_noise = args["generator_noise"] def summary(self): networks = [self.embedding_net, self.comparator_net, self.generator_net, self.discriminator_net] for net in networks: net.summary() def embedding(self, visual_size, hidden_units, embedded_size): inputs = keras.Input(shape=visual_size) x = keras.layers.Dense(hidden_units)(inputs) embed_h = ReLU(name="embed_h")(x) x = keras.layers.Dense(embedded_size)(embed_h) embed_z = keras.layers.Lambda(lambda x: K.l2_normalize(x, axis=1), name="embed_z")(x) self.embedding_net = keras.Model(inputs, [embed_h, embed_z], name="embedding") def comparator(self, embedding_size, attribute_size, hidden_units): inputs = keras.Input(shape=embedding_size + attribute_size) x = keras.layers.Dense(hidden_units)(inputs) x = LeakyReLU(0.2)(x) output = keras.layers.Dense(1, name="comp_out")(x) self.comparator_net = keras.Model(inputs, output, name="comparator") def generator(self, visual_size, attribute_size, noise, hidden_units): inputs = keras.Input(shape=attribute_size + noise) x = keras.layers.Dense(hidden_units)(inputs) x = LeakyReLU(0.2)(x) x = keras.layers.Dense(visual_size)(x) output = ReLU(name="gen_out")(x) self.generator_net = keras.Model(inputs, output, name="generator") def discriminator(self, visual_size, attribute_size, hidden_units): inputs = keras.Input(shape=visual_size + attribute_size) x = keras.layers.Dense(hidden_units)(inputs) x = LeakyReLU(0.2)(x) output = keras.layers.Dense(1, name="disc_out")(x) self.discriminator_net = keras.Model(inputs, output, name="discriminator") def d_loss_fn(self, real_logits, fake_logits): real_loss = tf.reduce_mean(real_logits) fake_loss = tf.reduce_mean(fake_logits) return fake_loss - real_loss def gradient_penalty(self, batch_size, real_images, fake_images, attribute_data): """ Calculates the gradient penalty. This loss is calculated on an interpolated image and added to the discriminator loss. """ # Get the interpolated image alpha = tf.random.uniform(shape=(batch_size, 1)) alpha = tf.tile(alpha, (1, real_images.shape[1])) interpolated = real_images * alpha + (1-alpha) * fake_images with tf.GradientTape() as gp_tape: gp_tape.watch(interpolated) # 1. Get the discriminator output for this interpolated image. pred = self.discriminator_net(tf.concat([interpolated, attribute_data], axis=1)) # 2. Calculate the gradients w.r.t to this interpolated image. grads = gp_tape.gradient(pred, [interpolated])[0] # 3. Calculate the norm of the gradients. norm = tf.sqrt(tf.reduce_sum(tf.square(grads), axis=1)) gp = tf.reduce_mean((norm - 1.0) ** 2) return gp def contrastive_criterion(self, labels, feature_vectors): # Compute logits anchor_dot_contrast = tf.divide( tf.matmul( feature_vectors, tf.transpose(feature_vectors) ), self.instance_temperature, ) logits_max = tf.reduce_max(anchor_dot_contrast, 1, keepdims=True) logits = anchor_dot_contrast - logits_max # Expand to [batch_size, 1] labels = tf.reshape(labels, (-1, 1)) mask = tf.cast(tf.equal(labels, tf.transpose(labels)), dtype=tf.float32) # rosife: all except anchor logits_mask = tf.Variable(tf.ones_like(mask)) indices = tf.reshape(tf.range(0, tf.shape(mask)[0]), (-1, 1)) indices = tf.concat([indices, indices], axis=1) updates = tf.zeros((tf.shape(mask)[0])) logits_mask.scatter_nd_update(indices, updates) # rosife: positive except anchor mask = mask * logits_mask single_samples = tf.cast(tf.equal(tf.reduce_sum(mask, axis=1), 0), dtype=tf.float32) # compute log_prob masked_logits = tf.exp(logits) * logits_mask log_prob = logits - tf.math.log(tf.reduce_sum(masked_logits, 1, keepdims=True)) # compute mean of log-likelihood over positive mean_log_prob_pos = tf.reduce_sum(mask * log_prob, 1) / (tf.reduce_sum(mask, 1)+single_samples) # loss loss = -mean_log_prob_pos * (1 - single_samples) loss = tf.reduce_sum(loss) / (tf.cast(tf.shape(loss)[0], dtype=tf.float32) - tf.reduce_sum(single_samples)) return loss def class_scores_for_loop(self, embed, input_label, attribute_seen): n_class_seen = attribute_seen.shape[0] expand_embed = tf.reshape(tf.tile(tf.expand_dims(embed, 1), [1, n_class_seen, 1]), [embed.shape[0] * n_class_seen, -1]) expand_att = tf.reshape(tf.tile(tf.expand_dims(attribute_seen, 0), [embed.shape[0], 1, 1]), [embed.shape[0] * n_class_seen, -1]) all_scores = tf.reshape(tf.divide(self.comparator_net(tf.concat([expand_embed, expand_att], axis=1)), self.class_temperature), [embed.shape[0], n_class_seen]) score_max = tf.reduce_max(all_scores, axis=1, keepdims=True) # normalize the scores for stable training scores_norm = all_scores - score_max exp_scores = tf.exp(scores_norm) mask = tf.one_hot(input_label, n_class_seen) log_scores = scores_norm - tf.math.log(tf.reduce_sum(exp_scores, axis=1, keepdims=True)) cls_loss = -tf.reduce_mean(tf.reduce_sum(mask * log_scores, axis=1) / tf.reduce_sum(mask, axis=1)) return cls_loss def generate_synthetic_features(self, classes, attribute_data): nclass = classes.shape[0] syn_feature = tf.Variable(tf.zeros((self.synthetic_number * nclass, self.visual_size))) syn_label = tf.Variable(tf.zeros((self.synthetic_number * nclass, 1), dtype=classes.dtype)) for i in range(nclass): iclass = classes[i] iclass_att = attribute_data[iclass] syn_att = tf.repeat(tf.reshape(iclass_att, (1, -1)), self.synthetic_number, axis=0) syn_noise = tf.random.normal(shape=(self.synthetic_number, self.generator_noise)) output = self.generator_net(tf.concat([syn_noise, syn_att], axis=1)) syn_feature[i * self.synthetic_number:(i+1) * self.synthetic_number, :].assign(output) syn_label[i * self.synthetic_number:(i+1) * self.synthetic_number, :].assign(tf.fill((self.synthetic_number, 1), iclass)) return syn_feature, syn_label def train_step(self, real_features, attribute_data, labels, attribute_seen): batch_size = tf.shape(real_features)[0] d_loss_tracker = keras.metrics.Mean() for i in range(self.discriminator_iterations): # Get the latent vector noise_data = tf.random.normal(shape=(batch_size, self.generator_noise)) with tf.GradientTape() as tape: embed_real, z_real = self.embedding_net(real_features) real_ins_contras_loss = self.contrastive_criterion(labels, z_real) cls_loss_real = self.class_scores_for_loop(embed_real, labels, attribute_seen) # Generate fake images from the latent vector fake_features = self.generator_net(tf.concat([noise_data, attribute_data], axis=1)) # Get the logits for the fake images fake_logits = self.discriminator_net(tf.concat([fake_features, attribute_data], axis=1)) # Get the logits for the real images real_logits = self.discriminator_net(tf.concat([real_features, attribute_data], axis=1)) # Calculate the discriminator loss using the fake and real image logits d_cost = self.d_loss_fn(real_logits, fake_logits) # Calculate the gradient penalty gp = self.gradient_penalty(batch_size, real_features, fake_features, attribute_data) # Add the gradient penalty to the original discriminator loss d_loss = d_cost + gp * self.gp_weight + real_ins_contras_loss + cls_loss_real trainable_variables = self.discriminator_net.trainable_variables + self.embedding_net.trainable_variables + self.comparator_net.trainable_variables # Get the gradients w.r.t the discriminator loss d_gradient = tape.gradient(d_loss, trainable_variables) # Update the weights of the discriminator using the discriminator optimizer self.discriminator_optimizer.apply_gradients(zip(d_gradient, trainable_variables)) d_loss_tracker.update_state(d_loss) # Train the generator # Get the latent vector noise_data = tf.random.normal(shape=(batch_size, self.generator_noise)) with tf.GradientTape() as tape: embed_real, z_real = self.embedding_net(real_features) embed_fake, z_fake = self.embedding_net(fake_features) fake_ins_contras_loss = self.contrastive_criterion(tf.concat([labels, labels], axis=0), tf.concat([z_fake, z_real], axis=0)) cls_loss_fake = self.class_scores_for_loop(embed_fake, labels, attribute_seen) # Generate fake images using the generator fake_features = self.generator_net(tf.concat([noise_data, attribute_data], axis=1)) # Get the discriminator logits for fake images fake_logits = self.discriminator_net(tf.concat([fake_features, attribute_data], axis=1)) # Calculate the generator loss G_cost = -tf.reduce_mean(fake_logits) errG = G_cost + self.instance_weight * fake_ins_contras_loss + self.class_weight * cls_loss_fake # Get the gradients w.r.t the generator loss gen_gradient = tape.gradient(errG, self.generator_net.trainable_variables) # Update the weights of the generator using the generator optimizer self.generator_optimizer.apply_gradients(zip(gen_gradient, self.generator_net.trainable_variables)) return d_loss_tracker.result(), errG, cls_loss_fake, cls_loss_real, fake_ins_contras_loss, real_ins_contras_loss def fit(self, dataset): train_features = dataset.train_features() train_attributes = dataset.train_attributes() train_labels = dataset.train_labels() unseen_classes = tf.constant(dataset.unseen_classes()) seen_classes = tf.constant(dataset.seen_classes()) attributes = tf.constant(dataset.attributes()) train_feat_ds = tf.data.Dataset.from_tensor_slices(train_features) train_feat_ds = train_feat_ds.shuffle(buffer_size=train_features.shape[0], seed=seed).batch(batch_size) train_att_ds = tf.data.Dataset.from_tensor_slices(train_attributes) train_att_ds = train_att_ds.shuffle(buffer_size=train_attributes.shape[0], seed=seed).batch(batch_size) train_label_ds = tf.data.Dataset.from_tensor_slices(train_labels) train_label_ds = train_label_ds.shuffle(buffer_size=train_labels.shape[0], seed=seed).batch(batch_size) attribute_seen = tf.constant(ds.attribute_seen()) for epoch in range(epochs): epoch_start = time.time() att_it = train_att_ds.__iter__() label_it = train_label_ds.__iter__() d_loss_tracker = keras.metrics.Mean() g_loss_tracker = keras.metrics.Mean() for step, train_feat in enumerate(train_feat_ds): train_att = att_it.next() train_label = label_it.next() train_label = map_label(train_label, seen_classes) d_loss, g_loss, cls_loss_fake, cls_loss_real, fake_ins_contras_loss, real_ins_contras_loss = ce_gzsl.train_step(train_feat, train_att, train_label, attribute_seen) d_loss_tracker.update_state(d_loss) g_loss_tracker.update_state(g_loss) logging.info("main epoch {} - d_loss {:.4f} - g_loss {:.4f} - time: {:.4f}".format(epoch, d_loss_tracker.result(), g_loss_tracker.result(), time.time() - epoch_start)) # classification cls_start = time.time() if self.gzsl: syn_feature, syn_label = self.generate_synthetic_features(unseen_classes, attributes) train_x = tf.concat([train_features, syn_feature], axis=0) train_y = tf.concat([train_labels.reshape(-1, 1), syn_label], axis=0) num_classes = tf.size(unseen_classes) + tf.size(seen_classes) cls = Classifier(train_x, train_y, self.embedding_net, seed, num_classes, 25, self.synthetic_number, self.visual_size, cls_lr, beta1, beta2, dataset) acc_seen, acc_unseen, acc_h = cls.fit() logging.info('best acc: seen {:.4f} - unseen {:.4f} - H {:.4f} - time {:.4f}'.format(acc_seen, acc_unseen, acc_h, time.time() - cls_start)) else: syn_feature, syn_label = self.generate_synthetic_features(unseen_classes, attributes) labels = map_label(syn_label, unseen_classes) num_classes = tf.size(unseen_classes) cls = Classifier(syn_feature, labels, self.embedding_net, seed, num_classes, 100, self.synthetic_number, self.visual_size, cls_lr, beta1, beta2, dataset) acc = cls.fit_zsl() logging.info('best acc: {:.4f} - time {:.4f}'.format(acc, time.time() - cls_start)) if (epoch + 1) % checkpoint_epochs == 0: logging.info("saving checkpoint: {}".format(exp_path)) np.save(os.path.join(exp_path, "syn_feature.npy"), syn_feature.numpy()) np.save(os.path.join(exp_path, "syn_label.npy"), syn_label.numpy()) self.generator_net.save(os.path.join(exp_path, "generator.h5")) self.discriminator_net.save(os.path.join(exp_path, "discriminator.h5")) self.comparator_net.save(os.path.join(exp_path, "comparator.h5")) self.embedding_net.save(os.path.join(exp_path, "embedding.h5")) validation = False preprocessing = False exp_local_path = "<local_path>" exp_remote_path = "<remote_path>" exp_path = os.path.join(exp_remote_path, "cegzsl_experiments", str(uuid.uuid4())) os.makedirs(exp_path) data_local_path = "xlsa17" data_remote_path = "xlsa17" ds = Dataset(data_remote_path) ds.read("APY", preprocessing=preprocessing, validation=validation) args = {"visual_size": ds.feature_size(), "attribute_size": ds.attribute_size(), "embedding_size": 512, "embedding_hidden": 2048, "comparator_hidden": 2048, "generator_hidden": 4096, "generator_noise": 1024, "discriminator_hidden": 4096, "discriminator_iterations": 5, "instance_weight": 0.001, "class_weight": 0.001, "instance_temperature": 0.1, "class_temperature": 0.1, "gp_weight": 10.0, "gzsl": False, "synthetic_number": 100} # main training epochs = 2000 batch_size = 4096 learning_rate = 0.0001 lr_decay = 0.99 lr_decay_epochs = 100 beta1 = 0.5 beta2 = 0.999 seed = 1985 checkpoint_epochs = 100 random.seed(seed) np.random.seed(seed) tf.random.set_seed(seed) steps_per_epoch = int(np.ceil(ds.train_features().shape[0] / batch_size)) lr_decay_steps = lr_decay_epochs * steps_per_epoch # classifier cls_lr = 0.001 gen_lr_schedule = keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=learning_rate, decay_steps=lr_decay_steps, decay_rate=lr_decay) disc_lr_schedule = keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=learning_rate, decay_steps=lr_decay_steps, decay_rate=lr_decay) gen_opt = keras.optimizers.Adam(learning_rate=gen_lr_schedule, beta_1=beta1, beta_2=beta2) disc_opt = keras.optimizers.Adam(learning_rate=disc_lr_schedule, beta_1=beta1, beta_2=beta2) ce_gzsl = CE_GZSL(gen_opt, disc_opt, args) # ce_gzsl.summary() ce_gzsl.fit(ds)
[ "tensorflow.tile", "tensorflow.shape", "tensorflow.transpose", "tensorflow.reduce_sum", "classifier.Classifier", "tensorflow.GradientTape", "tensorflow.keras.layers.Dense", "tensorflow.ones_like", "tensorflow.reduce_mean", "tensorflow.random.normal", "tensorflow.data.Dataset.from_tensor_slices",...
[((340, 378), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (376, 378), True, 'import tensorflow as tf\n'), ((380, 419), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (399, 419), False, 'import logging\n'), ((16616, 16637), 'os.makedirs', 'os.makedirs', (['exp_path'], {}), '(exp_path)\n', (16627, 16637), False, 'import os\n'), ((16700, 16725), 'dataset.Dataset', 'Dataset', (['data_remote_path'], {}), '(data_remote_path)\n', (16707, 16725), False, 'from dataset import Dataset\n'), ((17520, 17537), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (17531, 17537), False, 'import random\n'), ((17538, 17558), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (17552, 17558), True, 'import numpy as np\n'), ((17559, 17583), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (17577, 17583), True, 'import tensorflow as tf\n'), ((17759, 17893), 'tensorflow.keras.optimizers.schedules.ExponentialDecay', 'keras.optimizers.schedules.ExponentialDecay', ([], {'initial_learning_rate': 'learning_rate', 'decay_steps': 'lr_decay_steps', 'decay_rate': 'lr_decay'}), '(initial_learning_rate=\n learning_rate, decay_steps=lr_decay_steps, decay_rate=lr_decay)\n', (17802, 17893), False, 'from tensorflow import keras\n'), ((17971, 18105), 'tensorflow.keras.optimizers.schedules.ExponentialDecay', 'keras.optimizers.schedules.ExponentialDecay', ([], {'initial_learning_rate': 'learning_rate', 'decay_steps': 'lr_decay_steps', 'decay_rate': 'lr_decay'}), '(initial_learning_rate=\n learning_rate, decay_steps=lr_decay_steps, decay_rate=lr_decay)\n', (18014, 18105), False, 'from tensorflow import keras\n'), ((18175, 18260), 'tensorflow.keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'learning_rate': 'gen_lr_schedule', 'beta_1': 'beta1', 'beta_2': 'beta2'}), '(learning_rate=gen_lr_schedule, beta_1=beta1, beta_2=beta2\n )\n', (18196, 18260), False, 'from tensorflow import keras\n'), ((18267, 18353), 'tensorflow.keras.optimizers.Adam', 'keras.optimizers.Adam', ([], {'learning_rate': 'disc_lr_schedule', 'beta_1': 'beta1', 'beta_2': 'beta2'}), '(learning_rate=disc_lr_schedule, beta_1=beta1, beta_2=\n beta2)\n', (18288, 18353), False, 'from tensorflow import keras\n'), ((2494, 2524), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': 'visual_size'}), '(shape=visual_size)\n', (2505, 2524), False, 'from tensorflow import keras\n'), ((2800, 2857), 'tensorflow.keras.Model', 'keras.Model', (['inputs', '[embed_h, embed_z]'], {'name': '"""embedding"""'}), "(inputs, [embed_h, embed_z], name='embedding')\n", (2811, 2857), False, 'from tensorflow import keras\n'), ((2949, 2999), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': '(embedding_size + attribute_size)'}), '(shape=embedding_size + attribute_size)\n', (2960, 2999), False, 'from tensorflow import keras\n'), ((3173, 3219), 'tensorflow.keras.Model', 'keras.Model', (['inputs', 'output'], {'name': '"""comparator"""'}), "(inputs, output, name='comparator')\n", (3184, 3219), False, 'from tensorflow import keras\n'), ((3314, 3355), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': '(attribute_size + noise)'}), '(shape=attribute_size + noise)\n', (3325, 3355), False, 'from tensorflow import keras\n'), ((3556, 3601), 'tensorflow.keras.Model', 'keras.Model', (['inputs', 'output'], {'name': '"""generator"""'}), "(inputs, output, name='generator')\n", (3567, 3601), False, 'from tensorflow import keras\n'), ((3693, 3740), 'tensorflow.keras.Input', 'keras.Input', ([], {'shape': '(visual_size + attribute_size)'}), '(shape=visual_size + attribute_size)\n', (3704, 3740), False, 'from tensorflow import keras\n'), ((3916, 3965), 'tensorflow.keras.Model', 'keras.Model', (['inputs', 'output'], {'name': '"""discriminator"""'}), "(inputs, output, name='discriminator')\n", (3927, 3965), False, 'from tensorflow import keras\n'), ((4039, 4066), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['real_logits'], {}), '(real_logits)\n', (4053, 4066), True, 'import tensorflow as tf\n'), ((4087, 4114), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['fake_logits'], {}), '(fake_logits)\n', (4101, 4114), True, 'import tensorflow as tf\n'), ((4452, 4492), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '(batch_size, 1)'}), '(shape=(batch_size, 1))\n', (4469, 4492), True, 'import tensorflow as tf\n'), ((4509, 4550), 'tensorflow.tile', 'tf.tile', (['alpha', '(1, real_images.shape[1])'], {}), '(alpha, (1, real_images.shape[1]))\n', (4516, 4550), True, 'import tensorflow as tf\n'), ((5129, 5162), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['((norm - 1.0) ** 2)'], {}), '((norm - 1.0) ** 2)\n', (5143, 5162), True, 'import tensorflow as tf\n'), ((5483, 5535), 'tensorflow.reduce_max', 'tf.reduce_max', (['anchor_dot_contrast', '(1)'], {'keepdims': '(True)'}), '(anchor_dot_contrast, 1, keepdims=True)\n', (5496, 5535), True, 'import tensorflow as tf\n'), ((5640, 5667), 'tensorflow.reshape', 'tf.reshape', (['labels', '(-1, 1)'], {}), '(labels, (-1, 1))\n', (5650, 5667), True, 'import tensorflow as tf\n'), ((5928, 5965), 'tensorflow.concat', 'tf.concat', (['[indices, indices]'], {'axis': '(1)'}), '([indices, indices], axis=1)\n', (5937, 5965), True, 'import tensorflow as tf\n'), ((7354, 7402), 'tensorflow.reduce_max', 'tf.reduce_max', (['all_scores'], {'axis': '(1)', 'keepdims': '(True)'}), '(all_scores, axis=1, keepdims=True)\n', (7367, 7402), True, 'import tensorflow as tf\n'), ((7521, 7540), 'tensorflow.exp', 'tf.exp', (['scores_norm'], {}), '(scores_norm)\n', (7527, 7540), True, 'import tensorflow as tf\n'), ((7557, 7594), 'tensorflow.one_hot', 'tf.one_hot', (['input_label', 'n_class_seen'], {}), '(input_label, n_class_seen)\n', (7567, 7594), True, 'import tensorflow as tf\n'), ((8944, 8964), 'tensorflow.keras.metrics.Mean', 'keras.metrics.Mean', ([], {}), '()\n', (8962, 8964), False, 'from tensorflow import keras\n'), ((11002, 11060), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(batch_size, self.generator_noise)'}), '(shape=(batch_size, self.generator_noise))\n', (11018, 11060), True, 'import tensorflow as tf\n'), ((12809, 12859), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_features'], {}), '(train_features)\n', (12843, 12859), True, 'import tensorflow as tf\n'), ((12996, 13048), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_attributes'], {}), '(train_attributes)\n', (13030, 13048), True, 'import tensorflow as tf\n'), ((13187, 13235), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_labels'], {}), '(train_labels)\n', (13221, 13235), True, 'import tensorflow as tf\n'), ((16601, 16613), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (16611, 16613), False, 'import uuid\n'), ((2537, 2569), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['hidden_units'], {}), '(hidden_units)\n', (2555, 2569), False, 'from tensorflow import keras\n'), ((2596, 2616), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': '"""embed_h"""'}), "(name='embed_h')\n", (2600, 2616), False, 'from tensorflow.keras.layers import LeakyReLU, ReLU\n'), ((2632, 2665), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['embedded_size'], {}), '(embedded_size)\n', (2650, 2665), False, 'from tensorflow import keras\n'), ((3012, 3044), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['hidden_units'], {}), '(hidden_units)\n', (3030, 3044), False, 'from tensorflow import keras\n'), ((3065, 3079), 'tensorflow.keras.layers.LeakyReLU', 'LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (3074, 3079), False, 'from tensorflow.keras.layers import LeakyReLU, ReLU\n'), ((3100, 3138), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'name': '"""comp_out"""'}), "(1, name='comp_out')\n", (3118, 3138), False, 'from tensorflow import keras\n'), ((3368, 3400), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['hidden_units'], {}), '(hidden_units)\n', (3386, 3400), False, 'from tensorflow import keras\n'), ((3421, 3435), 'tensorflow.keras.layers.LeakyReLU', 'LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (3430, 3435), False, 'from tensorflow.keras.layers import LeakyReLU, ReLU\n'), ((3451, 3482), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['visual_size'], {}), '(visual_size)\n', (3469, 3482), False, 'from tensorflow import keras\n'), ((3503, 3523), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': '"""gen_out"""'}), "(name='gen_out')\n", (3507, 3523), False, 'from tensorflow.keras.layers import LeakyReLU, ReLU\n'), ((3753, 3785), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['hidden_units'], {}), '(hidden_units)\n', (3771, 3785), False, 'from tensorflow import keras\n'), ((3806, 3820), 'tensorflow.keras.layers.LeakyReLU', 'LeakyReLU', (['(0.2)'], {}), '(0.2)\n', (3815, 3820), False, 'from tensorflow.keras.layers import LeakyReLU, ReLU\n'), ((3841, 3879), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'name': '"""disc_out"""'}), "(1, name='disc_out')\n", (3859, 3879), False, 'from tensorflow import keras\n'), ((4634, 4651), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (4649, 4651), True, 'import tensorflow as tf\n'), ((5820, 5838), 'tensorflow.ones_like', 'tf.ones_like', (['mask'], {}), '(mask)\n', (5832, 5838), True, 'import tensorflow as tf\n'), ((6291, 6305), 'tensorflow.exp', 'tf.exp', (['logits'], {}), '(logits)\n', (6297, 6305), True, 'import tensorflow as tf\n'), ((6492, 6525), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(mask * log_prob)', '(1)'], {}), '(mask * log_prob, 1)\n', (6505, 6525), True, 'import tensorflow as tf\n'), ((6656, 6675), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['loss'], {}), '(loss)\n', (6669, 6675), True, 'import tensorflow as tf\n'), ((7964, 8024), 'tensorflow.zeros', 'tf.zeros', (['(self.synthetic_number * nclass, self.visual_size)'], {}), '((self.synthetic_number * nclass, self.visual_size))\n', (7972, 8024), True, 'import tensorflow as tf\n'), ((8058, 8124), 'tensorflow.zeros', 'tf.zeros', (['(self.synthetic_number * nclass, 1)'], {'dtype': 'classes.dtype'}), '((self.synthetic_number * nclass, 1), dtype=classes.dtype)\n', (8066, 8124), True, 'import tensorflow as tf\n'), ((8362, 8431), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(self.synthetic_number, self.generator_noise)'}), '(shape=(self.synthetic_number, self.generator_noise))\n', (8378, 8431), True, 'import tensorflow as tf\n'), ((8891, 8914), 'tensorflow.shape', 'tf.shape', (['real_features'], {}), '(real_features)\n', (8899, 8914), True, 'import tensorflow as tf\n'), ((9083, 9141), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(batch_size, self.generator_noise)'}), '(shape=(batch_size, self.generator_noise))\n', (9099, 9141), True, 'import tensorflow as tf\n'), ((11075, 11092), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (11090, 11092), True, 'import tensorflow as tf\n'), ((13471, 13482), 'time.time', 'time.time', ([], {}), '()\n', (13480, 13482), False, 'import time\n'), ((13608, 13628), 'tensorflow.keras.metrics.Mean', 'keras.metrics.Mean', ([], {}), '()\n', (13626, 13628), False, 'from tensorflow import keras\n'), ((13658, 13678), 'tensorflow.keras.metrics.Mean', 'keras.metrics.Mean', ([], {}), '()\n', (13676, 13678), False, 'from tensorflow import keras\n'), ((14421, 14432), 'time.time', 'time.time', ([], {}), '()\n', (14430, 14432), False, 'import time\n'), ((4821, 4870), 'tensorflow.concat', 'tf.concat', (['[interpolated, attribute_data]'], {'axis': '(1)'}), '([interpolated, attribute_data], axis=1)\n', (4830, 4870), True, 'import tensorflow as tf\n'), ((5089, 5105), 'tensorflow.square', 'tf.square', (['grads'], {}), '(grads)\n', (5098, 5105), True, 'import tensorflow as tf\n'), ((5367, 5396), 'tensorflow.transpose', 'tf.transpose', (['feature_vectors'], {}), '(feature_vectors)\n', (5379, 5396), True, 'import tensorflow as tf\n'), ((5708, 5728), 'tensorflow.transpose', 'tf.transpose', (['labels'], {}), '(labels)\n', (5720, 5728), True, 'import tensorflow as tf\n'), ((5994, 6008), 'tensorflow.shape', 'tf.shape', (['mask'], {}), '(mask)\n', (6002, 6008), True, 'import tensorflow as tf\n'), ((6188, 6215), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['mask'], {'axis': '(1)'}), '(mask, axis=1)\n', (6201, 6215), True, 'import tensorflow as tf\n'), ((6360, 6406), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['masked_logits', '(1)'], {'keepdims': '(True)'}), '(masked_logits, 1, keepdims=True)\n', (6373, 6406), True, 'import tensorflow as tf\n'), ((6529, 6551), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['mask', '(1)'], {}), '(mask, 1)\n', (6542, 6551), True, 'import tensorflow as tf\n'), ((6726, 6755), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['single_samples'], {}), '(single_samples)\n', (6739, 6755), True, 'import tensorflow as tf\n'), ((6943, 6967), 'tensorflow.expand_dims', 'tf.expand_dims', (['embed', '(1)'], {}), '(embed, 1)\n', (6957, 6967), True, 'import tensorflow as tf\n'), ((7069, 7102), 'tensorflow.expand_dims', 'tf.expand_dims', (['attribute_seen', '(0)'], {}), '(attribute_seen, 0)\n', (7083, 7102), True, 'import tensorflow as tf\n'), ((7643, 7691), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['exp_scores'], {'axis': '(1)', 'keepdims': '(True)'}), '(exp_scores, axis=1, keepdims=True)\n', (7656, 7691), True, 'import tensorflow as tf\n'), ((8273, 8304), 'tensorflow.reshape', 'tf.reshape', (['iclass_att', '(1, -1)'], {}), '(iclass_att, (1, -1))\n', (8283, 8304), True, 'import tensorflow as tf\n'), ((8473, 8512), 'tensorflow.concat', 'tf.concat', (['[syn_noise, syn_att]'], {'axis': '(1)'}), '([syn_noise, syn_att], axis=1)\n', (8482, 8512), True, 'import tensorflow as tf\n'), ((8703, 8746), 'tensorflow.fill', 'tf.fill', (['(self.synthetic_number, 1)', 'iclass'], {}), '((self.synthetic_number, 1), iclass)\n', (8710, 8746), True, 'import tensorflow as tf\n'), ((9160, 9177), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (9175, 9177), True, 'import tensorflow as tf\n'), ((11302, 11337), 'tensorflow.concat', 'tf.concat', (['[labels, labels]'], {'axis': '(0)'}), '([labels, labels], axis=0)\n', (11311, 11337), True, 'import tensorflow as tf\n'), ((11339, 11374), 'tensorflow.concat', 'tf.concat', (['[z_fake, z_real]'], {'axis': '(0)'}), '([z_fake, z_real], axis=0)\n', (11348, 11374), True, 'import tensorflow as tf\n'), ((11570, 11617), 'tensorflow.concat', 'tf.concat', (['[noise_data, attribute_data]'], {'axis': '(1)'}), '([noise_data, attribute_data], axis=1)\n', (11579, 11617), True, 'import tensorflow as tf\n'), ((11727, 11777), 'tensorflow.concat', 'tf.concat', (['[fake_features, attribute_data]'], {'axis': '(1)'}), '([fake_features, attribute_data], axis=1)\n', (11736, 11777), True, 'import tensorflow as tf\n'), ((11844, 11871), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['fake_logits'], {}), '(fake_logits)\n', (11858, 11871), True, 'import tensorflow as tf\n'), ((13862, 13898), 'util.map_label', 'map_label', (['train_label', 'seen_classes'], {}), '(train_label, seen_classes)\n', (13871, 13898), False, 'from util import map_label\n'), ((14590, 14638), 'tensorflow.concat', 'tf.concat', (['[train_features, syn_feature]'], {'axis': '(0)'}), '([train_features, syn_feature], axis=0)\n', (14599, 14638), True, 'import tensorflow as tf\n'), ((14826, 14973), 'classifier.Classifier', 'Classifier', (['train_x', 'train_y', 'self.embedding_net', 'seed', 'num_classes', '(25)', 'self.synthetic_number', 'self.visual_size', 'cls_lr', 'beta1', 'beta2', 'dataset'], {}), '(train_x, train_y, self.embedding_net, seed, num_classes, 25,\n self.synthetic_number, self.visual_size, cls_lr, beta1, beta2, dataset)\n', (14836, 14973), False, 'from classifier import Classifier\n'), ((15363, 15399), 'util.map_label', 'map_label', (['syn_label', 'unseen_classes'], {}), '(syn_label, unseen_classes)\n', (15372, 15399), False, 'from util import map_label\n'), ((15430, 15453), 'tensorflow.size', 'tf.size', (['unseen_classes'], {}), '(unseen_classes)\n', (15437, 15453), True, 'import tensorflow as tf\n'), ((15477, 15628), 'classifier.Classifier', 'Classifier', (['syn_feature', 'labels', 'self.embedding_net', 'seed', 'num_classes', '(100)', 'self.synthetic_number', 'self.visual_size', 'cls_lr', 'beta1', 'beta2', 'dataset'], {}), '(syn_feature, labels, self.embedding_net, seed, num_classes, 100,\n self.synthetic_number, self.visual_size, cls_lr, beta1, beta2, dataset)\n', (15487, 15628), False, 'from classifier import Classifier\n'), ((2724, 2749), 'tensorflow.keras.backend.l2_normalize', 'K.l2_normalize', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (2738, 2749), True, 'import tensorflow.keras.backend as K\n'), ((5881, 5895), 'tensorflow.shape', 'tf.shape', (['mask'], {}), '(mask)\n', (5889, 5895), True, 'import tensorflow as tf\n'), ((7228, 7273), 'tensorflow.concat', 'tf.concat', (['[expand_embed, expand_att]'], {'axis': '(1)'}), '([expand_embed, expand_att], axis=1)\n', (7237, 7273), True, 'import tensorflow as tf\n'), ((7729, 7769), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(mask * log_scores)'], {'axis': '(1)'}), '(mask * log_scores, axis=1)\n', (7742, 7769), True, 'import tensorflow as tf\n'), ((7772, 7799), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['mask'], {'axis': '(1)'}), '(mask, axis=1)\n', (7785, 7799), True, 'import tensorflow as tf\n'), ((9552, 9599), 'tensorflow.concat', 'tf.concat', (['[noise_data, attribute_data]'], {'axis': '(1)'}), '([noise_data, attribute_data], axis=1)\n', (9561, 9599), True, 'import tensorflow as tf\n'), ((9707, 9757), 'tensorflow.concat', 'tf.concat', (['[fake_features, attribute_data]'], {'axis': '(1)'}), '([fake_features, attribute_data], axis=1)\n', (9716, 9757), True, 'import tensorflow as tf\n'), ((9865, 9915), 'tensorflow.concat', 'tf.concat', (['[real_features, attribute_data]'], {'axis': '(1)'}), '([real_features, attribute_data], axis=1)\n', (9874, 9915), True, 'import tensorflow as tf\n'), ((14755, 14778), 'tensorflow.size', 'tf.size', (['unseen_classes'], {}), '(unseen_classes)\n', (14762, 14778), True, 'import tensorflow as tf\n'), ((14781, 14802), 'tensorflow.size', 'tf.size', (['seen_classes'], {}), '(seen_classes)\n', (14788, 14802), True, 'import tensorflow as tf\n'), ((15945, 15986), 'os.path.join', 'os.path.join', (['exp_path', '"""syn_feature.npy"""'], {}), "(exp_path, 'syn_feature.npy')\n", (15957, 15986), False, 'import os\n'), ((16033, 16072), 'os.path.join', 'os.path.join', (['exp_path', '"""syn_label.npy"""'], {}), "(exp_path, 'syn_label.npy')\n", (16045, 16072), False, 'import os\n'), ((16133, 16171), 'os.path.join', 'os.path.join', (['exp_path', '"""generator.h5"""'], {}), "(exp_path, 'generator.h5')\n", (16145, 16171), False, 'import os\n'), ((16217, 16259), 'os.path.join', 'os.path.join', (['exp_path', '"""discriminator.h5"""'], {}), "(exp_path, 'discriminator.h5')\n", (16229, 16259), False, 'import os\n'), ((16302, 16341), 'os.path.join', 'os.path.join', (['exp_path', '"""comparator.h5"""'], {}), "(exp_path, 'comparator.h5')\n", (16314, 16341), False, 'import os\n'), ((16383, 16421), 'os.path.join', 'os.path.join', (['exp_path', '"""embedding.h5"""'], {}), "(exp_path, 'embedding.h5')\n", (16395, 16421), False, 'import os\n'), ((6687, 6701), 'tensorflow.shape', 'tf.shape', (['loss'], {}), '(loss)\n', (6695, 6701), True, 'import tensorflow as tf\n'), ((14338, 14349), 'time.time', 'time.time', ([], {}), '()\n', (14347, 14349), False, 'import time\n'), ((15191, 15202), 'time.time', 'time.time', ([], {}), '()\n', (15200, 15202), False, 'import time\n'), ((15770, 15781), 'time.time', 'time.time', ([], {}), '()\n', (15779, 15781), False, 'import time\n')]
import logging import os import numpy as np import simulacra as si from simulacra.units import * import matplotlib.pyplot as plt FILE_NAME = os.path.splitext(os.path.basename(__file__))[0] OUT_DIR = os.path.join(os.getcwd(), "out", FILE_NAME) if __name__ == "__main__": with si.utils.LogManager( "simulacra", stdout_logs=True, stdout_level=logging.DEBUG, file_dir=OUT_DIR, file_logs=False, ) as logger: x = np.linspace(-5, 5, 200) y = np.linspace(-5, 5, 200) x_mesh, y_mesh = np.meshgrid(x, y, indexing="ij") # z_mesh = 1j * np.sin(y_mesh) # z_mesh = np.zeros(np.shape(x_mesh)) z_mesh = x_mesh + (1j * y_mesh) rich = si.plots.RichardsonColormap() for equator_mag in (0.2, 1, 5): for shading in ("flat", "gouraud"): si.plots.xyz_plot( f"richardson_xyz_eq={equator_mag}_{shading}", x_mesh, y_mesh, z_mesh, x_unit="rad", y_unit="rad", shading=shading, colormap=plt.get_cmap("richardson"), richardson_equator_magnitude=equator_mag, target_dir=OUT_DIR, show_colorbar=False, aspect_ratio=1, ) def z(x_mesh, y_mesh, t): return z_mesh * np.exp(1j * t) t = np.linspace(0, 10, 900) * pi for equator_mag in (0.2, 1, 5): for shading in ("flat", "gouraud"): si.plots.xyzt_plot( f"richardson_xyzt_eq={equator_mag}_{shading}", x_mesh, y_mesh, t, z, x_label=r"$x$", y_label=r"$y$", x_unit="rad", y_unit="rad", title=r"$(x + iy) e^{i t}$", shading=shading, colormap=plt.get_cmap("richardson"), richardson_equator_magnitude=equator_mag, target_dir=OUT_DIR, show_colorbar=False, aspect_ratio=1, ) def z2(x_mesh, y_mesh, t): return z_mesh * np.exp(1j * t) * np.sin(x_mesh ** 2 + y_mesh ** 2 + t) for equator_mag in (0.2, 1, 5): for shading in ("flat", "gouraud"): si.plots.xyzt_plot( f"richardson_xyzt2_eq={equator_mag}_{shading}", x_mesh, y_mesh, t, z2, x_label=r"$x$", y_label=r"$y$", x_unit="rad", y_unit="rad", title=r"$(x + iy) e^{i t} \sin(x^2 + y^2 + t)$", shading=shading, colormap=plt.get_cmap("richardson"), richardson_equator_magnitude=equator_mag, target_dir=OUT_DIR, show_colorbar=False, aspect_ratio=1, )
[ "simulacra.plots.RichardsonColormap", "simulacra.utils.LogManager", "os.getcwd", "numpy.exp", "numpy.linspace", "os.path.basename", "numpy.sin", "numpy.meshgrid", "matplotlib.pyplot.get_cmap" ]
[((217, 228), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (226, 228), False, 'import os\n'), ((163, 189), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (179, 189), False, 'import os\n'), ((285, 403), 'simulacra.utils.LogManager', 'si.utils.LogManager', (['"""simulacra"""'], {'stdout_logs': '(True)', 'stdout_level': 'logging.DEBUG', 'file_dir': 'OUT_DIR', 'file_logs': '(False)'}), "('simulacra', stdout_logs=True, stdout_level=logging.\n DEBUG, file_dir=OUT_DIR, file_logs=False)\n", (304, 403), True, 'import simulacra as si\n'), ((469, 492), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(200)'], {}), '(-5, 5, 200)\n', (480, 492), True, 'import numpy as np\n'), ((505, 528), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', '(200)'], {}), '(-5, 5, 200)\n', (516, 528), True, 'import numpy as np\n'), ((555, 587), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {'indexing': '"""ij"""'}), "(x, y, indexing='ij')\n", (566, 587), True, 'import numpy as np\n'), ((730, 759), 'simulacra.plots.RichardsonColormap', 'si.plots.RichardsonColormap', ([], {}), '()\n', (757, 759), True, 'import simulacra as si\n'), ((1483, 1506), 'numpy.linspace', 'np.linspace', (['(0)', '(10)', '(900)'], {}), '(0, 10, 900)\n', (1494, 1506), True, 'import numpy as np\n'), ((1455, 1471), 'numpy.exp', 'np.exp', (['(1.0j * t)'], {}), '(1.0j * t)\n', (1461, 1471), True, 'import numpy as np\n'), ((2367, 2404), 'numpy.sin', 'np.sin', (['(x_mesh ** 2 + y_mesh ** 2 + t)'], {}), '(x_mesh ** 2 + y_mesh ** 2 + t)\n', (2373, 2404), True, 'import numpy as np\n'), ((2350, 2366), 'numpy.exp', 'np.exp', (['(1.0j * t)'], {}), '(1.0j * t)\n', (2356, 2366), True, 'import numpy as np\n'), ((1167, 1193), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""richardson"""'], {}), "('richardson')\n", (1179, 1193), True, 'import matplotlib.pyplot as plt\n'), ((2061, 2087), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""richardson"""'], {}), "('richardson')\n", (2073, 2087), True, 'import matplotlib.pyplot as plt\n'), ((2976, 3002), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""richardson"""'], {}), "('richardson')\n", (2988, 3002), True, 'import matplotlib.pyplot as plt\n')]
""" Shapes ------ Utility functions to generate different shapes. """ from typing import List import numpy as np from plofeld.utils.classes import Vector from plofeld.elements import PointCharge def get_regular_polygon(n: int, skew: bool = False, r: float = 1) -> List[Vector]: """Generate the coordinates for a regular polygon with 2n corners around the origin. Args: n (int): Half of the corners. skew (bool): Rotate polygon by half the angle between two poles. Default: ``False`` r (float): All corners lie on a circle of ratius ``r``. Default: ``1`` Returns: A list of Vectors defining the corners of the polygon. """ n_poles = 2*n phases = (np.arange(0, n_poles) + (0.5 * ~skew)) / n_poles coordinates = r * np.exp(2 * np.pi * 1j * phases) return [Vector(c.real, c.imag) for c in coordinates] def generate_mulitpole(n: int, skew: bool = False, **kwargs) -> List[PointCharge]: """Generate a multipole field consisting of 2n PointCharges with alternating polarity around origin. Args: n (int): Half of the corners. skew (bool): Rotate polygon by half the angle between two poles. Default: ``False`` Keyword Args: Are passed on to PointCharge objects Return: List of 2n PointCharges defining the Multipole. """ charge_map = {0: -1, 1: 1} coordinates = get_regular_polygon(n, skew) return [PointCharge(vec, charge_map[idx % 2], **kwargs) for idx, vec in enumerate(coordinates)]
[ "numpy.exp", "plofeld.elements.PointCharge", "plofeld.utils.classes.Vector", "numpy.arange" ]
[((781, 814), 'numpy.exp', 'np.exp', (['(2 * np.pi * 1.0j * phases)'], {}), '(2 * np.pi * 1.0j * phases)\n', (787, 814), True, 'import numpy as np\n'), ((825, 847), 'plofeld.utils.classes.Vector', 'Vector', (['c.real', 'c.imag'], {}), '(c.real, c.imag)\n', (831, 847), False, 'from plofeld.utils.classes import Vector\n'), ((1436, 1483), 'plofeld.elements.PointCharge', 'PointCharge', (['vec', 'charge_map[idx % 2]'], {}), '(vec, charge_map[idx % 2], **kwargs)\n', (1447, 1483), False, 'from plofeld.elements import PointCharge\n'), ((710, 731), 'numpy.arange', 'np.arange', (['(0)', 'n_poles'], {}), '(0, n_poles)\n', (719, 731), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from scipy import stats def beta(y, x): mask = ~np.isnan(y) & ~np.isnan(x) y = y[mask] x = x[mask] slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) return intercept, slope, p_value np.random.seed(12345678) x = np.random.random(10) y = np.random.random(10) # slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) # print("r-squared:", r_value**2) alpha, beta, p_value = beta(y, x) print(alpha, beta, p_value) plt.plot(x, y, 'o', label='original data') plt.plot(x, alpha + beta*x, 'r', label='fitted line') plt.legend() plt.show()
[ "scipy.stats.linregress", "numpy.random.random", "matplotlib.pyplot.plot", "numpy.isnan", "numpy.random.seed", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((274, 298), 'numpy.random.seed', 'np.random.seed', (['(12345678)'], {}), '(12345678)\n', (288, 298), True, 'import numpy as np\n'), ((303, 323), 'numpy.random.random', 'np.random.random', (['(10)'], {}), '(10)\n', (319, 323), True, 'import numpy as np\n'), ((328, 348), 'numpy.random.random', 'np.random.random', (['(10)'], {}), '(10)\n', (344, 348), True, 'import numpy as np\n'), ((517, 559), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o"""'], {'label': '"""original data"""'}), "(x, y, 'o', label='original data')\n", (525, 559), True, 'import matplotlib.pyplot as plt\n'), ((560, 615), 'matplotlib.pyplot.plot', 'plt.plot', (['x', '(alpha + beta * x)', '"""r"""'], {'label': '"""fitted line"""'}), "(x, alpha + beta * x, 'r', label='fitted line')\n", (568, 615), True, 'import matplotlib.pyplot as plt\n'), ((614, 626), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (624, 626), True, 'import matplotlib.pyplot as plt\n'), ((627, 637), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (635, 637), True, 'import matplotlib.pyplot as plt\n'), ((213, 235), 'scipy.stats.linregress', 'stats.linregress', (['x', 'y'], {}), '(x, y)\n', (229, 235), False, 'from scipy import stats\n'), ((104, 115), 'numpy.isnan', 'np.isnan', (['y'], {}), '(y)\n', (112, 115), True, 'import numpy as np\n'), ((119, 130), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (127, 130), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # Plot the standard gaussian distribution. import matplotlib.pyplot as pl import numpy as np from scipy.stats import norm x = np.linspace(-3, 3, 100) y = norm.pdf(x) pl.plot(x, y) pl.savefig('gaussPlotDemo.png') pl.show()
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.linspace", "scipy.stats.norm.pdf", "matplotlib.pyplot.show" ]
[((152, 175), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (163, 175), True, 'import numpy as np\n'), ((180, 191), 'scipy.stats.norm.pdf', 'norm.pdf', (['x'], {}), '(x)\n', (188, 191), False, 'from scipy.stats import norm\n'), ((192, 205), 'matplotlib.pyplot.plot', 'pl.plot', (['x', 'y'], {}), '(x, y)\n', (199, 205), True, 'import matplotlib.pyplot as pl\n'), ((206, 237), 'matplotlib.pyplot.savefig', 'pl.savefig', (['"""gaussPlotDemo.png"""'], {}), "('gaussPlotDemo.png')\n", (216, 237), True, 'import matplotlib.pyplot as pl\n'), ((238, 247), 'matplotlib.pyplot.show', 'pl.show', ([], {}), '()\n', (245, 247), True, 'import matplotlib.pyplot as pl\n')]
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 15:39:21 2015 @author: Ben """ import clearplot.figure as figure import matplotlib.pyplot import os import numpy as np #Load image into python data_dir = os.path.join(os.path.dirname(figure.__file__), os.pardir, 'doc', \ 'source', 'data') path = os.path.join(data_dir, 'fiber_image.tiff') im = matplotlib.pyplot.imread(path) #Specify image position im_x = np.array([ 2.78977515, 15.43370266]) im_y = np.array([ -0.5998, 6.20705447]) #Load edge dectection results path = os.path.join(data_dir, 'fiber_edge_detection_data.csv') data = np.loadtxt(path, delimiter = ',') #Place the image on a set of axes fig = figure.Figure() ax = fig.add_axes() im_obj = ax.add_image(im, x = im_x, y = im_y) ax.x_label = ['x', 'mm'] ax.y_label = ['y', 'mm'] ax.x_tick = 2 ax.y_tick = 2 ax.x_lim = [0, None] ax.y_lim = [-2, None] #Add edge detected data ax.plot(data[:,0], data[:,1]) #Save the data1 fig.auto_adjust_layout() fig.save('plot_image_and_add_curve.png')
[ "clearplot.figure.Figure", "os.path.join", "os.path.dirname", "numpy.array", "numpy.loadtxt" ]
[((302, 344), 'os.path.join', 'os.path.join', (['data_dir', '"""fiber_image.tiff"""'], {}), "(data_dir, 'fiber_image.tiff')\n", (314, 344), False, 'import os\n'), ((412, 447), 'numpy.array', 'np.array', (['[2.78977515, 15.43370266]'], {}), '([2.78977515, 15.43370266])\n', (420, 447), True, 'import numpy as np\n'), ((457, 488), 'numpy.array', 'np.array', (['[-0.5998, 6.20705447]'], {}), '([-0.5998, 6.20705447])\n', (465, 488), True, 'import numpy as np\n'), ((527, 582), 'os.path.join', 'os.path.join', (['data_dir', '"""fiber_edge_detection_data.csv"""'], {}), "(data_dir, 'fiber_edge_detection_data.csv')\n", (539, 582), False, 'import os\n'), ((590, 621), 'numpy.loadtxt', 'np.loadtxt', (['path'], {'delimiter': '""","""'}), "(path, delimiter=',')\n", (600, 621), True, 'import numpy as np\n'), ((665, 680), 'clearplot.figure.Figure', 'figure.Figure', ([], {}), '()\n', (678, 680), True, 'import clearplot.figure as figure\n'), ((219, 251), 'os.path.dirname', 'os.path.dirname', (['figure.__file__'], {}), '(figure.__file__)\n', (234, 251), False, 'import os\n')]
# Get extrinsic position from aruco marker import cv2 import pickle import numpy as np def plot_markers(cv2_aruco_output, screen, VERBOSE=False): # Detector data (corners, ids, _) = cv2_aruco_output centres = [] # If there are valid points if len(corners) > 0: for (markerCorner, markerID) in zip(corners, ids.flatten()): # extract the marker corners # (top-left, top-right, bottom-right, and bottom-left order) corners = markerCorner.reshape((4, 2)) (topLeft, topRight, bottomRight, bottomLeft) = corners # convert each of the coordinate pairs to integers topRight = (int(topRight[0]), int(topRight[1])) bottomRight = (int(bottomRight[0]), int(bottomRight[1])) bottomLeft = (int(bottomLeft[0]), int(bottomLeft[1])) topLeft = (int(topLeft[0]), int(topLeft[1])) # draw the bounding box of the ArUCo detection cv2.line(screen, topLeft, topRight, (0, 255, 0), 2) cv2.line(screen, topRight, bottomRight, (0, 255, 0), 2) cv2.line(screen, bottomRight, bottomLeft, (0, 255, 0), 2) cv2.line(screen, bottomLeft, topLeft, (0, 255, 0), 2) # Put a little circle on the top left cv2.circle(screen, topLeft, 8, (0, 255, 0), -1) # compute and draw the center coordinates of the ArUco marker cX = int((topLeft[0] + bottomRight[0]) / 2.0) cY = int((topLeft[1] + bottomRight[1]) / 2.0) cv2.circle(screen, (cX, cY), 4, (0, 0, 255), -1) centres.append((cX, cY)) # draw the ArUco marker ID on the screen cv2.putText(screen, str(markerID), (topLeft[0], topLeft[1] - 15), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 5) if VERBOSE: print("[INFO] ArUco marker ID: {}".format(markerID)) return centres def clean_angles(angle): # angle = (angle / (2 * np.pi)) * 360 angle = round(angle, 2) return angle # Load previously saved data with open('camera_data.pkl', 'rb') as file: mtx, dist = pickle.load(file) # Define Aruco markers being used arucoDict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_4X4_1000) arucoParams = cv2.aruco.DetectorParameters_create() # Load video stream vs = cv2.VideoCapture(0) active = True while active: # Get frame active, img = vs.read() h, w, c = img.shape img = cv2.resize(img, (int(w/2), int(h/2))) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Unidistort the image map1, map2 = cv2.fisheye.initUndistortRectifyMap(mtx, dist, np.eye(3), mtx, gray.shape[:2][::-1], cv2.CV_16SC2) img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) #### Do aruco stuff # Get the aruco marker position cv2_aruco_output = cv2.aruco.detectMarkers(img, arucoDict, parameters=arucoParams) (corners, ids, rejected) = cv2_aruco_output plot_markers(cv2_aruco_output, img) # # If there were any detected # if np.all(ids != None): # # POSE ESTIMATION # rvec, trans,_ = cv2.aruco.estimatePoseSingleMarkers(corners, 0.1, mtx, dist) # # # Convert to rotation matrix # # rot = cv2.Rodrigues(rvec) # # x, y, z = trans[0][0] # # rho, theta, phi = list(map(clean_angles, rvec[0][0])) # # print(f"x: {round(x,2)}, y: {round(y,2)}, z: {round(z,2)}") # # print(f"rho: {rho}, theta: {theta}, phi: {phi}") # # print("") # for r, t in zip(rvec, trans): # img = cv2.aruco.drawAxis(img, mtx, dist, r, t, length=0.2) ### cv2.imshow('img',img) cv2.waitKey(1)
[ "numpy.eye", "cv2.line", "pickle.load", "cv2.remap", "cv2.aruco.detectMarkers", "cv2.aruco.DetectorParameters_create", "cv2.aruco.Dictionary_get", "cv2.imshow", "cv2.circle", "cv2.VideoCapture", "cv2.cvtColor", "cv2.waitKey" ]
[((2207, 2256), 'cv2.aruco.Dictionary_get', 'cv2.aruco.Dictionary_get', (['cv2.aruco.DICT_4X4_1000'], {}), '(cv2.aruco.DICT_4X4_1000)\n', (2231, 2256), False, 'import cv2\n'), ((2271, 2308), 'cv2.aruco.DetectorParameters_create', 'cv2.aruco.DetectorParameters_create', ([], {}), '()\n', (2306, 2308), False, 'import cv2\n'), ((2335, 2354), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2351, 2354), False, 'import cv2\n'), ((2142, 2159), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (2153, 2159), False, 'import pickle\n'), ((2511, 2548), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (2523, 2548), False, 'import cv2\n'), ((2703, 2798), 'cv2.remap', 'cv2.remap', (['img', 'map1', 'map2'], {'interpolation': 'cv2.INTER_LINEAR', 'borderMode': 'cv2.BORDER_CONSTANT'}), '(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.\n BORDER_CONSTANT)\n', (2712, 2798), False, 'import cv2\n'), ((2879, 2942), 'cv2.aruco.detectMarkers', 'cv2.aruco.detectMarkers', (['img', 'arucoDict'], {'parameters': 'arucoParams'}), '(img, arucoDict, parameters=arucoParams)\n', (2902, 2942), False, 'import cv2\n'), ((3682, 3704), 'cv2.imshow', 'cv2.imshow', (['"""img"""', 'img'], {}), "('img', img)\n", (3692, 3704), False, 'import cv2\n'), ((3708, 3722), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3719, 3722), False, 'import cv2\n'), ((2641, 2650), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (2647, 2650), True, 'import numpy as np\n'), ((976, 1027), 'cv2.line', 'cv2.line', (['screen', 'topLeft', 'topRight', '(0, 255, 0)', '(2)'], {}), '(screen, topLeft, topRight, (0, 255, 0), 2)\n', (984, 1027), False, 'import cv2\n'), ((1040, 1095), 'cv2.line', 'cv2.line', (['screen', 'topRight', 'bottomRight', '(0, 255, 0)', '(2)'], {}), '(screen, topRight, bottomRight, (0, 255, 0), 2)\n', (1048, 1095), False, 'import cv2\n'), ((1108, 1165), 'cv2.line', 'cv2.line', (['screen', 'bottomRight', 'bottomLeft', '(0, 255, 0)', '(2)'], {}), '(screen, bottomRight, bottomLeft, (0, 255, 0), 2)\n', (1116, 1165), False, 'import cv2\n'), ((1178, 1231), 'cv2.line', 'cv2.line', (['screen', 'bottomLeft', 'topLeft', '(0, 255, 0)', '(2)'], {}), '(screen, bottomLeft, topLeft, (0, 255, 0), 2)\n', (1186, 1231), False, 'import cv2\n'), ((1294, 1341), 'cv2.circle', 'cv2.circle', (['screen', 'topLeft', '(8)', '(0, 255, 0)', '(-1)'], {}), '(screen, topLeft, 8, (0, 255, 0), -1)\n', (1304, 1341), False, 'import cv2\n'), ((1544, 1592), 'cv2.circle', 'cv2.circle', (['screen', '(cX, cY)', '(4)', '(0, 0, 255)', '(-1)'], {}), '(screen, (cX, cY), 4, (0, 0, 255), -1)\n', (1554, 1592), False, 'import cv2\n')]
""" The core tools used in pyfstat """ import os import logging from pprint import pformat import glob import numpy as np import scipy.special import scipy.optimize from datetime import datetime import getpass import socket import lal import lalpulsar import pyfstat.helper_functions as helper_functions import pyfstat.tcw_fstat_map_funcs as tcw # workaround for matplotlib on X-less remote logins if "DISPLAY" in os.environ: import matplotlib.pyplot as plt else: logging.info( 'No $DISPLAY environment variable found, so importing \ matplotlib.pyplot with non-interactive "Agg" backend.' ) import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt helper_functions.set_up_matplotlib_defaults() args, tqdm = helper_functions.set_up_command_line_arguments() detector_colors = {"h1": "C0", "l1": "C1"} class BaseSearchClass: """The base class providing parent methods to other PyFstat classes. This does not actually have any 'search' functionality, which needs to be added by child classes along with full initialization and any other custom methods. """ def __new__(cls, *args, **kwargs): logging.info(f"Creating {cls.__name__} object...") instance = super().__new__(cls) return instance def _add_log_file(self, header=None): """ Log output to a file, requires class to have outdir and label """ header = [] if header is None else header logfilename = os.path.join(self.outdir, self.label + ".log") with open(logfilename, "w") as fp: for hline in header: fp.write("# {:s}\n".format(hline)) fh = logging.FileHandler(logfilename) fh.setLevel(logging.INFO) fh.setFormatter( logging.Formatter( "%(asctime)s %(levelname)-8s: %(message)s", datefmt="%y-%m-%d %H:%M" ) ) logging.getLogger().addHandler(fh) def _get_list_of_matching_sfts(self): """ Returns a list of sfts matching the attribute sftfilepattern """ sftfilepatternlist = np.atleast_1d(self.sftfilepattern.split(";")) matches = [glob.glob(p) for p in sftfilepatternlist] matches = [item for sublist in matches for item in sublist] if len(matches) > 0: return matches else: raise IOError("No sfts found matching {}".format(self.sftfilepattern)) def set_ephemeris_files(self, earth_ephem=None, sun_ephem=None): """Set the ephemeris files to use for the Earth and Sun. NOTE: If not given explicit arguments, default values from helper_functions.get_ephemeris_files() are used (looking in ~/.pyfstat or $LALPULSAR_DATADIR) Parameters ---------- earth_ephem, sun_ephem: str Paths of the two files containing positions of Earth and Sun, respectively at evenly spaced times, as passed to CreateFstatInput """ earth_ephem_default, sun_ephem_default = helper_functions.get_ephemeris_files() if earth_ephem is None: self.earth_ephem = earth_ephem_default else: self.earth_ephem = earth_ephem if sun_ephem is None: self.sun_ephem = sun_ephem_default else: self.sun_ephem = sun_ephem def _set_init_params_dict(self, argsdict): """ Store the initial input arguments, e.g. for logging output. """ argsdict.pop("self") self.init_params_dict = argsdict def pprint_init_params_dict(self): """Pretty-print a parameters dictionary for output file headers. Returns ------- pretty_init_parameters: list A list of lines to be printed, including opening/closing "{" and "}", consistent indentation, as well as end-of-line commas, but no comment markers at start of lines. """ pretty_init_parameters = pformat( self.init_params_dict, indent=2, width=74 ).split("\n") pretty_init_parameters = ( ["{"] + [pretty_init_parameters[0].replace("{", " ")] + pretty_init_parameters[1:-2] + [pretty_init_parameters[-1].rstrip("}")] + ["}"] ) return pretty_init_parameters def get_output_file_header(self): """Constructs a meta-information header for text output files. This will include PyFstat and LALSuite versioning, information about when/where/how the code was run, and input parameters of the instantiated class. Returns ------- header: list A list of formatted header lines. """ header = [ "date: {}".format(str(datetime.now())), "user: {}".format(getpass.getuser()), "hostname: {}".format(socket.gethostname()), "PyFstat: {}".format(helper_functions.get_version_string()), ] lalVCSinfo = lal.VCSInfoString(lalpulsar.PulsarVCSInfoList, 0, "") header += filter(None, lalVCSinfo.split("\n")) header += [ "search: {}".format(type(self).__name__), "parameters: ", ] header += self.pprint_init_params_dict() return header def read_par( self, filename=None, label=None, outdir=None, suffix="par", raise_error=True ): """Read a `key=val` file and return a dictionary. Parameters ---------- filename: str or None Filename (path) containing rows of `key=val` data to read in. label, outdir, suffix : str or None If filename is None, form the file to read as `outdir/label.suffix`. raise_error : bool If True, raise an error for lines which are not comments, but cannot be read. Returns ------- params_dict: dict A dictionary of the parsed `key=val` pairs. """ params_dict = helper_functions.read_par( filename=filename, label=label or getattr(self, "label", None), outdir=outdir or getattr(self, "outdir", None), suffix=suffix, raise_error=raise_error, ) return params_dict @staticmethod def translate_keys_to_lal(dictionary): """Convert input keys into lalpulsar convention. In PyFstat's convention, input keys (search parameter names) are F0, F1, F2, ..., while lalpulsar functions prefer to use Freq, f1dot, f2dot, .... Since lalpulsar keys are only used internally to call lalpulsar routines, this function is provided so the keys can be translated on the fly. Parameters ---------- dictionary: dict Dictionary to translate. A copy will be made (and returned) before translation takes place. Returns ------- translated_dict: dict Copy of "dictionary" with new keys according to lalpulsar convention. """ translation = { "F0": "Freq", "F1": "f1dot", "F2": "f2dot", "phi": "phi0", "tref": "refTime", "asini": "orbitasini", "period": "orbitPeriod", "tp": "orbitTp", "argp": "orbitArgp", "ecc": "orbitEcc", "transient_tstart": "transient-t0Epoch", "transient_duration": "transient-tau", } keys_to_translate = [key for key in dictionary.keys() if key in translation] translated_dict = dictionary.copy() for key in keys_to_translate: translated_dict[translation[key]] = translated_dict.pop(key) return translated_dict class ComputeFstat(BaseSearchClass): """Base search class providing an interface to `lalpulsar.ComputeFstat`. In most cases, users should be using one of the higher-level search classes from the grid_based_searches or mcmc_based_searches modules instead. See the lalpulsar documentation at https://lscsoft.docs.ligo.org/lalsuite/lalpulsar/group___compute_fstat__h.html and <NAME>, The F-statistic and its implementation in ComputeFstatistic_v2 ( https://dcc.ligo.org/T0900149/public ) for details of the lalpulsar module and the meaning of various technical concepts as embodied by some of the class's parameters. Normally this will read in existing data through the `sftfilepattern` argument, but if that option is `None` and the necessary alternative arguments are used, it can also generate simulated data (including noise and/or signals) on the fly. """ @helper_functions.initializer def __init__( self, tref, sftfilepattern=None, minStartTime=None, maxStartTime=None, Tsft=1800, binary=False, BSGL=False, transientWindowType=None, t0Band=None, tauBand=None, tauMin=None, dt0=None, dtau=None, detectors=None, minCoverFreq=None, maxCoverFreq=None, search_ranges=None, injectSources=None, injectSqrtSX=None, assumeSqrtSX=None, SSBprec=None, RngMedWindow=None, tCWFstatMapVersion="lal", cudaDeviceName=None, computeAtoms=False, earth_ephem=None, sun_ephem=None, ): """ Parameters ---------- tref : int GPS seconds of the reference time. sftfilepattern : str Pattern to match SFTs using wildcards (`*?`) and ranges [0-9]; mutiple patterns can be given separated by colons. minStartTime, maxStartTime : int Only use SFTs with timestamps starting from within this range, following the XLALCWGPSinRange convention: half-open intervals [minStartTime,maxStartTime]. Tsft: int SFT duration in seconds. Only required if `sftfilepattern=None` and hence simulted data is generated on the fly. binary : bool If true, search over binary parameters. BSGL : bool If true, compute the log10BSGL statistic rather than the twoF value. For details, see Keitel et al (PRD 89, 064023, 2014): https://arxiv.org/abs/1311.5738 Tuning parameters are currently hardcoded: * `Fstar0=15` for coherent searches. * A p-value of 1e-6 and correspondingly recalculated Fstar0 for semicoherent searches. * Uniform per-detector prior line-vs-Gaussian odds. transientWindowType: str If `rect` or `exp`, allow for the Fstat to be computed over a transient range. (`none` instead of `None` explicitly calls the transient-window function, but with the full range, for debugging.) (If not None, will also force atoms regardless of computeAtoms option.) t0Band, tauBand: int Search ranges for transient start-time t0 and duration tau. If >0, search t0 in (minStartTime,minStartTime+t0Band) and tau in (tauMin,2*Tsft+tauBand). If =0, only compute the continuous-wave Fstat with t0=minStartTime, tau=maxStartTime-minStartTime. tauMin: int Minimum transient duration to cover, defaults to 2*Tsft. dt0: int Grid resolution in transient start-time, defaults to Tsft. dtau: int Grid resolution in transient duration, defaults to Tsft. detectors : str Two-character references to the detectors for which to use data. Specify `None` for no constraint. For multiple detectors, separate by commas. minCoverFreq, maxCoverFreq : float The min and max cover frequency passed to lalpulsar.CreateFstatInput. For negative values, these will be used as offsets from the min/max frequency contained in the sftfilepattern. If either is `None`, the search_ranges argument is used to estimate them. If the automatic estimation fails and you do not have a good idea what to set these two options to, setting both to -0.5 will reproduce the default behaviour of PyFstat <=1.4 and may be a reasonably safe fallback in many cases. search_ranges: dict Dictionary of ranges in all search parameters, only used to estimate frequency band passed to lalpulsar.CreateFstatInput, if minCoverFreq, maxCoverFreq are not specified (==`None`). For actually running searches, grids/points will have to be passed separately to the .run() method. The entry for each parameter must be a list of length 1, 2 or 3: [single_value], [min,max] or [min,max,step]. injectSources : dict or str Either a dictionary of the signal parameters to inject, or a string pointing to a .cff file defining a signal. injectSqrtSX : float or list or str Single-sided PSD values for generating fake Gaussian noise on the fly. Single float or str value: use same for all IFOs. List or comma-separated string: must match len(detectors) and/or the data in sftfilepattern. Detectors will be paired to list elements following alphabetical order. assumeSqrtSX : float or list or str Don't estimate noise-floors but assume this (stationary) single-sided PSD. Single float or str value: use same for all IFOs. List or comma-separated string: must match len(detectors) and/or the data in sftfilepattern. Detectors will be paired to list elements following alphabetical order. If working with signal-only data, please set assumeSqrtSX=1 . SSBprec : int Flag to set the Solar System Barycentring (SSB) calculation in lalpulsar: 0=Newtonian, 1=relativistic, 2=relativistic optimised, 3=DMoff, 4=NO_SPIN RngMedWindow : int Running-Median window size for F-statistic noise normalization (number of SFT bins). tCWFstatMapVersion: str Choose between implementations of the transient F-statistic funcionality: standard `lal` implementation, `pycuda` for GPU version, and some others only for devel/debug. cudaDeviceName: str GPU name to be matched against drv.Device output, only for `tCWFstatMapVersion=pycuda`. computeAtoms: bool Request calculation of 'F-statistic atoms' regardless of transientWindowType. earth_ephem: str Earth ephemeris file path. If None, will check standard sources as per helper_functions.get_ephemeris_files(). sun_ephem: str Sun ephemeris file path. If None, will check standard sources as per helper_functions.get_ephemeris_files(). """ self._set_init_params_dict(locals()) self.set_ephemeris_files(earth_ephem, sun_ephem) self.init_computefstatistic() self.output_file_header = self.get_output_file_header() self.get_det_stat = self.get_fullycoherent_detstat def _get_SFTCatalog(self): """Load the SFTCatalog If sftfilepattern is specified, load the data. If not, attempt to create data on the fly. """ if hasattr(self, "SFTCatalog"): logging.info("Already have SFTCatalog.") return if self.sftfilepattern is None: logging.info("No sftfilepattern given, making fake SFTCatalog.") for k in ["minStartTime", "maxStartTime", "detectors"]: if getattr(self, k) is None: raise ValueError( "If sftfilepattern==None, you must provide" " '{}'.".format(k) ) C1 = getattr(self, "injectSources", None) is None C2 = getattr(self, "injectSqrtSX", None) is None C3 = getattr(self, "Tsft", None) is None if (C1 and C2) or C3: raise ValueError( "If sftfilepattern==None, you must specify Tsft and" " either one of injectSources or injectSqrtSX." ) SFTCatalog = lalpulsar.SFTCatalog() Toverlap = 0 self.detector_names = self.detectors.split(",") self.numDetectors = len(self.detector_names) detNames = lal.CreateStringVector(*[d for d in self.detector_names]) # MakeMultiTimestamps follows the same [minStartTime,maxStartTime) # convention as the SFT library, so we can pass Tspan like this Tspan = self.maxStartTime - self.minStartTime multiTimestamps = lalpulsar.MakeMultiTimestamps( self.minStartTime, Tspan, self.Tsft, Toverlap, detNames.length ) SFTCatalog = lalpulsar.MultiAddToFakeSFTCatalog( SFTCatalog, detNames, multiTimestamps ) self.SFTCatalog = SFTCatalog return logging.info("Initialising SFTCatalog from sftfilepattern.") constraints = lalpulsar.SFTConstraints() constr_str = [] if self.detectors: if "," in self.detectors: logging.warning( "Multiple-detector constraints not available," " using all available data." ) else: constraints.detector = self.detectors constr_str.append("detector=" + constraints.detector) if self.minStartTime: constraints.minStartTime = lal.LIGOTimeGPS(self.minStartTime) constr_str.append("minStartTime={}".format(self.minStartTime)) if self.maxStartTime: constraints.maxStartTime = lal.LIGOTimeGPS(self.maxStartTime) constr_str.append("maxStartTime={}".format(self.maxStartTime)) logging.info( "Loading data matching SFT file name pattern '{}'" " with constraints {}.".format(self.sftfilepattern, ", ".join(constr_str)) ) self.SFTCatalog = lalpulsar.SFTdataFind(self.sftfilepattern, constraints) Tsft_from_catalog = int(1.0 / self.SFTCatalog.data[0].header.deltaF) if Tsft_from_catalog != self.Tsft: logging.info( "Overwriting pre-set Tsft={:d} with {:d} obtained from SFTs.".format( self.Tsft, Tsft_from_catalog ) ) self.Tsft = Tsft_from_catalog # NOTE: in multi-IFO case, this will be a joint list of timestamps # over all IFOs, probably sorted and not cleaned for uniqueness. SFT_timestamps = [d.header.epoch for d in self.SFTCatalog.data] self.SFT_timestamps = [float(s) for s in SFT_timestamps] if len(SFT_timestamps) == 0: raise ValueError("Failed to load any data") if args.quite is False and args.no_interactive is False: try: from bashplotlib.histogram import plot_hist print("Data timestamps histogram:") plot_hist(SFT_timestamps, height=5, bincount=50) except ImportError: pass cl_tconv1 = "lalapps_tconvert {}".format(int(SFT_timestamps[0])) output = helper_functions.run_commandline(cl_tconv1, log_level=logging.DEBUG) tconvert1 = output.rstrip("\n") cl_tconv2 = "lalapps_tconvert {}".format(int(SFT_timestamps[-1])) output = helper_functions.run_commandline(cl_tconv2, log_level=logging.DEBUG) tconvert2 = output.rstrip("\n") logging.info( "Data contains SFT timestamps from {} ({}) to (including) {} ({})".format( int(SFT_timestamps[0]), tconvert1, int(SFT_timestamps[-1]), tconvert2 ) ) if self.minStartTime is None: self.minStartTime = int(SFT_timestamps[0]) if self.maxStartTime is None: # XLALCWGPSinRange() convention: half-open intervals, # maxStartTime must always be > last actual SFT timestamp self.maxStartTime = int(SFT_timestamps[-1]) + self.Tsft self.detector_names = list(set([d.header.name for d in self.SFTCatalog.data])) self.numDetectors = len(self.detector_names) if self.numDetectors == 0: raise ValueError("No data loaded.") logging.info( "Loaded {} SFTs from {} detectors: {}".format( len(SFT_timestamps), self.numDetectors, self.detector_names ) ) def init_computefstatistic(self): """Initialization step for the F-stastic computation internals. This sets up the special input and output structures the lalpulsar module needs, the ephemerides, optional on-the-fly signal injections, and extra options for multi-detector consistency checks and transient searches. All inputs are taken from the pre-initialized object, so this function does not have additional arguments of its own. """ self._get_SFTCatalog() logging.info("Initialising ephems") ephems = lalpulsar.InitBarycenter(self.earth_ephem, self.sun_ephem) logging.info("Initialising Fstat arguments") dFreq = 0 self.whatToCompute = lalpulsar.FSTATQ_2F if self.transientWindowType or self.computeAtoms: self.whatToCompute += lalpulsar.FSTATQ_ATOMS_PER_DET FstatOAs = lalpulsar.FstatOptionalArgs() FstatOAs.randSeed = lalpulsar.FstatOptionalArgsDefaults.randSeed if self.SSBprec: logging.info("Using SSBprec={}".format(self.SSBprec)) FstatOAs.SSBprec = self.SSBprec else: FstatOAs.SSBprec = lalpulsar.FstatOptionalArgsDefaults.SSBprec FstatOAs.Dterms = lalpulsar.FstatOptionalArgsDefaults.Dterms if self.RngMedWindow: FstatOAs.runningMedianWindow = self.RngMedWindow else: FstatOAs.runningMedianWindow = ( lalpulsar.FstatOptionalArgsDefaults.runningMedianWindow ) FstatOAs.FstatMethod = lalpulsar.FstatOptionalArgsDefaults.FstatMethod if self.assumeSqrtSX is None: FstatOAs.assumeSqrtSX = lalpulsar.FstatOptionalArgsDefaults.assumeSqrtSX else: mnf = lalpulsar.MultiNoiseFloor() assumeSqrtSX = helper_functions.parse_list_of_numbers(self.assumeSqrtSX) mnf.sqrtSn[: len(assumeSqrtSX)] = assumeSqrtSX mnf.length = len(assumeSqrtSX) FstatOAs.assumeSqrtSX = mnf FstatOAs.prevInput = lalpulsar.FstatOptionalArgsDefaults.prevInput FstatOAs.collectTiming = lalpulsar.FstatOptionalArgsDefaults.collectTiming if hasattr(self, "injectSources") and type(self.injectSources) == dict: logging.info("Injecting source with params: {}".format(self.injectSources)) PPV = lalpulsar.CreatePulsarParamsVector(1) PP = PPV.data[0] h0 = self.injectSources["h0"] cosi = self.injectSources["cosi"] use_aPlus = "aPlus" in dir(PP.Amp) print("use_aPlus = {}".format(use_aPlus)) if use_aPlus: # lalsuite interface changed in aff93c45 PP.Amp.aPlus = 0.5 * h0 * (1.0 + cosi ** 2) PP.Amp.aCross = h0 * cosi else: PP.Amp.h0 = h0 PP.Amp.cosi = cosi PP.Amp.phi0 = self.injectSources["phi"] PP.Amp.psi = self.injectSources["psi"] PP.Doppler.Alpha = self.injectSources["Alpha"] PP.Doppler.Delta = self.injectSources["Delta"] if "fkdot" in self.injectSources: PP.Doppler.fkdot = np.array(self.injectSources["fkdot"]) else: PP.Doppler.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) for i, key in enumerate(["F0", "F1", "F2"]): PP.Doppler.fkdot[i] = self.injectSources[key] PP.Doppler.refTime = self.tref if "t0" not in self.injectSources: PP.Transient.type = lalpulsar.TRANSIENT_NONE FstatOAs.injectSources = PPV elif hasattr(self, "injectSources") and type(self.injectSources) == str: logging.info( "Injecting source from param file: {}".format(self.injectSources) ) PPV = lalpulsar.PulsarParamsFromFile(self.injectSources, self.tref) FstatOAs.injectSources = PPV else: FstatOAs.injectSources = lalpulsar.FstatOptionalArgsDefaults.injectSources if hasattr(self, "injectSqrtSX") and self.injectSqrtSX is not None: self.injectSqrtSX = helper_functions.parse_list_of_numbers( self.injectSqrtSX ) if len(self.injectSqrtSX) != len(self.detector_names): raise ValueError( "injectSqrtSX must be of same length as detector_names ({}!={})".format( len(self.injectSqrtSX), len(self.detector_names) ) ) FstatOAs.injectSqrtSX = lalpulsar.MultiNoiseFloor() FstatOAs.injectSqrtSX.length = len(self.injectSqrtSX) FstatOAs.injectSqrtSX.sqrtSn[ : FstatOAs.injectSqrtSX.length ] = self.injectSqrtSX else: FstatOAs.injectSqrtSX = lalpulsar.FstatOptionalArgsDefaults.injectSqrtSX self._set_min_max_cover_freqs() logging.info("Initialising FstatInput") self.FstatInput = lalpulsar.CreateFstatInput( self.SFTCatalog, self.minCoverFreq, self.maxCoverFreq, dFreq, ephems, FstatOAs, ) logging.info("Initialising PulsarDoplerParams") PulsarDopplerParams = lalpulsar.PulsarDopplerParams() PulsarDopplerParams.refTime = self.tref PulsarDopplerParams.Alpha = 1 PulsarDopplerParams.Delta = 1 PulsarDopplerParams.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) self.PulsarDopplerParams = PulsarDopplerParams logging.info("Initialising FstatResults") self.FstatResults = lalpulsar.FstatResults() if self.BSGL: if len(self.detector_names) < 2: raise ValueError("Can't use BSGL with single detectors data") else: logging.info("Initialising BSGL") # Tuning parameters - to be reviewed # We use a fixed Fstar0 for coherent searches, # and recompute it from a fixed p-value for the semicoherent case. nsegs_eff = max([getattr(self, "nsegs", 1), getattr(self, "nglitch", 1)]) if nsegs_eff > 1: p_val_threshold = 1e-6 Fstar0s = np.linspace(0, 1000, 10000) p_vals = scipy.special.gammaincc(2 * nsegs_eff, Fstar0s) Fstar0 = Fstar0s[np.argmin(np.abs(p_vals - p_val_threshold))] if Fstar0 == Fstar0s[-1]: raise ValueError("Max Fstar0 exceeded") else: Fstar0 = 15.0 logging.info("Using Fstar0 of {:1.2f}".format(Fstar0)) # assume uniform per-detector prior line-vs-Gaussian odds oLGX = np.zeros(lalpulsar.PULSAR_MAX_DETECTORS) oLGX[: self.numDetectors] = 1.0 / self.numDetectors self.BSGLSetup = lalpulsar.CreateBSGLSetup( numDetectors=self.numDetectors, Fstar0sc=Fstar0, oLGX=oLGX, useLogCorrection=True, numSegments=getattr(self, "nsegs", 1), ) self.twoFX = np.zeros(lalpulsar.PULSAR_MAX_DETECTORS) self.whatToCompute += lalpulsar.FSTATQ_2F_PER_DET if self.transientWindowType: logging.info("Initialising transient parameters") self.windowRange = lalpulsar.transientWindowRange_t() transientWindowTypes = { "none": lalpulsar.TRANSIENT_NONE, "rect": lalpulsar.TRANSIENT_RECTANGULAR, "exp": lalpulsar.TRANSIENT_EXPONENTIAL, } if self.transientWindowType in transientWindowTypes: self.windowRange.type = transientWindowTypes[self.transientWindowType] else: raise ValueError( "Unknown window-type ({}) passed as input, [{}] allows.".format( self.transientWindowType, ", ".join(transientWindowTypes) ) ) # default spacing self.windowRange.dt0 = self.Tsft self.windowRange.dtau = self.Tsft # special treatment of window_type = none # ==> replace by rectangular window spanning all the data if self.windowRange.type == lalpulsar.TRANSIENT_NONE: self.windowRange.t0 = int(self.minStartTime) self.windowRange.t0Band = 0 self.windowRange.tau = int(self.maxStartTime - self.minStartTime) self.windowRange.tauBand = 0 else: # user-set bands and spacings if getattr(self, "t0Band", None) is None: self.windowRange.t0Band = 0 else: if not isinstance(self.t0Band, int): logging.warn( "Casting non-integer t0Band={} to int...".format( self.t0Band ) ) self.t0Band = int(self.t0Band) self.windowRange.t0Band = self.t0Band if self.dt0: self.windowRange.dt0 = self.dt0 if getattr(self, "tauBand", None) is None: self.windowRange.tauBand = 0 else: if not isinstance(self.tauBand, int): logging.warn( "Casting non-integer tauBand={} to int...".format( self.tauBand ) ) self.tauBand = int(self.tauBand) self.windowRange.tauBand = self.tauBand if self.dtau: self.windowRange.dtau = self.dtau if self.tauMin is None: self.windowRange.tau = int(2 * self.Tsft) else: if not isinstance(self.tauMin, int): logging.warn( "Casting non-integer tauMin={} to int...".format( self.tauMin ) ) self.tauMin = int(self.tauMin) self.windowRange.tau = self.tauMin logging.info("Initialising transient FstatMap features...") ( self.tCWFstatMapFeatures, self.gpu_context, ) = tcw.init_transient_fstat_map_features( self.tCWFstatMapVersion == "pycuda", self.cudaDeviceName ) if self.BSGL: self.twoFXatMaxTwoF = np.zeros(lalpulsar.PULSAR_MAX_DETECTORS) def _set_min_max_cover_freqs(self): # decide on which minCoverFreq and maxCoverFreq to use: # either from direct user input, estimate_min_max_CoverFreq(), or SFTs if self.sftfilepattern is not None: minFreq_SFTs, maxFreq_SFTs = self._get_min_max_freq_from_SFTCatalog() if (self.minCoverFreq is None) != (self.maxCoverFreq is None): raise ValueError( "Please use either both or none of [minCoverFreq,maxCoverFreq]." ) elif ( self.minCoverFreq is None and self.maxCoverFreq is None and self.search_ranges is None ): raise ValueError( "Please use either search_ranges or both of [minCoverFreq,maxCoverFreq]." ) elif self.minCoverFreq is None or self.maxCoverFreq is None: logging.info( "[minCoverFreq,maxCoverFreq] not provided, trying to estimate" " from search ranges." ) self.estimate_min_max_CoverFreq() elif (self.minCoverFreq < 0.0) or (self.maxCoverFreq < 0.0): if self.sftfilepattern is None: raise ValueError( "If sftfilepattern==None, cannot use negative values for" " minCoverFreq or maxCoverFreq (interpreted as offsets from" " min/max SFT frequency)." " Please use actual frequency values for both," " or set both to None (automated estimation)." ) if self.minCoverFreq < 0.0: logging.info( "minCoverFreq={:f} provided, using as offset from min(SFTs).".format( self.minCoverFreq ) ) # to set *above* min, since minCoverFreq is negative: subtract it self.minCoverFreq = minFreq_SFTs - self.minCoverFreq if self.maxCoverFreq < 0.0: logging.info( "maxCoverFreq={:f} provided, using as offset from max(SFTs).".format( self.maxCoverFreq ) ) # to set *below* max, since minCoverFreq is negative: add it self.maxCoverFreq = maxFreq_SFTs + self.maxCoverFreq if (self.sftfilepattern is not None) and ( (self.minCoverFreq < minFreq_SFTs) or (self.maxCoverFreq > maxFreq_SFTs) ): raise ValueError( "[minCoverFreq,maxCoverFreq]=[{:f},{:f}] Hz incompatible with" " SFT files content [{:f},{:f}] Hz".format( self.minCoverFreq, self.maxCoverFreq, minFreq_SFTs, maxFreq_SFTs ) ) logging.info( "Using minCoverFreq={} and maxCoverFreq={}.".format( self.minCoverFreq, self.maxCoverFreq ) ) def _get_min_max_freq_from_SFTCatalog(self): fAs = [d.header.f0 for d in self.SFTCatalog.data] minFreq_SFTs = np.min(fAs) fBs = [ d.header.f0 + (d.numBins - 1) * d.header.deltaF for d in self.SFTCatalog.data ] maxFreq_SFTs = np.max(fBs) return minFreq_SFTs, maxFreq_SFTs def estimate_min_max_CoverFreq(self): """Extract spanned spin-range at reference -time from the template bank. To use this method, self.search_ranges must be a dictionary of lists per search parameter which can be either [single_value], [min,max] or [min,max,step]. """ if type(self.search_ranges) is not dict: raise ValueError("Need a dictionary for search_ranges!") range_keys = list(self.search_ranges.keys()) required_keys = ["Alpha", "Delta", "F0"] if len(np.setdiff1d(required_keys, range_keys)) > 0: raise ValueError( "Required keys not found in search_ranges: {}".format( np.setdiff1d(required_keys, range_keys) ) ) for key in range_keys: if ( type(self.search_ranges[key]) is not list or len(self.search_ranges[key]) == 0 or len(self.search_ranges[key]) > 3 ): raise ValueError( "search_ranges entry for {:s}" " is not a list of a known format" " (either [single_value], [min,max]" " or [min,max,step]): {}".format(key, self.search_ranges[key]) ) # start by constructing a DopplerRegion structure # which will be needed to conservatively account for sky-position dependent # Doppler shifts of the frequency range to be covered searchRegion = lalpulsar.DopplerRegion() # sky region Alpha = self.search_ranges["Alpha"][0] AlphaBand = ( self.search_ranges["Alpha"][1] - Alpha if len(self.search_ranges["Alpha"]) >= 2 else 0.0 ) Delta = self.search_ranges["Delta"][0] DeltaBand = ( self.search_ranges["Delta"][1] - Delta if len(self.search_ranges["Delta"]) >= 2 else 0.0 ) searchRegion.skyRegionString = lalpulsar.SkySquare2String( Alpha, Delta, AlphaBand, DeltaBand, ) searchRegion.refTime = self.tref # frequency and spindowns searchRegion.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) searchRegion.fkdotBand = np.zeros(lalpulsar.PULSAR_MAX_SPINS) for k in range(3): Fk = "F{:d}".format(k) if Fk in range_keys: searchRegion.fkdot[k] = self.search_ranges[Fk][0] searchRegion.fkdotBand[k] = ( self.search_ranges[Fk][1] - self.search_ranges[Fk][0] if len(self.search_ranges[Fk]) >= 2 else 0.0 ) # now construct DopplerFullScan from searchRegion scanInit = lalpulsar.DopplerFullScanInit() scanInit.searchRegion = searchRegion scanInit.stepSizes = lalpulsar.PulsarDopplerParams() scanInit.stepSizes.refTime = self.tref scanInit.stepSizes.Alpha = ( self.search_ranges["Alpha"][-1] if len(self.search_ranges["Alpha"]) == 3 else 0.001 # fallback, irrelevant for band estimate but must be > 0 ) scanInit.stepSizes.Delta = ( self.search_ranges["Delta"][-1] if len(self.search_ranges["Delta"]) == 3 else 0.001 # fallback, irrelevant for band estimate but must be > 0 ) scanInit.stepSizes.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) for k in range(3): if Fk in range_keys: Fk = "F{:d}".format(k) scanInit.stepSizes.fkdot[k] = ( self.search_ranges[Fk][-1] if len(self.search_ranges[Fk]) == 3 else 0.0 ) scanInit.startTime = self.minStartTime scanInit.Tspan = float(self.maxStartTime - self.minStartTime) scanState = lalpulsar.InitDopplerFullScan(scanInit) # now obtain the PulsarSpinRange extended over all relevant Doppler shifts spinRangeRef = lalpulsar.PulsarSpinRange() lalpulsar.GetDopplerSpinRange(spinRangeRef, scanState) # optional: binary parameters if "asini" in range_keys: if len(self.search_ranges["asini"]) >= 2: maxOrbitAsini = self.search_ranges["asini"][1] else: maxOrbitAsini = self.search_ranges["asini"][0] else: maxOrbitAsini = 0.0 if "period" in range_keys: minOrbitPeriod = self.search_ranges["period"][0] else: minOrbitPeriod = 0.0 if "ecc" in range_keys: if len(self.search_ranges["ecc"]) >= 2: maxOrbitEcc = self.search_ranges["ecc"][1] else: maxOrbitEcc = self.search_ranges["ecc"][0] else: maxOrbitEcc = 0.0 # finally call the wrapped lalpulsar estimation function with the # extended PulsarSpinRange and optional binary parameters self.minCoverFreq, self.maxCoverFreq = helper_functions.get_covering_band( tref=self.tref, tstart=self.minStartTime, tend=self.maxStartTime, F0=spinRangeRef.fkdot[0], F1=spinRangeRef.fkdot[1], F2=spinRangeRef.fkdot[2], F0band=spinRangeRef.fkdotBand[0], F1band=spinRangeRef.fkdotBand[1], F2band=spinRangeRef.fkdotBand[2], maxOrbitAsini=maxOrbitAsini, minOrbitPeriod=minOrbitPeriod, maxOrbitEcc=maxOrbitEcc, ) def get_fullycoherent_detstat( self, F0, F1, F2, Alpha, Delta, asini=None, period=None, ecc=None, tp=None, argp=None, tstart=None, tend=None, ): """Computes the detection statistic (twoF or log10BSGL) fully-coherently at a single point. These are also stored to `self.twoF` and `self.log10BSGL` respectively. As the basic statistic of this class, `self.twoF` is always computed. If `self.BSGL`, additionally the single-detector 2F-stat values are saved in `self.twoFX`. If transient parameters are enabled (`self.transientWindowType` is set), the full transient-F-stat map will also be computed here, but stored in `self.FstatMap`, not returned. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the statistic. tstart, tend: int or None GPS times to restrict the range of data used. If None: falls back to self.minStartTime and self.maxStartTime. This is only passed on to `self.get_transient_detstat()`, i.e. only used if `self.transientWindowType` is set. Returns ------- stat: float A single value of the detection statistic (twoF or log10BSGL) at the input parameter values. Also stored as `self.twoF` or `self.log10BSGL`. """ self.get_fullycoherent_twoF( F0, F1, F2, Alpha, Delta, asini, period, ecc, tp, argp ) if not self.transientWindowType: if self.BSGL is False: return self.twoF self.get_fullycoherent_single_IFO_twoFs() self.get_fullycoherent_log10BSGL() return self.log10BSGL self.get_transient_maxTwoFstat(tstart, tend) if self.BSGL is False: return self.maxTwoF else: return self.get_transient_log10BSGL() def get_fullycoherent_twoF( self, F0, F1, F2, Alpha, Delta, asini=None, period=None, ecc=None, tp=None, argp=None, ): """Computes the fully-coherent 2F statistic at a single point. NOTE: This always uses the full data set as defined when initialising the search object. If you want to restrict the range of data used for a single 2F computation, you need to set a `self.transientWindowType` and then call `self.get_fullycoherent_detstat()` with `tstart` and `tend` options instead of this funcion. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the statistic. Returns ------- twoF: float A single value of the fully-coherent 2F statistic at the input parameter values. Also stored as `self.twoF`. """ self.PulsarDopplerParams.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) self.PulsarDopplerParams.fkdot[:3] = [F0, F1, F2] self.PulsarDopplerParams.Alpha = float(Alpha) self.PulsarDopplerParams.Delta = float(Delta) if self.binary: self.PulsarDopplerParams.asini = float(asini) self.PulsarDopplerParams.period = float(period) self.PulsarDopplerParams.ecc = float(ecc) self.PulsarDopplerParams.tp = float(tp) self.PulsarDopplerParams.argp = float(argp) lalpulsar.ComputeFstat( Fstats=self.FstatResults, input=self.FstatInput, doppler=self.PulsarDopplerParams, numFreqBins=1, whatToCompute=self.whatToCompute, ) # We operate on a single frequency bin, so we grab the 0 component # of what is internally a twoF array. self.twoF = np.float(self.FstatResults.twoF[0]) return self.twoF def get_fullycoherent_single_IFO_twoFs(self): """Computes single-detector F-stats at a single point. This requires `self.get_fullycoherent_twoF()` to be run first. Returns ------- twoFX: list A list of the single-detector detection statistics twoF. Also stored as `self.twoFX`. """ self.twoFX[: self.FstatResults.numDetectors] = [ self.FstatResults.twoFPerDet(X) for X in range(self.FstatResults.numDetectors) ] return self.twoFX def get_fullycoherent_log10BSGL(self): """Computes the line-robust statistic log10BSGL at a single point. This requires `self.get_fullycoherent_twoF()` and `self.get_fullycoherent_single_IFO_twoFs()` to be run first. Returns ------- log10BSGL: float A single value of the detection statistic log10BSGL at the input parameter values. Also stored as `self.log10BSGL`. """ self.log10BSGL = lalpulsar.ComputeBSGL(self.twoF, self.twoFX, self.BSGLSetup) return self.log10BSGL def get_transient_maxTwoFstat( self, tstart=None, tend=None, ): """Computes the transient maxTwoF statistic at a single point. This requires `self.get_fullycoherent_twoF()` to be run first. The full transient-F-stat map will also be computed here, but stored in `self.FstatMap`, not returned. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the statistic. tstart, tend: int or None GPS times to restrict the range of data used. If None: falls back to self.minStartTime and self.maxStartTime. This is only passed on to `self.get_transient_detstat()`, i.e. only used if `self.transientWindowType` is set. Returns ------- maxTwoF: float A single value of the detection statistic (twoF or log10BSGL) at the input parameter values. Also stored as `self.maxTwoF`. """ tstart = tstart or getattr(self, "minStartTime", None) tend = tend or getattr(self, "maxStartTime", None) if tstart is None or tend is None: raise ValueError( "Need tstart or self.minStartTime, and tend or self.maxStartTime!" ) self.windowRange.t0 = int(tstart) # TYPE UINT4 if self.windowRange.tauBand == 0: self.windowRange.tau = int(tend - tstart) # TYPE UINT4 self.FstatMap, self.timingFstatMap = tcw.call_compute_transient_fstat_map( self.tCWFstatMapVersion, self.tCWFstatMapFeatures, self.FstatResults.multiFatoms[0], # 0 index: single frequency bin self.windowRange, ) # Now instead of the overall twoF, # we get the maximum twoF over the transient window range. self.maxTwoF = 2 * self.FstatMap.maxF if np.isnan(self.maxTwoF): self.maxTwoF = 0 return self.maxTwoF def get_transient_log10BSGL(self): """Computes a transient detection statistic log10BSGL at a single point. This requires `self.get_transient_maxTwoFstat()` to be run first. The single-detector 2F-stat values used for that computation (at the index of `maxTwoF`) are saved in `self.twoFXatMaxTwoF`, not returned. Returns ------- log10BSGL: float A single value of the detection statistic log10BSGL at the input parameter values. Also stored as `self.log10BSGL`. """ # First, we need to also compute per-detector F_mn maps. # For now, we use the t0,tau index that maximises the multi-detector F # to return BSGL for a signal with those parameters. # FIXME: should we instead compute BSGL over the whole F_mn # and return the maximum of that? idx_maxTwoF = self.FstatMap.get_maxF_idx() for X in range(self.FstatResults.numDetectors): # For each detector, we need to build a MultiFstatAtomVector # because that's what the Fstat map function expects. singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1) # The first [0] index on the multiFatoms here is over frequency bins; # we always operate on a single bin. singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector( self.FstatResults.multiFatoms[0].data[X].length ) singleIFOmultiFatoms.data[0].TAtom = ( self.FstatResults.multiFatoms[0].data[X].TAtom ) singleIFOmultiFatoms.data[0].data = ( self.FstatResults.multiFatoms[0].data[X].data ) FXstatMap, timingFXstatMap = tcw.call_compute_transient_fstat_map( self.tCWFstatMapVersion, self.tCWFstatMapFeatures, singleIFOmultiFatoms, self.windowRange, ) self.twoFXatMaxTwoF[X] = 2 * FXstatMap.F_mn[idx_maxTwoF] self.log10BSGL = lalpulsar.ComputeBSGL( self.maxTwoF, self.twoFXatMaxTwoF, self.BSGLSetup ) return self.log10BSGL def _set_up_cumulative_times(self, tstart, tend, num_segments): """Construct time arrays to be used in cumulative twoF computations. This allows calculate_twoF_cumulative and predict_twoF_cumulative to use the same convention (although the number of segments on use is generally different due to the computing time required by predict_twoF_cumulative). First segment is hardcoded to spann 2 * self.Tsft. Last segment embraces the whole data stream. Parameters ---------- tstart, tend: int or None GPS times to restrict the range of data used; if None: falls back to self.minStartTime and self.maxStartTime; if outside those: auto-truncated num_segments: int Number of segments to split [tstart,tend] into """ tstart = max(tstart, self.minStartTime) if tstart else self.minStartTime tend = min(tend, self.maxStartTime) if tend else self.maxStartTime min_duration = 2 * self.Tsft max_duration = tend - tstart cumulative_durations = np.linspace(min_duration, max_duration, num_segments) return tstart, tend, cumulative_durations def calculate_twoF_cumulative( self, F0, F1, F2, Alpha, Delta, asini=None, period=None, ecc=None, tp=None, argp=None, tstart=None, tend=None, num_segments=1000, ): """Calculate the cumulative twoF over subsets of the observation span. This means that we consider sub-"segments" of the [tstart,tend] interval, each starting at the overall tstart and with increasing durations, and compute the 2F for each of these, which for a true CW signal should increase roughly with duration towards the full value. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the cumulative twoF. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the cumulative 2F. tstart, tend: int or None GPS times to restrict the range of data used. If None: falls back to self.minStartTime and self.maxStartTime;. If outside those: auto-truncated. num_segments: int Number of segments to split [tstart,tend] into. Returns ------- cumulative_durations : ndarray of shape (num_segments,) Offsets of each segment's tend from the overall tstart. twoFs : ndarray of shape (num_segments,) Values of twoF computed over [[tstart,tstart+duration] for duration in cumulative_durations]. """ reset_old_window = None if not self.transientWindowType: reset_old_window = self.transientWindowType self.transientWindowType = "rect" self.init_computefstatistic() tstart, tend, cumulative_durations = self._set_up_cumulative_times( tstart, tend, num_segments ) twoFs = [ self.get_fullycoherent_detstat( tstart=tstart, tend=tstart + duration, F0=F0, F1=F1, F2=F2, Alpha=Alpha, Delta=Delta, asini=asini, period=period, ecc=ecc, tp=tp, argp=argp, ) for duration in cumulative_durations ] if reset_old_window is not None: self.transientWindowType = reset_old_window self.init_computefstatistic() return tstart, cumulative_durations, np.array(twoFs) def predict_twoF_cumulative( self, F0, Alpha, Delta, h0, cosi, psi, tstart=None, tend=None, num_segments=10, **predict_fstat_kwargs, ): """Calculate expected 2F, with uncertainty, over subsets of the observation span. This yields the expected behaviour that calculate_twoF_cumulative() can be compared against: 2F for CW signals increases with duration as we take longer and longer subsets of the total observation span. Parameters ---------- F0, Alpha, Delta, h0, cosi, psi: float Parameters at which to compute the cumulative predicted twoF. tstart, tend: int or None GPS times to restrict the range of data used. If None: falls back to self.minStartTime and self.maxStartTime. If outside those: auto-truncated. num_segments: int Number of segments to split [tstart,tend] into. predict_fstat_kwargs: Other kwargs to be passed to helper_functions.predict_fstat(). Returns ------- tstart: int GPS start time of the observation span. cumulative_durations: ndarray of shape (num_segments,) Offsets of each segment's tend from the overall tstart. pfs: ndarray of size (num_segments,) Predicted 2F for each segment. pfs_sigma: ndarray of size (num_segments,) Standard deviations of predicted 2F. """ tstart, tend, cumulative_durations = self._set_up_cumulative_times( tstart, tend, num_segments ) out = [ helper_functions.predict_fstat( minStartTime=tstart, duration=duration, sftfilepattern=self.sftfilepattern, h0=h0, cosi=cosi, psi=psi, Alpha=Alpha, Delta=Delta, F0=F0, **predict_fstat_kwargs, ) for duration in cumulative_durations ] pfs, pfs_sigma = np.array(out).T return tstart, cumulative_durations, pfs, pfs_sigma def plot_twoF_cumulative( self, CFS_input, PFS_input=None, tstart=None, tend=None, num_segments_CFS=1000, num_segments_PFS=10, custom_ax_kwargs=None, savefig=False, label=None, outdir=None, **PFS_kwargs, ): """Plot how 2F accumulates over time. This compares the accumulation on the actual data set ('CFS', from self.calculate_twoF_cumulative()) against (optionally) the average expectation ('PFS', from self.predict_twoF_cumulative()). Parameters ---------- CFS_input: dict Input arguments for self.calculate_twoF_cumulative() (besides [tstart, tend, num_segments]). PFS_input: dict Input arguments for self.predict_twoF_cumulative() (besides [tstart, tend, num_segments]). If None: do not calculate predicted 2F. tstart, tend: int or None GPS times to restrict the range of data used. If None: falls back to self.minStartTime and self.maxStartTime. If outside those: auto-truncated. num_segments_(CFS|PFS) : int Number of time segments to (compute|predict) twoF. custom_ax_kwargs : dict Optional axis formatting options. savefig : bool If true, save the figure in `outdir`. If false, return an axis object without saving to disk. label: str Output filename will be constructed by appending `_twoFcumulative.png` to this label. (Ignored unless `savefig=true`.) outdir: str Output folder (ignored unless `savefig=true`). PFS_kwargs: dict Other kwargs to be passed to self.predict_twoF_cumulative(). Returns ------- ax : matplotlib.axes._subplots_AxesSubplot, optional The axes object containing the plot. """ # Compute cumulative twoF actual_tstart_CFS, taus_CFS, twoFs = self.calculate_twoF_cumulative( tstart=tstart, tend=tend, num_segments=num_segments_CFS, **CFS_input, ) taus_CFS_days = taus_CFS / 86400.0 # Set up plot-related objects axis_kwargs = { "xlabel": f"Days from $t_\\mathrm{{start}}={actual_tstart_CFS:.0f}$", "ylabel": "$\\log_{10}(\\mathrm{BSGL})_{\\mathrm{cumulative}$" if self.BSGL else "$\\widetilde{2\\mathcal{F}}_{\\mathrm{cumulative}}$", "xlim": (0, taus_CFS_days[-1]), } plot_label = ( f"Cumulative 2F {num_segments_CFS:d} segments" f" ({(taus_CFS_days[1] - taus_CFS_days[0]):.2g} days per segment)" ) if custom_ax_kwargs is not None: for kwarg in "xlabel", "ylabel": if kwarg in custom_ax_kwargs: logging.warning( f"Be careful, overwriting {kwarg} {axis_kwargs[kwarg]}" " with {custom_ax_kwargs[kwarg]}: Check out the units!" ) axis_kwargs.update(custom_ax_kwargs or {}) plot_label = custom_ax_kwargs.pop("label", plot_label) fig, ax = plt.subplots() ax.grid() ax.set(**axis_kwargs) ax.plot(taus_CFS_days, twoFs, label=plot_label, color="k") # Predict cumulative twoF and plot if required if PFS_input is not None: actual_tstart_PFS, taus_PFS, pfs, pfs_sigma = self.predict_twoF_cumulative( tstart=tstart, tend=tend, num_segments=num_segments_PFS, **PFS_input, **PFS_kwargs, ) taus_PFS_days = taus_PFS / 86400.0 assert actual_tstart_CFS == actual_tstart_PFS, ( "CFS and PFS starting time differs: This shouldn't be the case. " "Did you change conventions?" ) ax.fill_between( taus_PFS_days, pfs - pfs_sigma, pfs + pfs_sigma, color="cyan", label=( "Predicted $\\langle 2\\mathcal{F} \\rangle \\pm 1\\sigma$ band" ), zorder=-10, alpha=0.2, ) ax.legend(loc="best") if savefig: plt.tight_layout() plt.savefig(os.path.join(outdir, label + "_twoFcumulative.png")) plt.close() return ax def write_atoms_to_file(self, fnamebase=""): """Save F-statistic atoms (time-dependent quantities) for a given parameter-space point. Parameters ---------- fnamebase: str Basis for output filename, full name will be `{fnamebase}_Fstatatoms_{dopplerName}.dat` where `dopplerName` is a canonical lalpulsar formatting of the 'Doppler' parameter space point (frequency-evolution parameters). """ multiFatoms = getattr(self.FstatResults, "multiFatoms", None) if multiFatoms and multiFatoms[0]: dopplerName = lalpulsar.PulsarDopplerParams2String(self.PulsarDopplerParams) # fnameAtoms = os.path.join(self.outdir,'Fstatatoms_%s.dat' % dopplerName) fnameAtoms = f"{fnamebase}_Fstatatoms_{dopplerName}.dat" fo = lal.FileOpen(fnameAtoms, "w") for hline in self.output_file_header: lal.FilePuts(f"# {hline}\n", fo) lalpulsar.write_MultiFstatAtoms_to_fp(fo, multiFatoms[0]) del fo # instead of lal.FileClose() which is not SWIG-exported else: raise RuntimeError( "Cannot print atoms vector to file: no FstatResults.multiFatoms, or it is None!" ) def __del__(self): """In pyCuda case without autoinit, make sure the context is removed at the end.""" if hasattr(self, "gpu_context") and self.gpu_context: self.gpu_context.detach() class SemiCoherentSearch(ComputeFstat): """A simple semi-coherent search class. This will split the data set into multiple segments, run a coherent F-stat search over each, and produce a final semi-coherent detection statistic as the sum over segments. This does not include any concept of refinement between the two steps, as some grid-based semi-coherent search algorithms do; both the per-segment coherent F-statistics and the incoherent sum are done at the same parameter space point. The implementation is based on a simple trick using the transient F-stat map functionality: basic F-stat atoms are computed only once over the full data set, then the transient code with rectangular 'windows' is used to compute the per-segment F-stats, and these are summed to get the semi-coherent result. """ @helper_functions.initializer def __init__( self, label, outdir, tref, nsegs=None, sftfilepattern=None, binary=False, BSGL=False, minStartTime=None, maxStartTime=None, Tsft=1800, minCoverFreq=None, maxCoverFreq=None, search_ranges=None, detectors=None, injectSources=None, assumeSqrtSX=None, SSBprec=None, RngMedWindow=None, earth_ephem=None, sun_ephem=None, ): """ Only parameters with a special meaning for SemiCoherentSearch itself are explicitly documented here. For all other parameters inherited from pyfstat.ComputeFStat see the documentation of that class. Parameters ---------- label, outdir: str A label and directory to read/write data from/to. tref: int GPS seconds of the reference time. nsegs: int The (fixed) number of segments to split the data set into. sftfilepattern: str Pattern to match SFTs using wildcards (`*?`) and ranges [0-9]; multiple patterns can be given separated by colons. minStartTime, maxStartTime : int Only use SFTs with timestamps starting from this range, following the XLALCWGPSinRange convention: half-open intervals [minStartTime,maxStartTime]. Also used to set up segment boundaries, i.e. `maxStartTime-minStartTime` will be divided by `nsegs` to obtain the per-segment coherence time `Tcoh`. """ self.set_ephemeris_files(earth_ephem, sun_ephem) self.transientWindowType = None # will use semicoherentWindowRange instead self.computeAtoms = True # for semicoh 2F from ComputeTransientFstatMap() self.tCWFstatMapVersion = "lal" self.cudaDeviceName = None self.init_computefstatistic() self.init_semicoherent_parameters() if self.BSGL: self.twoFX_per_segment = np.zeros( (lalpulsar.PULSAR_MAX_DETECTORS, self.nsegs) ) self.get_det_stat = self.get_semicoherent_det_stat def _init_semicoherent_window_range(self): """ Use this window to compute the semicoherent Fstat using TransientFstatMaps. This way we are able to decouple the semicoherent computation from the actual usage of a transient window. """ self.semicoherentWindowRange = lalpulsar.transientWindowRange_t() self.semicoherentWindowRange.type = lalpulsar.TRANSIENT_RECTANGULAR # Range [t0, t0+t0Band] step dt0 self.semicoherentWindowRange.t0 = int(self.tboundaries[0]) self.semicoherentWindowRange.t0Band = int( self.tboundaries[-1] - self.tboundaries[0] - self.Tcoh ) self.semicoherentWindowRange.dt0 = int(self.Tcoh) # Range [tau, tau + tauBand] step dtau # Watch out: dtau must be !=0, but tauBand==0 is allowed self.semicoherentWindowRange.tau = int(self.Tcoh) self.semicoherentWindowRange.tauBand = int(0) self.semicoherentWindowRange.dtau = int(1) # Irrelevant def init_semicoherent_parameters(self): """Set up a list of equal-length segments and the corresponding transient windows. For a requested number of segments `self.nsegs`, `self.tboundaries` will have `self.nsegs+1` entries covering `[self.minStartTime,self.maxStartTime]` and `self.Tcoh` will be the total duration divided by `self.nsegs`. Each segment is required to be at least two SFTs long.f """ logging.info( ( "Initialising semicoherent parameters from" " minStartTime={:d} to maxStartTime={:d} in {:d} segments..." ).format(self.minStartTime, self.maxStartTime, self.nsegs) ) self.tboundaries = np.linspace( self.minStartTime, self.maxStartTime, self.nsegs + 1 ) self.Tcoh = self.tboundaries[1] - self.tboundaries[0] logging.info( ("Obtained {:d} segments of length Tcoh={:f}s (={:f}d).").format( self.nsegs, self.Tcoh, self.Tcoh / 86400.0 ) ) logging.debug("Segment boundaries: {}".format(self.tboundaries)) if self.Tcoh < 2 * self.Tsft: raise RuntimeError( "Per-segment coherent time {} may not be < Tsft={}" " to avoid degenerate F-statistic computations".format( self.Tcoh, self.Tsft ) ) # FIXME: We can only easily do the next sanity check for a single # detector, since self.SFT_timestamps is a joint list for multi-IFO case # and the lower-level error checking of XLAL is complicated in that case. # But even in the multi-IFO case, if the last segment does not include # enough data, there will still be an error message (just uglier) from # XLALComputeTransientFstatMap() if ( (len(self.detector_names) == 1) and hasattr(self, "SFT_timestamps") and (self.tboundaries[-2] > self.SFT_timestamps[-2]) ): raise RuntimeError( "Each segment must contain at least 2 SFTs to avoid degenerate" " F-statistic computations, but last segment start time {}" " is after second-to-last SFT timestamp {}.".format( self.tboundaries[-2], self.SFT_timestamps[-2] ) ) self._init_semicoherent_window_range() def get_semicoherent_det_stat( self, F0, F1, F2, Alpha, Delta, asini=None, period=None, ecc=None, tp=None, argp=None, record_segments=False, ): """Computes the detection statistic (twoF or log10BSGL) semi-coherently at a single point. As the basic statistic of this class, `self.twoF` is always computed. If `self.BSGL`, additionally the single-detector 2F-stat values are saved in `self.twoFX`. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the statistic. record_segments: boolean If True, store the per-segment F-stat values as `self.twoF_per_segment` and (if `self.BSGL=True`) the per-detector per-segment F-stats as `self.twoFX_per_segment`. Returns ------- stat: float A single value of the detection statistic (semi-coherent twoF or log10BSGL) at the input parameter values. Also stored as `self.twoF` or `self.log10BSGL`. """ self.get_semicoherent_twoF( F0, F1, F2, Alpha, Delta, asini, period, ecc, tp, argp, record_segments ) if self.BSGL is False: return self.twoF else: self.get_semicoherent_single_IFO_twoFs(record_segments) return self.get_semicoherent_log10BSGL() def get_semicoherent_twoF( self, F0, F1, F2, Alpha, Delta, asini=None, period=None, ecc=None, tp=None, argp=None, record_segments=False, ): """Computes the semi-coherent twoF statistic at a single point. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. asini, period, ecc, tp, argp: float, optional Optional: Binary parameters at which to compute the statistic. record_segments: boolean If True, store the per-segment F-stat values as `self.twoF_per_segment`. Returns ------- twoF: float A single value of the semi-coherent twoF statistic at the input parameter values. Also stored as `self.twoF`. """ self.PulsarDopplerParams.fkdot = np.zeros(lalpulsar.PULSAR_MAX_SPINS) self.PulsarDopplerParams.fkdot[:3] = [F0, F1, F2] self.PulsarDopplerParams.Alpha = float(Alpha) self.PulsarDopplerParams.Delta = float(Delta) if self.binary: self.PulsarDopplerParams.asini = float(asini) self.PulsarDopplerParams.period = float(period) self.PulsarDopplerParams.ecc = float(ecc) self.PulsarDopplerParams.tp = float(tp) self.PulsarDopplerParams.argp = float(argp) lalpulsar.ComputeFstat( Fstats=self.FstatResults, input=self.FstatInput, doppler=self.PulsarDopplerParams, numFreqBins=1, whatToCompute=self.whatToCompute, ) twoF_per_segment = self._get_per_segment_twoF() self.twoF = twoF_per_segment.sum() if np.isnan(self.twoF): logging.debug( "NaNs in per-segment 2F treated as zero" " and semi-coherent 2F re-computed." ) twoF_per_segment = np.nan_to_num(twoF_per_segment, nan=0.0) self.twoF = twoF_per_segment.sum() if record_segments: self.twoF_per_segment = twoF_per_segment def get_semicoherent_single_IFO_twoFs(self, record_segments=False): """Computes the semi-coherent single-detector F-statss at a single point. This requires `self.get_semicoherent_twoF()` to be run first. Parameters ---------- record_segments: boolean If True, store the per-detector per-segment F-stat values as `self.twoFX_per_segment`. Returns ------- twoFX: list A list of the single-detector detection statistics twoF. Also stored as `self.twoFX`. """ for X in range(self.FstatResults.numDetectors): # For each detector, we need to build a MultiFstatAtomVector # because that's what the Fstat map function expects. singleIFOmultiFatoms = lalpulsar.CreateMultiFstatAtomVector(1) # The first [0] index on the multiFatoms here is over frequency bins; # we always operate on a single bin. singleIFOmultiFatoms.data[0] = lalpulsar.CreateFstatAtomVector( self.FstatResults.multiFatoms[0].data[X].length ) singleIFOmultiFatoms.data[0].TAtom = ( self.FstatResults.multiFatoms[0].data[X].TAtom ) singleIFOmultiFatoms.data[0].data = ( self.FstatResults.multiFatoms[0].data[X].data ) FXstatMap = lalpulsar.ComputeTransientFstatMap( multiFstatAtoms=singleIFOmultiFatoms, windowRange=self.semicoherentWindowRange, useFReg=False, ) twoFX_per_segment = 2 * FXstatMap.F_mn.data[:, 0] self.twoFX[X] = twoFX_per_segment.sum() if np.isnan(self.twoFX[X]): logging.debug( "NaNs in per-segment per-detector 2F treated as zero" " and sum re-computed." ) twoFX_per_segment = np.nan_to_num(twoFX_per_segment, nan=0.0) self.twoFX[X] = twoFX_per_segment.sum() if record_segments: self.twoFX_per_segment[ : self.FstatResults.numDetectors, : ] = twoFX_per_segment return self.twoFX def get_semicoherent_log10BSGL(self): """Computes the semi-coherent log10BSGL statistic at a single point. This requires `self.get_semicoherent_twoF()` and `self.get_semicoherent_single_IFO_twoFs()` to be run first. Returns ------- log10BSGL: float A single value of the semi-coherent log10BSGL statistic at the input parameter values. Also stored as `self.log10BSGL`. """ self.log10BSGL = lalpulsar.ComputeBSGL(self.twoF, self.twoFX, self.BSGLSetup) if np.isnan(self.log10BSGL): logging.debug("NaNs in semi-coherent log10BSGL treated as zero") self.log10BSGL = 0.0 return self.log10BSGL def _get_per_segment_twoF(self): Fmap = lalpulsar.ComputeTransientFstatMap( multiFstatAtoms=self.FstatResults.multiFatoms[0], windowRange=self.semicoherentWindowRange, useFReg=False, ) twoF = 2 * Fmap.F_mn.data[:, 0] return twoF class SearchForSignalWithJumps(BaseSearchClass): """Internal helper class with some useful methods for glitches or timing noise. Users should never need to interact with this class, just with the derived search classes. """ def _shift_matrix(self, n, dT): """Generate the shift matrix Parameters ---------- n : int The dimension of the shift-matrix to generate dT : float The time delta of the shift matrix Returns ------- m : ndarray, shape (n,) The shift matrix. """ m = np.zeros((n, n)) factorial = np.math.factorial for i in range(n): for j in range(n): if i == j: m[i, j] = 1.0 elif i > j: m[i, j] = 0.0 else: if i == 0: m[i, j] = 2 * np.pi * float(dT) ** (j - i) / factorial(j - i) else: m[i, j] = float(dT) ** (j - i) / factorial(j - i) return m def _shift_coefficients(self, theta, dT): """Shift a set of coefficients by dT Parameters ---------- theta : array-like, shape (n,) Vector of the expansion coefficients to transform starting from the lowest degree e.g [phi, F0, F1,...]. dT : float Difference between the two reference times as tref_new - tref_old. Returns ------- theta_new : ndarray, shape (n,) Vector of the coefficients as evaluated as the new reference time. """ n = len(theta) m = self._shift_matrix(n, dT) return np.dot(m, theta) def _calculate_thetas(self, theta, delta_thetas, tbounds, theta0_idx=0): """Calculates the set of thetas given delta_thetas, the jumps This is used when generating data containing glitches or timing noise. Specifically, the source parameters of the signal are not constant in time, but jump by `delta_theta` at `tbounds`. Parameters ---------- theta : array_like The source parameters of size (n,). delta_thetas : array_like The jumps in the source parameters of size (m, n) where m is the number of jumps. tbounds : array_like Time boundaries of the jumps of size (m+2,). theta0_idx : int Index of the segment for which the theta are defined. Returns ------- ndarray The set of thetas, shape (m+1, n). """ thetas = [theta] for i, dt in enumerate(delta_thetas): if i < theta0_idx: pre_theta_at_ith_glitch = self._shift_coefficients( thetas[0], tbounds[i + 1] - self.tref ) post_theta_at_ith_glitch = pre_theta_at_ith_glitch - dt thetas.insert( 0, self._shift_coefficients( post_theta_at_ith_glitch, self.tref - tbounds[i + 1] ), ) elif i >= theta0_idx: pre_theta_at_ith_glitch = self._shift_coefficients( thetas[i], tbounds[i + 1] - self.tref ) post_theta_at_ith_glitch = pre_theta_at_ith_glitch + dt thetas.append( self._shift_coefficients( post_theta_at_ith_glitch, self.tref - tbounds[i + 1] ) ) self.thetas_at_tref = thetas return thetas class SemiCoherentGlitchSearch(SearchForSignalWithJumps, ComputeFstat): """A semi-coherent search for CW signals from sources with timing glitches. This implements a basic semi-coherent F-stat search in which the data is divided into segments either side of the proposed glitch epochs and the fully-coherent F-stat in each segment is summed to give the semi-coherent F-stat. """ @helper_functions.initializer def __init__( self, label, outdir, tref, minStartTime, maxStartTime, Tsft=1800, nglitch=1, sftfilepattern=None, theta0_idx=0, BSGL=False, minCoverFreq=None, maxCoverFreq=None, search_ranges=None, assumeSqrtSX=None, detectors=None, SSBprec=None, RngMedWindow=None, injectSources=None, earth_ephem=None, sun_ephem=None, ): """ Only parameters with a special meaning for SemiCoherentGlitchSearch itself are explicitly documented here. For all other parameters inherited from pyfstat.ComputeFStat see the documentation of that class. Parameters ---------- label, outdir: str A label and directory to read/write data from/to. tref, minStartTime, maxStartTime: int GPS seconds of the reference time, and start and end of the data. nglitch: int The (fixed) number of glitches. This is also allowed to be zero, but occasionally this causes issues, in which case please use the basic ComputeFstat class instead. sftfilepattern: str Pattern to match SFTs using wildcards (`*?`) and ranges [0-9]; multiple patterns can be given separated by colons. theta0_idx: int Index (zero-based) of which segment the theta (searched parameters) refer to. This is useful if providing a tight prior on theta to allow the signal to jump to theta (and not just from). """ if self.BSGL: raise ValueError( f"BSGL option currently not supported by {self.__class__.__name__}." ) self.set_ephemeris_files(earth_ephem, sun_ephem) self.transientWindowType = "rect" self.t0Band = None self.tauBand = None self.tCWFstatMapVersion = "lal" self.cudaDeviceName = None self.binary = False self.init_computefstatistic() self.get_det_stat = self.get_semicoherent_nglitch_twoF def get_semicoherent_nglitch_twoF(self, F0, F1, F2, Alpha, Delta, *args): """Returns the semi-coherent glitch summed twoF. Parameters ---------- F0, F1, F2, Alpha, Delta: float Parameters at which to compute the statistic. args: dict Additional arguments for the glitch parameters; see the source code for full details. Returns ------- twoFSum: float A single value of the semi-coherent summed detection statistic at the input parameter values. """ args = list(args) tboundaries = [self.minStartTime] + args[-self.nglitch :] + [self.maxStartTime] delta_F0s = args[-3 * self.nglitch : -2 * self.nglitch] delta_F1s = args[-2 * self.nglitch : -self.nglitch] delta_F2 = np.zeros(len(delta_F0s)) delta_phi = np.zeros(len(delta_F0s)) theta = [0, F0, F1, F2] delta_thetas = np.atleast_2d( np.array([delta_phi, delta_F0s, delta_F1s, delta_F2]).T ) thetas = self._calculate_thetas( theta, delta_thetas, tboundaries, theta0_idx=self.theta0_idx ) twoFSum = 0 for i, theta_i_at_tref in enumerate(thetas): ts, te = tboundaries[i], tboundaries[i + 1] if te - ts > 1800: twoFVal = self.get_fullycoherent_detstat( F0=theta_i_at_tref[1], F1=theta_i_at_tref[2], F2=theta_i_at_tref[3], Alpha=Alpha, Delta=Delta, tstart=ts, tend=te, ) twoFSum += twoFVal if np.isfinite(twoFSum): return twoFSum else: return -np.inf def compute_glitch_fstat_single( self, F0, F1, F2, Alpha, Delta, delta_F0, delta_F1, tglitch ): """Returns the semi-coherent glitch summed twoF for nglitch=1. NOTE: OBSOLETE, used only for testing. """ theta = [F0, F1, F2] delta_theta = [delta_F0, delta_F1, 0] tref = self.tref theta_at_glitch = self._shift_coefficients(theta, tglitch - tref) theta_post_glitch_at_glitch = theta_at_glitch + delta_theta theta_post_glitch = self._shift_coefficients( theta_post_glitch_at_glitch, tref - tglitch ) twoFsegA = self.get_fullycoherent_detstat( F0=theta[0], F1=theta[1], F2=theta[2], Alpha=Alpha, Delta=Delta, tstart=self.minStartTime, tend=tglitch, ) if tglitch == self.maxStartTime: return twoFsegA twoFsegB = self.get_fullycoherent_detstat( F0=theta_post_glitch[0], F1=theta_post_glitch[1], F2=theta_post_glitch[2], Alpha=Alpha, Delta=Delta, tstart=tglitch, tend=self.maxStartTime, ) return twoFsegA + twoFsegB class DeprecatedClass: """Outdated classes are marked for future removal by inheriting from this.""" def __new__(cls, *args, **kwargs): logging.warning( f"The {cls.__name__} class is no longer maintained" " and will be removed in an upcoming release of PyFstat!" " If you rely on this class and/or are interested in taking over" " maintenance, please report an issue at:" " https://github.com/PyFstat/PyFstat/issues", ) return super().__new__(cls, *args, **kwargs) class DefunctClass: """Removed classes are retained for a while but marked by inheriting from this.""" last_supported_version = None pr_welcome = True def __new__(cls, *args, **kwargs): defunct_message = f"The {cls.__name__} class is no longer included in PyFstat!" if cls.last_supported_version: defunct_message += ( f" Last supported version was {cls.last_supported_version}." ) if cls.pr_welcome: defunct_message += " Pull requests to reinstate the class are welcome." raise NotImplementedError(defunct_message)
[ "logging.getLogger", "logging.debug", "lalpulsar.DopplerRegion", "lalpulsar.write_MultiFstatAtoms_to_fp", "lalpulsar.MultiNoiseFloor", "numpy.array", "numpy.isfinite", "lalpulsar.ComputeBSGL", "pyfstat.tcw_fstat_map_funcs.init_transient_fstat_map_features", "lalpulsar.PulsarDopplerParams2String", ...
[((720, 765), 'pyfstat.helper_functions.set_up_matplotlib_defaults', 'helper_functions.set_up_matplotlib_defaults', ([], {}), '()\n', (763, 765), True, 'import pyfstat.helper_functions as helper_functions\n'), ((779, 827), 'pyfstat.helper_functions.set_up_command_line_arguments', 'helper_functions.set_up_command_line_arguments', ([], {}), '()\n', (825, 827), True, 'import pyfstat.helper_functions as helper_functions\n'), ((477, 627), 'logging.info', 'logging.info', (['"""No $DISPLAY environment variable found, so importing matplotlib.pyplot with non-interactive "Agg" backend."""'], {}), '(\n \'No $DISPLAY environment variable found, so importing matplotlib.pyplot with non-interactive "Agg" backend.\'\n )\n', (489, 627), False, 'import logging\n'), ((661, 682), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (675, 682), False, 'import matplotlib\n'), ((1196, 1246), 'logging.info', 'logging.info', (['f"""Creating {cls.__name__} object..."""'], {}), "(f'Creating {cls.__name__} object...')\n", (1208, 1246), False, 'import logging\n'), ((1504, 1550), 'os.path.join', 'os.path.join', (['self.outdir', "(self.label + '.log')"], {}), "(self.outdir, self.label + '.log')\n", (1516, 1550), False, 'import os\n'), ((1691, 1723), 'logging.FileHandler', 'logging.FileHandler', (['logfilename'], {}), '(logfilename)\n', (1710, 1723), False, 'import logging\n'), ((3045, 3083), 'pyfstat.helper_functions.get_ephemeris_files', 'helper_functions.get_ephemeris_files', ([], {}), '()\n', (3081, 3083), True, 'import pyfstat.helper_functions as helper_functions\n'), ((5055, 5108), 'lal.VCSInfoString', 'lal.VCSInfoString', (['lalpulsar.PulsarVCSInfoList', '(0)', '""""""'], {}), "(lalpulsar.PulsarVCSInfoList, 0, '')\n", (5072, 5108), False, 'import lal\n'), ((17472, 17532), 'logging.info', 'logging.info', (['"""Initialising SFTCatalog from sftfilepattern."""'], {}), "('Initialising SFTCatalog from sftfilepattern.')\n", (17484, 17532), False, 'import logging\n'), ((17555, 17581), 'lalpulsar.SFTConstraints', 'lalpulsar.SFTConstraints', ([], {}), '()\n', (17579, 17581), False, 'import lalpulsar\n'), ((18546, 18601), 'lalpulsar.SFTdataFind', 'lalpulsar.SFTdataFind', (['self.sftfilepattern', 'constraints'], {}), '(self.sftfilepattern, constraints)\n', (18567, 18601), False, 'import lalpulsar\n'), ((19736, 19804), 'pyfstat.helper_functions.run_commandline', 'helper_functions.run_commandline', (['cl_tconv1'], {'log_level': 'logging.DEBUG'}), '(cl_tconv1, log_level=logging.DEBUG)\n', (19768, 19804), True, 'import pyfstat.helper_functions as helper_functions\n'), ((19936, 20004), 'pyfstat.helper_functions.run_commandline', 'helper_functions.run_commandline', (['cl_tconv2'], {'log_level': 'logging.DEBUG'}), '(cl_tconv2, log_level=logging.DEBUG)\n', (19968, 20004), True, 'import pyfstat.helper_functions as helper_functions\n'), ((21554, 21589), 'logging.info', 'logging.info', (['"""Initialising ephems"""'], {}), "('Initialising ephems')\n", (21566, 21589), False, 'import logging\n'), ((21607, 21665), 'lalpulsar.InitBarycenter', 'lalpulsar.InitBarycenter', (['self.earth_ephem', 'self.sun_ephem'], {}), '(self.earth_ephem, self.sun_ephem)\n', (21631, 21665), False, 'import lalpulsar\n'), ((21675, 21719), 'logging.info', 'logging.info', (['"""Initialising Fstat arguments"""'], {}), "('Initialising Fstat arguments')\n", (21687, 21719), False, 'import logging\n'), ((21930, 21959), 'lalpulsar.FstatOptionalArgs', 'lalpulsar.FstatOptionalArgs', ([], {}), '()\n', (21957, 21959), False, 'import lalpulsar\n'), ((25985, 26024), 'logging.info', 'logging.info', (['"""Initialising FstatInput"""'], {}), "('Initialising FstatInput')\n", (25997, 26024), False, 'import logging\n'), ((26051, 26162), 'lalpulsar.CreateFstatInput', 'lalpulsar.CreateFstatInput', (['self.SFTCatalog', 'self.minCoverFreq', 'self.maxCoverFreq', 'dFreq', 'ephems', 'FstatOAs'], {}), '(self.SFTCatalog, self.minCoverFreq, self.\n maxCoverFreq, dFreq, ephems, FstatOAs)\n', (26077, 26162), False, 'import lalpulsar\n'), ((26250, 26297), 'logging.info', 'logging.info', (['"""Initialising PulsarDoplerParams"""'], {}), "('Initialising PulsarDoplerParams')\n", (26262, 26297), False, 'import logging\n'), ((26328, 26359), 'lalpulsar.PulsarDopplerParams', 'lalpulsar.PulsarDopplerParams', ([], {}), '()\n', (26357, 26359), False, 'import lalpulsar\n'), ((26520, 26556), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (26528, 26556), True, 'import numpy as np\n'), ((26621, 26662), 'logging.info', 'logging.info', (['"""Initialising FstatResults"""'], {}), "('Initialising FstatResults')\n", (26633, 26662), False, 'import logging\n'), ((26691, 26715), 'lalpulsar.FstatResults', 'lalpulsar.FstatResults', ([], {}), '()\n', (26713, 26715), False, 'import lalpulsar\n'), ((34931, 34942), 'numpy.min', 'np.min', (['fAs'], {}), '(fAs)\n', (34937, 34942), True, 'import numpy as np\n'), ((35094, 35105), 'numpy.max', 'np.max', (['fBs'], {}), '(fBs)\n', (35100, 35105), True, 'import numpy as np\n'), ((36681, 36706), 'lalpulsar.DopplerRegion', 'lalpulsar.DopplerRegion', ([], {}), '()\n', (36704, 36706), False, 'import lalpulsar\n'), ((37175, 37237), 'lalpulsar.SkySquare2String', 'lalpulsar.SkySquare2String', (['Alpha', 'Delta', 'AlphaBand', 'DeltaBand'], {}), '(Alpha, Delta, AlphaBand, DeltaBand)\n', (37201, 37237), False, 'import lalpulsar\n'), ((37401, 37437), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (37409, 37437), True, 'import numpy as np\n'), ((37471, 37507), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (37479, 37507), True, 'import numpy as np\n'), ((37969, 38000), 'lalpulsar.DopplerFullScanInit', 'lalpulsar.DopplerFullScanInit', ([], {}), '()\n', (37998, 38000), False, 'import lalpulsar\n'), ((38075, 38106), 'lalpulsar.PulsarDopplerParams', 'lalpulsar.PulsarDopplerParams', ([], {}), '()\n', (38104, 38106), False, 'import lalpulsar\n'), ((38639, 38675), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (38647, 38675), True, 'import numpy as np\n'), ((39110, 39149), 'lalpulsar.InitDopplerFullScan', 'lalpulsar.InitDopplerFullScan', (['scanInit'], {}), '(scanInit)\n', (39139, 39149), False, 'import lalpulsar\n'), ((39256, 39283), 'lalpulsar.PulsarSpinRange', 'lalpulsar.PulsarSpinRange', ([], {}), '()\n', (39281, 39283), False, 'import lalpulsar\n'), ((39292, 39346), 'lalpulsar.GetDopplerSpinRange', 'lalpulsar.GetDopplerSpinRange', (['spinRangeRef', 'scanState'], {}), '(spinRangeRef, scanState)\n', (39321, 39346), False, 'import lalpulsar\n'), ((40257, 40645), 'pyfstat.helper_functions.get_covering_band', 'helper_functions.get_covering_band', ([], {'tref': 'self.tref', 'tstart': 'self.minStartTime', 'tend': 'self.maxStartTime', 'F0': 'spinRangeRef.fkdot[0]', 'F1': 'spinRangeRef.fkdot[1]', 'F2': 'spinRangeRef.fkdot[2]', 'F0band': 'spinRangeRef.fkdotBand[0]', 'F1band': 'spinRangeRef.fkdotBand[1]', 'F2band': 'spinRangeRef.fkdotBand[2]', 'maxOrbitAsini': 'maxOrbitAsini', 'minOrbitPeriod': 'minOrbitPeriod', 'maxOrbitEcc': 'maxOrbitEcc'}), '(tref=self.tref, tstart=self.minStartTime,\n tend=self.maxStartTime, F0=spinRangeRef.fkdot[0], F1=spinRangeRef.fkdot\n [1], F2=spinRangeRef.fkdot[2], F0band=spinRangeRef.fkdotBand[0], F1band\n =spinRangeRef.fkdotBand[1], F2band=spinRangeRef.fkdotBand[2],\n maxOrbitAsini=maxOrbitAsini, minOrbitPeriod=minOrbitPeriod, maxOrbitEcc\n =maxOrbitEcc)\n', (40291, 40645), True, 'import pyfstat.helper_functions as helper_functions\n'), ((44121, 44157), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (44129, 44157), True, 'import numpy as np\n'), ((44637, 44800), 'lalpulsar.ComputeFstat', 'lalpulsar.ComputeFstat', ([], {'Fstats': 'self.FstatResults', 'input': 'self.FstatInput', 'doppler': 'self.PulsarDopplerParams', 'numFreqBins': '(1)', 'whatToCompute': 'self.whatToCompute'}), '(Fstats=self.FstatResults, input=self.FstatInput,\n doppler=self.PulsarDopplerParams, numFreqBins=1, whatToCompute=self.\n whatToCompute)\n', (44659, 44800), False, 'import lalpulsar\n'), ((45004, 45039), 'numpy.float', 'np.float', (['self.FstatResults.twoF[0]'], {}), '(self.FstatResults.twoF[0])\n', (45012, 45039), True, 'import numpy as np\n'), ((46124, 46184), 'lalpulsar.ComputeBSGL', 'lalpulsar.ComputeBSGL', (['self.twoF', 'self.twoFX', 'self.BSGLSetup'], {}), '(self.twoF, self.twoFX, self.BSGLSetup)\n', (46145, 46184), False, 'import lalpulsar\n'), ((47876, 48020), 'pyfstat.tcw_fstat_map_funcs.call_compute_transient_fstat_map', 'tcw.call_compute_transient_fstat_map', (['self.tCWFstatMapVersion', 'self.tCWFstatMapFeatures', 'self.FstatResults.multiFatoms[0]', 'self.windowRange'], {}), '(self.tCWFstatMapVersion, self.\n tCWFstatMapFeatures, self.FstatResults.multiFatoms[0], self.windowRange)\n', (47912, 48020), True, 'import pyfstat.tcw_fstat_map_funcs as tcw\n'), ((48276, 48298), 'numpy.isnan', 'np.isnan', (['self.maxTwoF'], {}), '(self.maxTwoF)\n', (48284, 48298), True, 'import numpy as np\n'), ((50464, 50536), 'lalpulsar.ComputeBSGL', 'lalpulsar.ComputeBSGL', (['self.maxTwoF', 'self.twoFXatMaxTwoF', 'self.BSGLSetup'], {}), '(self.maxTwoF, self.twoFXatMaxTwoF, self.BSGLSetup)\n', (50485, 50536), False, 'import lalpulsar\n'), ((51703, 51756), 'numpy.linspace', 'np.linspace', (['min_duration', 'max_duration', 'num_segments'], {}), '(min_duration, max_duration, num_segments)\n', (51714, 51756), True, 'import numpy as np\n'), ((59924, 59938), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (59936, 59938), True, 'import matplotlib.pyplot as plt\n'), ((66143, 66177), 'lalpulsar.transientWindowRange_t', 'lalpulsar.transientWindowRange_t', ([], {}), '()\n', (66175, 66177), False, 'import lalpulsar\n'), ((67585, 67650), 'numpy.linspace', 'np.linspace', (['self.minStartTime', 'self.maxStartTime', '(self.nsegs + 1)'], {}), '(self.minStartTime, self.maxStartTime, self.nsegs + 1)\n', (67596, 67650), True, 'import numpy as np\n'), ((71863, 71899), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (71871, 71899), True, 'import numpy as np\n'), ((72379, 72542), 'lalpulsar.ComputeFstat', 'lalpulsar.ComputeFstat', ([], {'Fstats': 'self.FstatResults', 'input': 'self.FstatInput', 'doppler': 'self.PulsarDopplerParams', 'numFreqBins': '(1)', 'whatToCompute': 'self.whatToCompute'}), '(Fstats=self.FstatResults, input=self.FstatInput,\n doppler=self.PulsarDopplerParams, numFreqBins=1, whatToCompute=self.\n whatToCompute)\n', (72401, 72542), False, 'import lalpulsar\n'), ((72717, 72736), 'numpy.isnan', 'np.isnan', (['self.twoF'], {}), '(self.twoF)\n', (72725, 72736), True, 'import numpy as np\n'), ((75853, 75913), 'lalpulsar.ComputeBSGL', 'lalpulsar.ComputeBSGL', (['self.twoF', 'self.twoFX', 'self.BSGLSetup'], {}), '(self.twoF, self.twoFX, self.BSGLSetup)\n', (75874, 75913), False, 'import lalpulsar\n'), ((75925, 75949), 'numpy.isnan', 'np.isnan', (['self.log10BSGL'], {}), '(self.log10BSGL)\n', (75933, 75949), True, 'import numpy as np\n'), ((76144, 76290), 'lalpulsar.ComputeTransientFstatMap', 'lalpulsar.ComputeTransientFstatMap', ([], {'multiFstatAtoms': 'self.FstatResults.multiFatoms[0]', 'windowRange': 'self.semicoherentWindowRange', 'useFReg': '(False)'}), '(multiFstatAtoms=self.FstatResults.\n multiFatoms[0], windowRange=self.semicoherentWindowRange, useFReg=False)\n', (76178, 76290), False, 'import lalpulsar\n'), ((77009, 77025), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (77017, 77025), True, 'import numpy as np\n'), ((78138, 78154), 'numpy.dot', 'np.dot', (['m', 'theta'], {}), '(m, theta)\n', (78144, 78154), True, 'import numpy as np\n'), ((84433, 84453), 'numpy.isfinite', 'np.isfinite', (['twoFSum'], {}), '(twoFSum)\n', (84444, 84453), True, 'import numpy as np\n'), ((85930, 86208), 'logging.warning', 'logging.warning', (['f"""The {cls.__name__} class is no longer maintained and will be removed in an upcoming release of PyFstat! If you rely on this class and/or are interested in taking over maintenance, please report an issue at: https://github.com/PyFstat/PyFstat/issues"""'], {}), "(\n f'The {cls.__name__} class is no longer maintained and will be removed in an upcoming release of PyFstat! If you rely on this class and/or are interested in taking over maintenance, please report an issue at: https://github.com/PyFstat/PyFstat/issues'\n )\n", (85945, 86208), False, 'import logging\n'), ((1795, 1887), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s %(levelname)-8s: %(message)s"""'], {'datefmt': '"""%y-%m-%d %H:%M"""'}), "('%(asctime)s %(levelname)-8s: %(message)s', datefmt=\n '%y-%m-%d %H:%M')\n", (1812, 1887), False, 'import logging\n'), ((2180, 2192), 'glob.glob', 'glob.glob', (['p'], {}), '(p)\n', (2189, 2192), False, 'import glob\n'), ((15796, 15836), 'logging.info', 'logging.info', (['"""Already have SFTCatalog."""'], {}), "('Already have SFTCatalog.')\n", (15808, 15836), False, 'import logging\n'), ((15908, 15972), 'logging.info', 'logging.info', (['"""No sftfilepattern given, making fake SFTCatalog."""'], {}), "('No sftfilepattern given, making fake SFTCatalog.')\n", (15920, 15972), False, 'import logging\n'), ((16661, 16683), 'lalpulsar.SFTCatalog', 'lalpulsar.SFTCatalog', ([], {}), '()\n', (16681, 16683), False, 'import lalpulsar\n'), ((16849, 16906), 'lal.CreateStringVector', 'lal.CreateStringVector', (['*[d for d in self.detector_names]'], {}), '(*[d for d in self.detector_names])\n', (16871, 16906), False, 'import lal\n'), ((17150, 17247), 'lalpulsar.MakeMultiTimestamps', 'lalpulsar.MakeMultiTimestamps', (['self.minStartTime', 'Tspan', 'self.Tsft', 'Toverlap', 'detNames.length'], {}), '(self.minStartTime, Tspan, self.Tsft, Toverlap,\n detNames.length)\n', (17179, 17247), False, 'import lalpulsar\n'), ((17299, 17372), 'lalpulsar.MultiAddToFakeSFTCatalog', 'lalpulsar.MultiAddToFakeSFTCatalog', (['SFTCatalog', 'detNames', 'multiTimestamps'], {}), '(SFTCatalog, detNames, multiTimestamps)\n', (17333, 17372), False, 'import lalpulsar\n'), ((18049, 18083), 'lal.LIGOTimeGPS', 'lal.LIGOTimeGPS', (['self.minStartTime'], {}), '(self.minStartTime)\n', (18064, 18083), False, 'import lal\n'), ((18228, 18262), 'lal.LIGOTimeGPS', 'lal.LIGOTimeGPS', (['self.maxStartTime'], {}), '(self.maxStartTime)\n', (18243, 18262), False, 'import lal\n'), ((22796, 22823), 'lalpulsar.MultiNoiseFloor', 'lalpulsar.MultiNoiseFloor', ([], {}), '()\n', (22821, 22823), False, 'import lalpulsar\n'), ((22851, 22908), 'pyfstat.helper_functions.parse_list_of_numbers', 'helper_functions.parse_list_of_numbers', (['self.assumeSqrtSX'], {}), '(self.assumeSqrtSX)\n', (22889, 22908), True, 'import pyfstat.helper_functions as helper_functions\n'), ((23396, 23433), 'lalpulsar.CreatePulsarParamsVector', 'lalpulsar.CreatePulsarParamsVector', (['(1)'], {}), '(1)\n', (23430, 23433), False, 'import lalpulsar\n'), ((25189, 25246), 'pyfstat.helper_functions.parse_list_of_numbers', 'helper_functions.parse_list_of_numbers', (['self.injectSqrtSX'], {}), '(self.injectSqrtSX)\n', (25227, 25246), True, 'import pyfstat.helper_functions as helper_functions\n'), ((25620, 25647), 'lalpulsar.MultiNoiseFloor', 'lalpulsar.MultiNoiseFloor', ([], {}), '()\n', (25645, 25647), False, 'import lalpulsar\n'), ((27784, 27824), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_DETECTORS'], {}), '(lalpulsar.PULSAR_MAX_DETECTORS)\n', (27792, 27824), True, 'import numpy as np\n'), ((28186, 28226), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_DETECTORS'], {}), '(lalpulsar.PULSAR_MAX_DETECTORS)\n', (28194, 28226), True, 'import numpy as np\n'), ((28339, 28388), 'logging.info', 'logging.info', (['"""Initialising transient parameters"""'], {}), "('Initialising transient parameters')\n", (28351, 28388), False, 'import logging\n'), ((28420, 28454), 'lalpulsar.transientWindowRange_t', 'lalpulsar.transientWindowRange_t', ([], {}), '()\n', (28452, 28454), False, 'import lalpulsar\n'), ((31456, 31515), 'logging.info', 'logging.info', (['"""Initialising transient FstatMap features..."""'], {}), "('Initialising transient FstatMap features...')\n", (31468, 31515), False, 'import logging\n'), ((31622, 31721), 'pyfstat.tcw_fstat_map_funcs.init_transient_fstat_map_features', 'tcw.init_transient_fstat_map_features', (["(self.tCWFstatMapVersion == 'pycuda')", 'self.cudaDeviceName'], {}), "(self.tCWFstatMapVersion == 'pycuda',\n self.cudaDeviceName)\n", (31659, 31721), True, 'import pyfstat.tcw_fstat_map_funcs as tcw\n'), ((49543, 49582), 'lalpulsar.CreateMultiFstatAtomVector', 'lalpulsar.CreateMultiFstatAtomVector', (['(1)'], {}), '(1)\n', (49579, 49582), False, 'import lalpulsar\n'), ((49757, 49842), 'lalpulsar.CreateFstatAtomVector', 'lalpulsar.CreateFstatAtomVector', (['self.FstatResults.multiFatoms[0].data[X].length'], {}), '(self.FstatResults.multiFatoms[0].data[X].length\n )\n', (49788, 49842), False, 'import lalpulsar\n'), ((50163, 50295), 'pyfstat.tcw_fstat_map_funcs.call_compute_transient_fstat_map', 'tcw.call_compute_transient_fstat_map', (['self.tCWFstatMapVersion', 'self.tCWFstatMapFeatures', 'singleIFOmultiFatoms', 'self.windowRange'], {}), '(self.tCWFstatMapVersion, self.\n tCWFstatMapFeatures, singleIFOmultiFatoms, self.windowRange)\n', (50199, 50295), True, 'import pyfstat.tcw_fstat_map_funcs as tcw\n'), ((54393, 54408), 'numpy.array', 'np.array', (['twoFs'], {}), '(twoFs)\n', (54401, 54408), True, 'import numpy as np\n'), ((56115, 56314), 'pyfstat.helper_functions.predict_fstat', 'helper_functions.predict_fstat', ([], {'minStartTime': 'tstart', 'duration': 'duration', 'sftfilepattern': 'self.sftfilepattern', 'h0': 'h0', 'cosi': 'cosi', 'psi': 'psi', 'Alpha': 'Alpha', 'Delta': 'Delta', 'F0': 'F0'}), '(minStartTime=tstart, duration=duration,\n sftfilepattern=self.sftfilepattern, h0=h0, cosi=cosi, psi=psi, Alpha=\n Alpha, Delta=Delta, F0=F0, **predict_fstat_kwargs)\n', (56145, 56314), True, 'import pyfstat.helper_functions as helper_functions\n'), ((56565, 56578), 'numpy.array', 'np.array', (['out'], {}), '(out)\n', (56573, 56578), True, 'import numpy as np\n'), ((61078, 61096), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (61094, 61096), True, 'import matplotlib.pyplot as plt\n'), ((61186, 61197), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (61195, 61197), True, 'import matplotlib.pyplot as plt\n'), ((61841, 61903), 'lalpulsar.PulsarDopplerParams2String', 'lalpulsar.PulsarDopplerParams2String', (['self.PulsarDopplerParams'], {}), '(self.PulsarDopplerParams)\n', (61877, 61903), False, 'import lalpulsar\n'), ((62077, 62106), 'lal.FileOpen', 'lal.FileOpen', (['fnameAtoms', '"""w"""'], {}), "(fnameAtoms, 'w')\n", (62089, 62106), False, 'import lal\n'), ((62218, 62275), 'lalpulsar.write_MultiFstatAtoms_to_fp', 'lalpulsar.write_MultiFstatAtoms_to_fp', (['fo', 'multiFatoms[0]'], {}), '(fo, multiFatoms[0])\n', (62255, 62275), False, 'import lalpulsar\n'), ((65681, 65735), 'numpy.zeros', 'np.zeros', (['(lalpulsar.PULSAR_MAX_DETECTORS, self.nsegs)'], {}), '((lalpulsar.PULSAR_MAX_DETECTORS, self.nsegs))\n', (65689, 65735), True, 'import numpy as np\n'), ((72750, 72844), 'logging.debug', 'logging.debug', (['"""NaNs in per-segment 2F treated as zero and semi-coherent 2F re-computed."""'], {}), "(\n 'NaNs in per-segment 2F treated as zero and semi-coherent 2F re-computed.')\n", (72763, 72844), False, 'import logging\n'), ((72920, 72960), 'numpy.nan_to_num', 'np.nan_to_num', (['twoF_per_segment'], {'nan': '(0.0)'}), '(twoF_per_segment, nan=0.0)\n', (72933, 72960), True, 'import numpy as np\n'), ((73905, 73944), 'lalpulsar.CreateMultiFstatAtomVector', 'lalpulsar.CreateMultiFstatAtomVector', (['(1)'], {}), '(1)\n', (73941, 73944), False, 'import lalpulsar\n'), ((74119, 74204), 'lalpulsar.CreateFstatAtomVector', 'lalpulsar.CreateFstatAtomVector', (['self.FstatResults.multiFatoms[0].data[X].length'], {}), '(self.FstatResults.multiFatoms[0].data[X].length\n )\n', (74150, 74204), False, 'import lalpulsar\n'), ((74508, 74641), 'lalpulsar.ComputeTransientFstatMap', 'lalpulsar.ComputeTransientFstatMap', ([], {'multiFstatAtoms': 'singleIFOmultiFatoms', 'windowRange': 'self.semicoherentWindowRange', 'useFReg': '(False)'}), '(multiFstatAtoms=singleIFOmultiFatoms,\n windowRange=self.semicoherentWindowRange, useFReg=False)\n', (74542, 74641), False, 'import lalpulsar\n'), ((74830, 74853), 'numpy.isnan', 'np.isnan', (['self.twoFX[X]'], {}), '(self.twoFX[X])\n', (74838, 74853), True, 'import numpy as np\n'), ((75963, 76027), 'logging.debug', 'logging.debug', (['"""NaNs in semi-coherent log10BSGL treated as zero"""'], {}), "('NaNs in semi-coherent log10BSGL treated as zero')\n", (75976, 76027), False, 'import logging\n'), ((1931, 1950), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1948, 1950), False, 'import logging\n'), ((4003, 4053), 'pprint.pformat', 'pformat', (['self.init_params_dict'], {'indent': '(2)', 'width': '(74)'}), '(self.init_params_dict, indent=2, width=74)\n', (4010, 4053), False, 'from pprint import pformat\n'), ((4874, 4891), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (4889, 4891), False, 'import getpass\n'), ((4928, 4948), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (4946, 4948), False, 'import socket\n'), ((4984, 5021), 'pyfstat.helper_functions.get_version_string', 'helper_functions.get_version_string', ([], {}), '()\n', (5019, 5021), True, 'import pyfstat.helper_functions as helper_functions\n'), ((17687, 17781), 'logging.warning', 'logging.warning', (['"""Multiple-detector constraints not available, using all available data."""'], {}), "(\n 'Multiple-detector constraints not available, using all available data.')\n", (17702, 17781), False, 'import logging\n'), ((19543, 19591), 'bashplotlib.histogram.plot_hist', 'plot_hist', (['SFT_timestamps'], {'height': '(5)', 'bincount': '(50)'}), '(SFT_timestamps, height=5, bincount=50)\n', (19552, 19591), False, 'from bashplotlib.histogram import plot_hist\n'), ((24209, 24246), 'numpy.array', 'np.array', (["self.injectSources['fkdot']"], {}), "(self.injectSources['fkdot'])\n", (24217, 24246), True, 'import numpy as np\n'), ((24300, 24336), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_SPINS'], {}), '(lalpulsar.PULSAR_MAX_SPINS)\n', (24308, 24336), True, 'import numpy as np\n'), ((24877, 24938), 'lalpulsar.PulsarParamsFromFile', 'lalpulsar.PulsarParamsFromFile', (['self.injectSources', 'self.tref'], {}), '(self.injectSources, self.tref)\n', (24907, 24938), False, 'import lalpulsar\n'), ((26896, 26929), 'logging.info', 'logging.info', (['"""Initialising BSGL"""'], {}), "('Initialising BSGL')\n", (26908, 26929), False, 'import logging\n'), ((27299, 27326), 'numpy.linspace', 'np.linspace', (['(0)', '(1000)', '(10000)'], {}), '(0, 1000, 10000)\n', (27310, 27326), True, 'import numpy as np\n'), ((31813, 31853), 'numpy.zeros', 'np.zeros', (['lalpulsar.PULSAR_MAX_DETECTORS'], {}), '(lalpulsar.PULSAR_MAX_DETECTORS)\n', (31821, 31853), True, 'import numpy as np\n'), ((35691, 35730), 'numpy.setdiff1d', 'np.setdiff1d', (['required_keys', 'range_keys'], {}), '(required_keys, range_keys)\n', (35703, 35730), True, 'import numpy as np\n'), ((61121, 61172), 'os.path.join', 'os.path.join', (['outdir', "(label + '_twoFcumulative.png')"], {}), "(outdir, label + '_twoFcumulative.png')\n", (61133, 61172), False, 'import os\n'), ((62173, 62205), 'lal.FilePuts', 'lal.FilePuts', (['f"""# {hline}\n"""', 'fo'], {}), "(f'# {hline}\\n', fo)\n", (62185, 62205), False, 'import lal\n'), ((74871, 74965), 'logging.debug', 'logging.debug', (['"""NaNs in per-segment per-detector 2F treated as zero and sum re-computed."""'], {}), "(\n 'NaNs in per-segment per-detector 2F treated as zero and sum re-computed.')\n", (74884, 74965), False, 'import logging\n'), ((75058, 75099), 'numpy.nan_to_num', 'np.nan_to_num', (['twoFX_per_segment'], {'nan': '(0.0)'}), '(twoFX_per_segment, nan=0.0)\n', (75071, 75099), True, 'import numpy as np\n'), ((83703, 83756), 'numpy.array', 'np.array', (['[delta_phi, delta_F0s, delta_F1s, delta_F2]'], {}), '([delta_phi, delta_F0s, delta_F1s, delta_F2])\n', (83711, 83756), True, 'import numpy as np\n'), ((4826, 4840), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4838, 4840), False, 'from datetime import datetime\n'), ((32724, 32830), 'logging.info', 'logging.info', (['"""[minCoverFreq,maxCoverFreq] not provided, trying to estimate from search ranges."""'], {}), "(\n '[minCoverFreq,maxCoverFreq] not provided, trying to estimate from search ranges.'\n )\n", (32736, 32830), False, 'import logging\n'), ((35858, 35897), 'numpy.setdiff1d', 'np.setdiff1d', (['required_keys', 'range_keys'], {}), '(required_keys, range_keys)\n', (35870, 35897), True, 'import numpy as np\n'), ((59584, 59721), 'logging.warning', 'logging.warning', (['f"""Be careful, overwriting {kwarg} {axis_kwargs[kwarg]} with {{custom_ax_kwargs[kwarg]}}: Check out the units!"""'], {}), "(\n f'Be careful, overwriting {kwarg} {axis_kwargs[kwarg]} with {{custom_ax_kwargs[kwarg]}}: Check out the units!'\n )\n", (59599, 59721), False, 'import logging\n'), ((27443, 27475), 'numpy.abs', 'np.abs', (['(p_vals - p_val_threshold)'], {}), '(p_vals - p_val_threshold)\n', (27449, 27475), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 14:44:44 2021 @author: <NAME> """ from sklearn.metrics import explained_variance_score from sklearn.metrics import r2_score from sklearn.metrics import max_error from sklearn.metrics import accuracy_score from sklearn.metrics import roc_auc_score from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import average_precision_score from statsmodels.stats.outliers_influence import variance_inflation_factor import numpy as np import pandas as pd import logging class _Tool(): def KS(y_true,y_hat,sample_weight=None): if isinstance(y_true,np.ndarray): y_true=pd.Series(y_true) if sample_weight is None: sample_weight=pd.Series(np.ones_like(y_true),index=y_true.index) if isinstance(y_hat,np.ndarray): y_hat = pd.Series(y_hat,index=y_true.index) sample_weight.name='sample_weight' y_true.name='y' y_hat.name='score' df = pd.concat([y_hat,y_true,sample_weight],axis=1) df['y_mutli_w']=df['y']*df['sample_weight'] total = df.groupby(['score'])['sample_weight'].sum() bad = df.groupby(['score'])['y_mutli_w'].sum() all_df = pd.DataFrame({'total':total, 'bad':bad}) all_df['good'] = all_df['total'] - all_df['bad'] all_df.reset_index(inplace=True) all_df = all_df.sort_values(by='score',ascending=False) all_df['badCumRate'] = all_df['bad'].cumsum() / all_df['bad'].sum() all_df['goodCumRate'] = all_df['good'].cumsum() / all_df['good'].sum() ks = all_df.apply(lambda x: x.goodCumRate - x.badCumRate, axis=1) return np.abs(ks).max() def vif(df): vif = pd.DataFrame() vif['features'] = df.columns if df.shape[1]>1: vif['VIF Factor'] = [variance_inflation_factor(df.values, i) for i in range(df.shape[1])] else: vif['VIF Factor']=0 vif = vif.sort_values('VIF Factor',ascending=False) return vif def make_logger(logger_name,logger_file): logger = logging.getLogger(logger_name) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(logger_file,mode='w') fh.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(name)s]-[%(filename)s-%(lineno)d]-[%(processName)s]-[%(asctime)s]-[%(levelname)s]: %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) return logger,fh SCORERS = dict( r2=r2_score, explained_variance_score=explained_variance_score, max_error = max_error, accuracy=accuracy_score, roc_auc=roc_auc_score, balanced_accuracy=balanced_accuracy_score, average_precision=average_precision_score, ks=_Tool.KS)
[ "logging.getLogger", "pandas.Series", "numpy.ones_like", "numpy.abs", "logging.Formatter", "statsmodels.stats.outliers_influence.variance_inflation_factor", "logging.FileHandler", "pandas.DataFrame", "pandas.concat" ]
[((1015, 1064), 'pandas.concat', 'pd.concat', (['[y_hat, y_true, sample_weight]'], {'axis': '(1)'}), '([y_hat, y_true, sample_weight], axis=1)\n', (1024, 1064), True, 'import pandas as pd\n'), ((1251, 1293), 'pandas.DataFrame', 'pd.DataFrame', (["{'total': total, 'bad': bad}"], {}), "({'total': total, 'bad': bad})\n", (1263, 1293), True, 'import pandas as pd\n'), ((1761, 1775), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1773, 1775), True, 'import pandas as pd\n'), ((2144, 2174), 'logging.getLogger', 'logging.getLogger', (['logger_name'], {}), '(logger_name)\n', (2161, 2174), False, 'import logging\n'), ((2229, 2271), 'logging.FileHandler', 'logging.FileHandler', (['logger_file'], {'mode': '"""w"""'}), "(logger_file, mode='w')\n", (2248, 2271), False, 'import logging\n'), ((2328, 2456), 'logging.Formatter', 'logging.Formatter', (['"""[%(name)s]-[%(filename)s-%(lineno)d]-[%(processName)s]-[%(asctime)s]-[%(levelname)s]: %(message)s"""'], {}), "(\n '[%(name)s]-[%(filename)s-%(lineno)d]-[%(processName)s]-[%(asctime)s]-[%(levelname)s]: %(message)s'\n )\n", (2345, 2456), False, 'import logging\n'), ((674, 691), 'pandas.Series', 'pd.Series', (['y_true'], {}), '(y_true)\n', (683, 691), True, 'import pandas as pd\n'), ((868, 904), 'pandas.Series', 'pd.Series', (['y_hat'], {'index': 'y_true.index'}), '(y_hat, index=y_true.index)\n', (877, 904), True, 'import pandas as pd\n'), ((764, 784), 'numpy.ones_like', 'np.ones_like', (['y_true'], {}), '(y_true)\n', (776, 784), True, 'import numpy as np\n'), ((1705, 1715), 'numpy.abs', 'np.abs', (['ks'], {}), '(ks)\n', (1711, 1715), True, 'import numpy as np\n'), ((1875, 1914), 'statsmodels.stats.outliers_influence.variance_inflation_factor', 'variance_inflation_factor', (['df.values', 'i'], {}), '(df.values, i)\n', (1900, 1914), False, 'from statsmodels.stats.outliers_influence import variance_inflation_factor\n')]
from floris.tools.floris_interface import FlorisInterface from floris.tools.optimization.scipy.yaw import YawOptimization from wind_farm_gym import WindFarmEnv from .agent import Agent import numpy as np class FlorisAgent(Agent): def __init__(self, name, env: WindFarmEnv, floris: FlorisInterface = None): super().__init__(name, 'FLORIS', env) self._stored_representation = env.action_representation env.action_representation = 'wind' self._opt_options = {'disp': False} self._min_yaw, self._max_yaw = env.desired_min_yaw, env.desired_max_yaw if self._env.wind_process is None: self._opt_yaws = None if floris is None: # use FLORIS parameters from the env self._floris_interface = FlorisInterface(env.floris_interface.input_file) elif isinstance(floris, FlorisInterface): self._floris_interface = floris elif isinstance(floris, str): self._floris_interface = FlorisInterface(floris) self.turbine_layout = env.turbine_layout self._floris_interface.reinitialize_flow_field(layout_array=self.turbine_layout) self._is_learning = False def find_action(self, observation, in_eval=False): # if not in_eval: # return list(np.zeros(self.action_shape)) parameters = {} for s, desc in zip(observation, self._env.observed_variables): val = desc['min'] + s * (desc['max'] - desc['min']) if desc['type'] != 'yaw': if desc.get('index') is None: # these are global; they take priority parameters[desc['type']] = val else: data = parameters.get(desc['type'], []) data.append(val) parameters[desc['type']] = data if 'wind_speed' in parameters.keys(): # the point with maximum wind speed is not affected by wakes; use it for reference i = np.argmax(parameters['wind_speed']) parameters = {k: v[i] if isinstance(v, list) else v for k, v in parameters.items()} else: parameters = {k: np.mean(v) for k, v in parameters.items()} self._floris_interface.reinitialize_flow_field(**parameters) return self.optimal_action() def learn(self, observation, action, reward, next_observation, global_step): pass def get_log_dict(self): return {} def optimal_action(self): if self._env.wind_process is None: if self._opt_yaws is None: self._opt_yaws = YawOptimization(self._floris_interface, self._min_yaw, self._max_yaw, opt_options=self._opt_options).optimize(False) opt_yaws = self._opt_yaws else: opt_yaws = YawOptimization(self._floris_interface, self._min_yaw, self._max_yaw, opt_options=self._opt_options).optimize(False) return self.yaws_to_action(opt_yaws) def yaws_to_action(self, opt_yaws): return [ (min(self._max_yaw, max(self._min_yaw, yaw)) - self._min_yaw) * 2 / (self._max_yaw - self._min_yaw) - 1 for yaw in opt_yaws ] def close(self): self._env.action_representation = self._stored_representation super().close()
[ "floris.tools.floris_interface.FlorisInterface", "numpy.mean", "floris.tools.optimization.scipy.yaw.YawOptimization", "numpy.argmax" ]
[((781, 829), 'floris.tools.floris_interface.FlorisInterface', 'FlorisInterface', (['env.floris_interface.input_file'], {}), '(env.floris_interface.input_file)\n', (796, 829), False, 'from floris.tools.floris_interface import FlorisInterface\n'), ((2013, 2048), 'numpy.argmax', 'np.argmax', (["parameters['wind_speed']"], {}), "(parameters['wind_speed'])\n", (2022, 2048), True, 'import numpy as np\n'), ((2188, 2198), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (2195, 2198), True, 'import numpy as np\n'), ((999, 1022), 'floris.tools.floris_interface.FlorisInterface', 'FlorisInterface', (['floris'], {}), '(floris)\n', (1014, 1022), False, 'from floris.tools.floris_interface import FlorisInterface\n'), ((2964, 3068), 'floris.tools.optimization.scipy.yaw.YawOptimization', 'YawOptimization', (['self._floris_interface', 'self._min_yaw', 'self._max_yaw'], {'opt_options': 'self._opt_options'}), '(self._floris_interface, self._min_yaw, self._max_yaw,\n opt_options=self._opt_options)\n', (2979, 3068), False, 'from floris.tools.optimization.scipy.yaw import YawOptimization\n'), ((2625, 2729), 'floris.tools.optimization.scipy.yaw.YawOptimization', 'YawOptimization', (['self._floris_interface', 'self._min_yaw', 'self._max_yaw'], {'opt_options': 'self._opt_options'}), '(self._floris_interface, self._min_yaw, self._max_yaw,\n opt_options=self._opt_options)\n', (2640, 2729), False, 'from floris.tools.optimization.scipy.yaw import YawOptimization\n')]
""" Tests for ambiguity.py """ import unittest from enum import Enum import numpy as np from scipy.signal import chebwin import os from ambiguity import ambiguity from m2py import brk, dmpdat, chkdat import subprocess class TestAmbiguity(unittest.TestCase): """ Simple unit tests for ambiguity """ SIMPLE_ARGS = { "u_basic": np.ones((1, 51)), "fcode": True, "f_basic": np.dot(0.0031, np.array(np.arange(-25, 26))), "F": 6, "K": 360, # 60, "T": 1.1, "N": 360, # 60, "sr": 10, "plot1_file": "fig_1.png", "plot2_file": "fig_2.png", "plot_format": "png", } _OUTPUT_DIR = 'test_plots' _OUTPUT_FORMAT = "png" _TEST_CASES = { 'Pulse': { 'u_basic': np.array([[1]]), 'fcode': False, 'f_basic': None, 'F': 4, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, 'LFM': { 'u_basic': np.ones((1, 51)), 'fcode': True, 'f_basic': np.multiply(0.0031, np.array(np.arange(-25, 26))), 'F': 6, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, 'Weighted LFM': { 'u_basic': np.conj(np.array([np.sqrt(chebwin(51, 50))])).T, 'fcode': True, 'f_basic': np.multiply(0.0031, np.array(np.arange(-25, 26), dtype=float)), 'F': 6, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, '<NAME>': { 'u_basic': np.ones((1, 7)), 'fcode': True, 'f_basic': np.array([[4, 7, 1, 6, 5, 2, 3]], dtype=float), 'F': 12, 'K': 60, 'T': 1.1, 'N': 80, 'sr': 20, }, '<NAME>': { 'u_basic': np.array([[1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]], dtype=float), 'fcode': False, 'f_basic': None, 'F': 10, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, '<NAME>': { 'u_basic': np.array([[1., 1, 1, 1, 1, 1j, -1, -1j, 1, -1, 1, -1, 1, -1j, -1, 1j]]), 'fcode': False, 'f_basic': None, 'F': 10, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, 'P4 25': { 'u_basic': np.exp(1j * np.pi * (1./25. * np.power(np.array([np.arange(0, 25)], dtype=float), 2) - np.array([np.arange(0, 25)], dtype=float))), 'fcode': False, 'f_basic': None, 'F': 15, 'K': 80, 'T': 1.1, 'N': 80, 'sr': 20, }, 'Complementary Pair': { 'u_basic': np.array([[1., 1., -1., 0., 0., 0., 0., 0., 0., 0, 1., 1.0j, 1.]]), 'fcode': False, 'f_basic': None, 'F': 10, 'K': 60, 'T': 1.1, 'N': 60, 'sr': 10, }, 'Pulse Train 1': { 'u_basic': np.array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=float), 'fcode': False, 'f_basic': None, 'F': 15, 'K': 80, 'T': 1.05, 'N': 100, 'sr': 10, }, 'Pulse Train 2': { 'u_basic': np.array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=float), 'fcode': False, 'f_basic': None, 'F': 12, 'K': 80, 'T': 0.042, 'N': 60, 'sr': 10, }, 'Stepped Freq. Pulse Train': { 'u_basic': np.array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=float), 'fcode': True, 'f_basic': np.multiply(0.78, np.array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5]], dtype=float)), 'F': 12, 'K': 80, 'T': 0.042, 'N': 60, 'sr': 10, }, 'Weighted Stepped Freq. Pulse Train': { 'u_basic': np.multiply( np.conj(np.sqrt(chebwin(36, 50))).T, np.array([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=float)), 'fcode': True, 'f_basic': np.multiply(0.7, np.array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 0, 0, 0, 7]], dtype=float)), 'F': 16, 'K': 70, 'T': 0.03, 'N': 60, 'sr': 5, }, } _SIGNAL_MAP = { 'pulse': 'Pulse', 'lfm': 'LFM', 'wlfm': 'Weighted LFM', 'costas7': 'Costas 7', 'barker13': 'Barker 13', 'frank16': 'Frank 16', 'p4_25': 'P4 25', 'comppair': 'Complementary Pair', 'ptrain1': 'Pulse Train 1', 'ptrain2': 'Pulse Train 2', 'sfptrain': 'Stepped Freq. Pulse Train', 'wsfptrain': 'Weighted Stepped Freq. Pulse Train', } def setUp(self): if not os.path.exists(self._OUTPUT_DIR): os.makedirs(self._OUTPUT_DIR) def test_ambiguity_fcode1(self): """ Test basic functionality """ args = self.SIMPLE_ARGS.copy() args['plot_title'] = 'ambiguity_fcode1' args['fcode'] = True args['plot1_file'] = os.path.join(self._OUTPUT_DIR, "fig_1_fcode1.png") args['plot2_file'] = os.path.join(self._OUTPUT_DIR, "fig_2_fcode1.png") print(args) (delay, freq, a) = ambiguity(**args) self.assertTrue(delay is not None and freq is not None and a is not None) def test_ambiguity_fcode0(self): """ Test code path when no frequency coding. """ args = self.SIMPLE_ARGS.copy() args['plot_title'] = 'ambiguity_fcode0' args['fcode'] = False args['plot1_file'] = os.path.join(self._OUTPUT_DIR, "fig_1_fcode0.png") args['plot2_file'] = os.path.join(self._OUTPUT_DIR, "fig_2_fcode0.png") print(args) (delay, freq, a) = ambiguity(**args) self.assertTrue(delay is not None and freq is not None and a is not None) def test_ambiguity_signals(self): """ Test all the given sample signals """ # First run the octave/matlab tests to generate # the reference data. subprocess.call(['octave', 'test_ambiguity_all.m']) # Now check the output against the reference data xtn = self._OUTPUT_FORMAT for signal_name in self._TEST_CASES.keys(): print(signal_name) plot1_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_1." + xtn) plot2_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_2." + xtn) args = self._TEST_CASES[signal_name] args['plot_title'] = signal_name args['plot1_file'] = plot1_file args['plot2_file'] = plot2_file args['plot_format'] = xtn args['plot_mesh'] = False print(args) (delay, freq, a) = ambiguity(**args) # Simple Sanity Check self.assertTrue(delay is not None and freq is not None and a is not None) # A more thorough check self.assertTrue(chkdat(signal_name, 'delay_final', delay, rtol=0.1, atol=1e-04)) self.assertTrue(chkdat(signal_name, 'freq_final', freq)) ''' self.assertTrue(chkdat(signal_name, 'a_final', a, rtol=0.5, atol=1e-04)) ''' def test_input_signals(self): for (signal_name, args) in self._TEST_CASES.items(): print(signal_name) dmpdat('u_basic', args['u_basic']) def test_wsfptrain(self): xtn = self._OUTPUT_FORMAT signal = 'wsfptrain' signal_name = self._SIGNAL_MAP[signal] print(signal_name) plot1_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_1." + xtn) plot2_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_2." + xtn) args = self._TEST_CASES[signal_name] args['plot_title'] = signal_name args['plot1_file'] = plot1_file args['plot2_file'] = plot2_file args['plot_format'] = xtn print(args) (delay, freq, a) = ambiguity(**args) self.assertTrue(delay is not None and freq is not None and a is not None) def test_sfptrain(self): xtn = self._OUTPUT_FORMAT signal = 'sfptrain' signal_name = self._SIGNAL_MAP[signal] print(signal_name) plot1_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_1." + xtn) plot2_file = os.path.join(self._OUTPUT_DIR, signal_name + "_fig_2." + xtn) args = self._TEST_CASES[signal_name] args['plot_title'] = signal_name args['plot1_file'] = plot1_file args['plot2_file'] = plot2_file args['plot_format'] = xtn print(args) (delay, freq, a) = ambiguity(**args) self.assertTrue(delay is not None and freq is not None and a is not None)
[ "os.path.exists", "numpy.ones", "os.makedirs", "ambiguity.ambiguity", "os.path.join", "scipy.signal.chebwin", "m2py.chkdat", "numpy.array", "subprocess.call", "m2py.dmpdat", "numpy.arange" ]
[((349, 365), 'numpy.ones', 'np.ones', (['(1, 51)'], {}), '((1, 51))\n', (356, 365), True, 'import numpy as np\n'), ((7680, 7730), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', '"""fig_1_fcode1.png"""'], {}), "(self._OUTPUT_DIR, 'fig_1_fcode1.png')\n", (7692, 7730), False, 'import os\n'), ((7802, 7852), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', '"""fig_2_fcode1.png"""'], {}), "(self._OUTPUT_DIR, 'fig_2_fcode1.png')\n", (7814, 7852), False, 'import os\n'), ((7943, 7960), 'ambiguity.ambiguity', 'ambiguity', ([], {}), '(**args)\n', (7952, 7960), False, 'from ambiguity import ambiguity\n'), ((8341, 8391), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', '"""fig_1_fcode0.png"""'], {}), "(self._OUTPUT_DIR, 'fig_1_fcode0.png')\n", (8353, 8391), False, 'import os\n'), ((8463, 8513), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', '"""fig_2_fcode0.png"""'], {}), "(self._OUTPUT_DIR, 'fig_2_fcode0.png')\n", (8475, 8513), False, 'import os\n'), ((8604, 8621), 'ambiguity.ambiguity', 'ambiguity', ([], {}), '(**args)\n', (8613, 8621), False, 'from ambiguity import ambiguity\n'), ((8946, 8997), 'subprocess.call', 'subprocess.call', (["['octave', 'test_ambiguity_all.m']"], {}), "(['octave', 'test_ambiguity_all.m'])\n", (8961, 8997), False, 'import subprocess\n'), ((10966, 11027), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_1.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_1.' + xtn)\n", (10978, 11027), False, 'import os\n'), ((11083, 11144), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_2.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_2.' + xtn)\n", (11095, 11144), False, 'import os\n'), ((11426, 11443), 'ambiguity.ambiguity', 'ambiguity', ([], {}), '(**args)\n', (11435, 11443), False, 'from ambiguity import ambiguity\n'), ((11764, 11825), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_1.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_1.' + xtn)\n", (11776, 11825), False, 'import os\n'), ((11881, 11942), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_2.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_2.' + xtn)\n", (11893, 11942), False, 'import os\n'), ((12224, 12241), 'ambiguity.ambiguity', 'ambiguity', ([], {}), '(**args)\n', (12233, 12241), False, 'from ambiguity import ambiguity\n'), ((813, 828), 'numpy.array', 'np.array', (['[[1]]'], {}), '([[1]])\n', (821, 828), True, 'import numpy as np\n'), ((1045, 1061), 'numpy.ones', 'np.ones', (['(1, 51)'], {}), '((1, 51))\n', (1052, 1061), True, 'import numpy as np\n'), ((1734, 1749), 'numpy.ones', 'np.ones', (['(1, 7)'], {}), '((1, 7))\n', (1741, 1749), True, 'import numpy as np\n'), ((1801, 1847), 'numpy.array', 'np.array', (['[[4, 7, 1, 6, 5, 2, 3]]'], {'dtype': 'float'}), '([[4, 7, 1, 6, 5, 2, 3]], dtype=float)\n', (1809, 1847), True, 'import numpy as np\n'), ((2011, 2079), 'numpy.array', 'np.array', (['[[1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]]'], {'dtype': 'float'}), '([[1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]], dtype=float)\n', (2019, 2079), True, 'import numpy as np\n'), ((2402, 2487), 'numpy.array', 'np.array', (['[[1.0, 1, 1, 1, 1, 1.0j, -1, -1.0j, 1, -1, 1, -1, 1, -1.0j, -1, 1.0j]]'], {}), '([[1.0, 1, 1, 1, 1, 1.0j, -1, -1.0j, 1, -1, 1, -1, 1, -1.0j, -1, 1.0j]]\n )\n', (2410, 2487), True, 'import numpy as np\n'), ((3306, 3383), 'numpy.array', 'np.array', (['[[1.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 1.0, 1.0j, 1.0]]'], {}), '([[1.0, 1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 1.0, 1.0j, 1.0]])\n', (3314, 3383), True, 'import numpy as np\n'), ((3702, 3809), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n ]'], {'dtype': 'float'}), '([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 1]], dtype=float)\n', (3710, 3809), True, 'import numpy as np\n'), ((4205, 4312), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n ]'], {'dtype': 'float'}), '([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 1]], dtype=float)\n', (4213, 4312), True, 'import numpy as np\n'), ((4720, 4827), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n ]'], {'dtype': 'float'}), '([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 1]], dtype=float)\n', (4728, 4827), True, 'import numpy as np\n'), ((7372, 7404), 'os.path.exists', 'os.path.exists', (['self._OUTPUT_DIR'], {}), '(self._OUTPUT_DIR)\n', (7386, 7404), False, 'import os\n'), ((7418, 7447), 'os.makedirs', 'os.makedirs', (['self._OUTPUT_DIR'], {}), '(self._OUTPUT_DIR)\n', (7429, 7447), False, 'import os\n'), ((9199, 9260), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_1.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_1.' + xtn)\n", (9211, 9260), False, 'import os\n'), ((9324, 9385), 'os.path.join', 'os.path.join', (['self._OUTPUT_DIR', "(signal_name + '_fig_2.' + xtn)"], {}), "(self._OUTPUT_DIR, signal_name + '_fig_2.' + xtn)\n", (9336, 9385), False, 'import os\n'), ((9739, 9756), 'ambiguity.ambiguity', 'ambiguity', ([], {}), '(**args)\n', (9748, 9756), False, 'from ambiguity import ambiguity\n'), ((10741, 10775), 'm2py.dmpdat', 'dmpdat', (['"""u_basic"""', "args['u_basic']"], {}), "('u_basic', args['u_basic'])\n", (10747, 10775), False, 'from m2py import brk, dmpdat, chkdat\n'), ((459, 477), 'numpy.arange', 'np.arange', (['(-25)', '(26)'], {}), '(-25, 26)\n', (468, 477), True, 'import numpy as np\n'), ((5063, 5170), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5]\n ]'], {'dtype': 'float'}), '([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0,\n 0, 0, 0, 5]], dtype=float)\n', (5071, 5170), True, 'import numpy as np\n'), ((5741, 5878), 'numpy.array', 'np.array', (['[[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]]'], {'dtype': 'float'}), '([[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=float)\n', (5749, 5878), True, 'import numpy as np\n'), ((6266, 6403), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0,\n 5, 0, 0, 0, 0, 6, 0, 0, 0, 0, 7]]'], {'dtype': 'float'}), '([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0,\n 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 0, 0, 0, 7]], dtype=float)\n', (6274, 6403), True, 'import numpy as np\n'), ((10000, 10064), 'm2py.chkdat', 'chkdat', (['signal_name', '"""delay_final"""', 'delay'], {'rtol': '(0.1)', 'atol': '(0.0001)'}), "(signal_name, 'delay_final', delay, rtol=0.1, atol=0.0001)\n", (10006, 10064), False, 'from m2py import brk, dmpdat, chkdat\n'), ((10234, 10273), 'm2py.chkdat', 'chkdat', (['signal_name', '"""freq_final"""', 'freq'], {}), "(signal_name, 'freq_final', freq)\n", (10240, 10273), False, 'from m2py import brk, dmpdat, chkdat\n'), ((1142, 1160), 'numpy.arange', 'np.arange', (['(-25)', '(26)'], {}), '(-25, 26)\n', (1151, 1160), True, 'import numpy as np\n'), ((1494, 1512), 'numpy.arange', 'np.arange', (['(-25)', '(26)'], {}), '(-25, 26)\n', (1503, 1512), True, 'import numpy as np\n'), ((5685, 5700), 'scipy.signal.chebwin', 'chebwin', (['(36)', '(50)'], {}), '(36, 50)\n', (5692, 5700), False, 'from scipy.signal import chebwin\n'), ((1357, 1372), 'scipy.signal.chebwin', 'chebwin', (['(51)', '(50)'], {}), '(51, 50)\n', (1364, 1372), False, 'from scipy.signal import chebwin\n'), ((3000, 3016), 'numpy.arange', 'np.arange', (['(0)', '(25)'], {}), '(0, 25)\n', (3009, 3016), True, 'import numpy as np\n'), ((2874, 2890), 'numpy.arange', 'np.arange', (['(0)', '(25)'], {}), '(0, 25)\n', (2883, 2890), True, 'import numpy as np\n')]
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F class AttentionBranch(nn.Module): def __init__(self,conv_flag=True): super(AttentionBranch, self).__init__() if conv_flag: self.basicMode = nn.Sequential( nn.Conv2d(in_channels=512,out_channels=512,kernel_size=3,stride=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True), nn.Conv2d(in_channels=512,out_channels=1024,kernel_size=3,stride=1,dilation=1), nn.ReLU(inplace=True), ) def build_Gram_Matrix(self,x): a, b, c, d = x.size() # a=batch size(=1) # b=number of feature maps # (c,d)=dimensions of a f. map (N=c*d) Gram_Matrix = [] x_reshape = x.view(c*d, a*b) for loc in range(c*d): loc_feat = x_reshape[loc] loc_gram_matrix = torch.mm(loc_feat,loc_feat.t()) Gram_Matrix.append(loc_gram_matrix) return Gram_Matrix ''''''''' features = x.view(a * b, c * d) # resise F_XL into \hat F_XL G = torch.mm(features, features.t()) # compute the gram product # we 'normalize' the values of the gram matrix # by dividing by the number of element in each feature maps. return G.div(a * b * c * d) ''''''''' def rebuild_features(self,gram_matrix,input): batch_size,height,width,nchannel = input.size() input_resize = input.view(height,width,nchannel) for loc in range(height*width): pass def forward(self,input): x = self.basicMode(input) gram_matrix = self.build_Gram_Matrix(x) features = self.rebuild_features(gram_matrix,input) return features ###### source code from tensorflow version ######## def whole_img_attention(self, bottom): #### assun batch_size == 1 #### l2_normalization bottom_norm = tf.nn.l2_normalize(bottom, dim=3, epsilon=1e-12) assert len(bottom_norm.get_shape().as_list()) == 4 batch_size, height, width, nchannel = bottom.get_shape().as_list() bottom_seq = 100 * tf.reshape(bottom_norm, [height * width, nchannel]) time_step = height * width alpha = [] ctx_attention = [] for _step in range(time_step): hidden_step = bottom_seq[_step] alpha_ = self.attention_simple_dot(hidden_step, bottom_seq) # alpha_ = self.attention_model_generate_(hidden_i,out_seq) ctx_attention_step = tf.reduce_sum(tf.expand_dims(alpha_, 1) * bottom_seq, 0) ctx_attention.append(ctx_attention_step) alpha.append(alpha_) context_att_tensor_ = tf.pack(ctx_attention, axis=0) shape_ = [batch_size, height, width, nchannel] context_att_ = tf.reshape(context_att_tensor_, shape_) alphas = tf.pack(alpha, axis=0) a_shape = [time_step, height, width] alphas_ = tf.reshape(alphas, a_shape) print(context_att_.get_shape()) return context_att_, alphas_ class fcn32s(nn.Module): def __init__(self): super(fcn32s, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels=3,out_channels=64,kernel_size=3,stride=1,padding=100), nn.ReLU(inplace=True), nn.Conv2d(in_channels=64,out_channels=64,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True), ) self.conv2 = nn.Sequential( nn.Conv2d(in_channels=64,out_channels=128,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=128,out_channels=128,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True), ) self.conv3 = nn.Sequential( nn.Conv2d(in_channels=128,out_channels=256,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=256,out_channels=256,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=256,out_channels=256,kernel_size=3,stride=1,padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True), ) self.conv4 = nn.Sequential( nn.Conv2d(in_channels=256,out_channels=512,kernel_size=3, stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=512, out_channels= 512, kernel_size=3, stride=1,padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=True), ) self.conv5 = nn.Sequential( nn.Conv2d(in_channels=512,out_channels=512,kernel_size=3, stride=1,padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=512,out_channels=512, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=512,out_channels=512, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2,stride=2,ceil_mode=True), ) self.fc6 = nn.Sequential( nn.Conv2d(in_channels=512,out_channels=4096,kernel_size=7), nn.ReLU(inplace=True), nn.Dropout2d(), ) self.fc7 = nn.Sequential( nn.Conv2d(in_channels=4096,out_channels=4096,kernel_size=1), nn.ReLU(inplace=True), nn.Dropout2d(), ) self.score = nn.Conv2d(in_channels=4096,out_channels=21,kernel_size=1) self.upscore = nn.ConvTranspose2d(in_channels=21,out_channels=21,kernel_size=64,stride=32,bias=False) def forward(self,input): x = self.conv1(input) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) self.conv_features = self.conv5(x) x = self.fc6(self.conv_features) x = self.fc7(x) score = self.score(x) #out = F.upsample_bilinear(score, input.size()[2:]) upscore = self.upscore(score) upscore = upscore[:, :,19:19+input.size()[2], 19:19+input.size()[3]].contiguous() #n_size = upscore.size() return upscore,self.conv_features def init_parameters(self,pretrain_vgg16): ##### init parameter using pretrain vgg16 model ########### conv_blocks = [self.conv1, self.conv2, self.conv3, self.conv4, self.conv5] ranges = [[0, 4], [5, 9], [10, 16], [17, 23], [24, 29]] features = list(pretrain_vgg16.features.children()) for idx, conv_block in enumerate(conv_blocks): for l1, l2 in zip(features[ranges[idx][0]:ranges[idx][1]], conv_block): if isinstance(l1, nn.Conv2d) and isinstance(l2, nn.Conv2d): # print idx, l1, l2 assert l1.weight.size() == l2.weight.size() assert l1.bias.size() == l2.bias.size() l2.weight.data = l1.weight.data l2.bias.data = l1.bias.data ####### init fc parameters (transplant) ############## self.fc6[0].weight.data = pretrain_vgg16.classifier[0].weight.data.view(self.fc6[0].weight.size()) self.fc6[0].bias.data = pretrain_vgg16.classifier[0].bias.data.view(self.fc6[0].bias.size()) self.fc7[0].weight.data = pretrain_vgg16.classifier[3].weight.data.view(self.fc7[0].weight.size()) self.fc7[0].bias.data = pretrain_vgg16.classifier[3].bias.data.view(self.fc7[0].bias.size()) ###### random init socore layer parameters ########### assert self.upscore.kernel_size[0] == self.upscore.kernel_size[1] initial_weight = get_upsampling_weight(self.upscore.in_channels, self.upscore.out_channels, self.upscore.kernel_size[0]) self.upscore.weight.data.copy_(initial_weight) # https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py def get_upsampling_weight(in_channels, out_channels, kernel_size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:kernel_size, :kernel_size] filt = (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1] - center) / factor) weight = np.zeros((in_channels, out_channels, kernel_size, kernel_size), dtype=np.float64) weight[range(in_channels), range(out_channels), :, :] = filt return torch.from_numpy(weight).float()
[ "torch.nn.ReLU", "torch.nn.Dropout2d", "torch.from_numpy", "torch.nn.Conv2d", "numpy.zeros", "torch.nn.MaxPool2d", "torch.nn.ConvTranspose2d" ]
[((8598, 8684), 'numpy.zeros', 'np.zeros', (['(in_channels, out_channels, kernel_size, kernel_size)'], {'dtype': 'np.float64'}), '((in_channels, out_channels, kernel_size, kernel_size), dtype=np.\n float64)\n', (8606, 8684), True, 'import numpy as np\n'), ((5696, 5755), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(4096)', 'out_channels': '(21)', 'kernel_size': '(1)'}), '(in_channels=4096, out_channels=21, kernel_size=1)\n', (5705, 5755), True, 'import torch.nn as nn\n'), ((5778, 5873), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', ([], {'in_channels': '(21)', 'out_channels': '(21)', 'kernel_size': '(64)', 'stride': '(32)', 'bias': '(False)'}), '(in_channels=21, out_channels=21, kernel_size=64, stride=\n 32, bias=False)\n', (5796, 5873), True, 'import torch.nn as nn\n'), ((3162, 3241), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(3)', 'out_channels': '(64)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(100)'}), '(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=100)\n', (3171, 3241), True, 'import torch.nn as nn\n'), ((3251, 3272), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3258, 3272), True, 'import torch.nn as nn\n'), ((3286, 3364), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(64)', 'out_channels': '(64)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1)\n', (3295, 3364), True, 'import torch.nn as nn\n'), ((3374, 3395), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3381, 3395), True, 'import torch.nn as nn\n'), ((3409, 3462), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (3421, 3462), True, 'import torch.nn as nn\n'), ((3520, 3599), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(64)', 'out_channels': '(128)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1)\n', (3529, 3599), True, 'import torch.nn as nn\n'), ((3609, 3630), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3616, 3630), True, 'import torch.nn as nn\n'), ((3644, 3729), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(128)', 'out_channels': '(128)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1\n )\n', (3653, 3729), True, 'import torch.nn as nn\n'), ((3734, 3755), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3741, 3755), True, 'import torch.nn as nn\n'), ((3769, 3822), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (3781, 3822), True, 'import torch.nn as nn\n'), ((3881, 3966), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(128)', 'out_channels': '(256)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1\n )\n', (3890, 3966), True, 'import torch.nn as nn\n'), ((3971, 3992), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3978, 3992), True, 'import torch.nn as nn\n'), ((4006, 4091), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(256)', 'out_channels': '(256)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1\n )\n', (4015, 4091), True, 'import torch.nn as nn\n'), ((4096, 4117), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4103, 4117), True, 'import torch.nn as nn\n'), ((4131, 4216), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(256)', 'out_channels': '(256)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1\n )\n', (4140, 4216), True, 'import torch.nn as nn\n'), ((4221, 4242), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4228, 4242), True, 'import torch.nn as nn\n'), ((4256, 4309), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (4268, 4309), True, 'import torch.nn as nn\n'), ((4369, 4454), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(256)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (4378, 4454), True, 'import torch.nn as nn\n'), ((4460, 4481), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4467, 4481), True, 'import torch.nn as nn\n'), ((4495, 4580), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (4504, 4580), True, 'import torch.nn as nn\n'), ((4588, 4609), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4595, 4609), True, 'import torch.nn as nn\n'), ((4623, 4708), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (4632, 4708), True, 'import torch.nn as nn\n'), ((4717, 4738), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4724, 4738), True, 'import torch.nn as nn\n'), ((4752, 4805), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (4764, 4805), True, 'import torch.nn as nn\n'), ((4866, 4951), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (4875, 4951), True, 'import torch.nn as nn\n'), ((4957, 4978), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4964, 4978), True, 'import torch.nn as nn\n'), ((4992, 5077), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (5001, 5077), True, 'import torch.nn as nn\n'), ((5085, 5106), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5092, 5106), True, 'import torch.nn as nn\n'), ((5120, 5205), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n )\n', (5129, 5205), True, 'import torch.nn as nn\n'), ((5213, 5234), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5220, 5234), True, 'import torch.nn as nn\n'), ((5248, 5301), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (5260, 5301), True, 'import torch.nn as nn\n'), ((5359, 5419), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(4096)', 'kernel_size': '(7)'}), '(in_channels=512, out_channels=4096, kernel_size=7)\n', (5368, 5419), True, 'import torch.nn as nn\n'), ((5431, 5452), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5438, 5452), True, 'import torch.nn as nn\n'), ((5466, 5480), 'torch.nn.Dropout2d', 'nn.Dropout2d', ([], {}), '()\n', (5478, 5480), True, 'import torch.nn as nn\n'), ((5540, 5601), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(4096)', 'out_channels': '(4096)', 'kernel_size': '(1)'}), '(in_channels=4096, out_channels=4096, kernel_size=1)\n', (5549, 5601), True, 'import torch.nn as nn\n'), ((5613, 5634), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5620, 5634), True, 'import torch.nn as nn\n'), ((5648, 5662), 'torch.nn.Dropout2d', 'nn.Dropout2d', ([], {}), '()\n', (5660, 5662), True, 'import torch.nn as nn\n'), ((8778, 8802), 'torch.from_numpy', 'torch.from_numpy', (['weight'], {}), '(weight)\n', (8794, 8802), False, 'import torch\n'), ((290, 359), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(512)', 'kernel_size': '(3)', 'stride': '(1)'}), '(in_channels=512, out_channels=512, kernel_size=3, stride=1)\n', (299, 359), True, 'import torch.nn as nn\n'), ((373, 394), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (380, 394), True, 'import torch.nn as nn\n'), ((411, 464), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)', 'ceil_mode': '(True)'}), '(kernel_size=2, stride=2, ceil_mode=True)\n', (423, 464), True, 'import torch.nn as nn\n'), ((479, 565), 'torch.nn.Conv2d', 'nn.Conv2d', ([], {'in_channels': '(512)', 'out_channels': '(1024)', 'kernel_size': '(3)', 'stride': '(1)', 'dilation': '(1)'}), '(in_channels=512, out_channels=1024, kernel_size=3, stride=1,\n dilation=1)\n', (488, 565), True, 'import torch.nn as nn\n'), ((574, 595), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (581, 595), True, 'import torch.nn as nn\n')]
import unittest import numpy as np from PCAfold import preprocess from PCAfold import reduction from PCAfold import analysis class Analysis(unittest.TestCase): def test_analysis__plot_normalized_variance_comparison__allowed_calls(self): X = np.random.rand(100,5) Y = np.random.rand(100,5) pca_X = reduction.PCA(X, n_components=2) pca_Y = reduction.PCA(Y, n_components=2) principal_components_X = pca_X.transform(X) principal_components_Y = pca_Y.transform(Y) variance_data_X = analysis.compute_normalized_variance(principal_components_X, X, depvar_names=['A', 'B', 'C', 'D', 'E'], bandwidth_values=np.logspace(-3, 2, 20), scale_unit_box=True) variance_data_Y = analysis.compute_normalized_variance(principal_components_Y, Y, depvar_names=['F', 'G', 'H', 'I', 'J'], bandwidth_values=np.logspace(-3, 2, 20), scale_unit_box=True) # try: # plt = analysis.plot_normalized_variance_comparison((variance_data_X, variance_data_Y), # ([0,1,2], [0,1,2]), # ('Blues', 'Reds')) # plt.close() # except: # self.assertTrue(False) # # try: # plt = analysis.plot_normalized_variance_comparison((variance_data_X, variance_data_Y), # ([0,1,2], [0,1,2]), # ('Blues', 'Reds'), # figure_size=(10,5), # title='Normalized variance comparison', # save_filename=None) # plt.close() # except: # self.assertTrue(False) # ------------------------------------------------------------------------------ def test_analysis__plot_normalized_variance_comparison__not_allowed_calls(self): X = np.random.rand(100,5) Y = np.random.rand(100,5) pca_X = reduction.PCA(X, n_components=2) pca_Y = reduction.PCA(Y, n_components=2) principal_components_X = pca_X.transform(X) principal_components_Y = pca_Y.transform(Y) variance_data_X = analysis.compute_normalized_variance(principal_components_X, X, depvar_names=['A', 'B', 'C', 'D', 'E'], bandwidth_values=np.logspace(-3, 2, 20), scale_unit_box=True) variance_data_Y = analysis.compute_normalized_variance(principal_components_Y, Y, depvar_names=['F', 'G', 'H', 'I', 'J'], bandwidth_values=np.logspace(-3, 2, 20), scale_unit_box=True) with self.assertRaises(ValueError): plt = analysis.plot_normalized_variance_comparison((variance_data_X, variance_data_Y), ([0,1,2], [0,1,2]), ('Blues', 'Reds'), figure_size=[1]) plt.close() with self.assertRaises(ValueError): plt = analysis.plot_normalized_variance_comparison((variance_data_X, variance_data_Y), ([0,1,2], [0,1,2]), ('Blues', 'Reds'), title=[1]) plt.close() with self.assertRaises(ValueError): plt = analysis.plot_normalized_variance_comparison((variance_data_X, variance_data_Y), ([0,1,2], [0,1,2]), ('Blues', 'Reds'), save_filename=[1]) plt.close() # ------------------------------------------------------------------------------
[ "PCAfold.reduction.PCA", "numpy.logspace", "numpy.random.rand", "PCAfold.analysis.plot_normalized_variance_comparison" ]
[((256, 278), 'numpy.random.rand', 'np.random.rand', (['(100)', '(5)'], {}), '(100, 5)\n', (270, 278), True, 'import numpy as np\n'), ((290, 312), 'numpy.random.rand', 'np.random.rand', (['(100)', '(5)'], {}), '(100, 5)\n', (304, 312), True, 'import numpy as np\n'), ((329, 361), 'PCAfold.reduction.PCA', 'reduction.PCA', (['X'], {'n_components': '(2)'}), '(X, n_components=2)\n', (342, 361), False, 'from PCAfold import reduction\n'), ((378, 410), 'PCAfold.reduction.PCA', 'reduction.PCA', (['Y'], {'n_components': '(2)'}), '(Y, n_components=2)\n', (391, 410), False, 'from PCAfold import reduction\n'), ((2036, 2058), 'numpy.random.rand', 'np.random.rand', (['(100)', '(5)'], {}), '(100, 5)\n', (2050, 2058), True, 'import numpy as np\n'), ((2070, 2092), 'numpy.random.rand', 'np.random.rand', (['(100)', '(5)'], {}), '(100, 5)\n', (2084, 2092), True, 'import numpy as np\n'), ((2109, 2141), 'PCAfold.reduction.PCA', 'reduction.PCA', (['X'], {'n_components': '(2)'}), '(X, n_components=2)\n', (2122, 2141), False, 'from PCAfold import reduction\n'), ((2158, 2190), 'PCAfold.reduction.PCA', 'reduction.PCA', (['Y'], {'n_components': '(2)'}), '(Y, n_components=2)\n', (2171, 2190), False, 'from PCAfold import reduction\n'), ((2743, 2891), 'PCAfold.analysis.plot_normalized_variance_comparison', 'analysis.plot_normalized_variance_comparison', (['(variance_data_X, variance_data_Y)', '([0, 1, 2], [0, 1, 2])', "('Blues', 'Reds')"], {'figure_size': '[1]'}), "((variance_data_X,\n variance_data_Y), ([0, 1, 2], [0, 1, 2]), ('Blues', 'Reds'),\n figure_size=[1])\n", (2787, 2891), False, 'from PCAfold import analysis\n'), ((2967, 3105), 'PCAfold.analysis.plot_normalized_variance_comparison', 'analysis.plot_normalized_variance_comparison', (['(variance_data_X, variance_data_Y)', '([0, 1, 2], [0, 1, 2])', "('Blues', 'Reds')"], {'title': '[1]'}), "((variance_data_X,\n variance_data_Y), ([0, 1, 2], [0, 1, 2]), ('Blues', 'Reds'), title=[1])\n", (3011, 3105), False, 'from PCAfold import analysis\n'), ((3185, 3335), 'PCAfold.analysis.plot_normalized_variance_comparison', 'analysis.plot_normalized_variance_comparison', (['(variance_data_X, variance_data_Y)', '([0, 1, 2], [0, 1, 2])', "('Blues', 'Reds')"], {'save_filename': '[1]'}), "((variance_data_X,\n variance_data_Y), ([0, 1, 2], [0, 1, 2]), ('Blues', 'Reds'),\n save_filename=[1])\n", (3229, 3335), False, 'from PCAfold import analysis\n'), ((663, 685), 'numpy.logspace', 'np.logspace', (['(-3)', '(2)', '(20)'], {}), '(-3, 2, 20)\n', (674, 685), True, 'import numpy as np\n'), ((855, 877), 'numpy.logspace', 'np.logspace', (['(-3)', '(2)', '(20)'], {}), '(-3, 2, 20)\n', (866, 877), True, 'import numpy as np\n'), ((2443, 2465), 'numpy.logspace', 'np.logspace', (['(-3)', '(2)', '(20)'], {}), '(-3, 2, 20)\n', (2454, 2465), True, 'import numpy as np\n'), ((2635, 2657), 'numpy.logspace', 'np.logspace', (['(-3)', '(2)', '(20)'], {}), '(-3, 2, 20)\n', (2646, 2657), True, 'import numpy as np\n')]
import cv2 import numpy as np from utils import unpickle, unserialize from tensorflow.keras.datasets import cifar10 from tensorflow.keras.utils import to_categorical def prepare_pixels(data): """ Convert data from integers between 0 - 255 to floats between 0 - 1 """ data = data.astype("float32") norm = data / 255.0 return norm def image_to_feature_vector(image, size=(32, 32)): return cv2.resize(image, size).flatten() def extract_color_histogram(image, bins=(8, 8, 8)): hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hist = cv2.calcHist([hsv], [0, 1, 2], None, bins, [0, 180, 0, 256, 0, 256]) cv2.normalize(hist, hist) return hist.flatten() def prepare_labels(labels): """ One Hot Encoding """ labels = np.array(labels) N = labels.shape[0] one_hot = np.zeros((N, 10)) for index, value in enumerate(labels): one_hot[index][value] = 1 return one_hot def get_train_data(batch_no): train_set = unpickle("cifar10/data_batch_" + str(batch_no)) train_data = train_set[b"data"] train_images = unserialize(train_data) labels = train_set[b"labels"] images = prepare_pixels(train_images) labels = prepare_labels(labels) return images, labels def get_test_data(): test_set = unpickle("cifar10/test_batch") test_data = test_set[b"data"] test_images = unserialize(test_data) labels = test_set[b"labels"] images = prepare_pixels(test_images) labels = prepare_labels(labels) return images, labels def get_data_from_tensorflow(): (images_train, labels_train), (images_test, labels_test) = cifar10.load_data() # normalize the pixel values images_train = images_train.astype('float32') images_test = images_test.astype('float32') images_train /= 255 images_test /= 255 # one hot encoding labels_train = to_categorical(labels_train, 10) labels_test = to_categorical(labels_test, 10) return images_train, labels_train, images_test, labels_test
[ "tensorflow.keras.utils.to_categorical", "cv2.calcHist", "cv2.normalize", "utils.unpickle", "utils.unserialize", "numpy.array", "numpy.zeros", "tensorflow.keras.datasets.cifar10.load_data", "cv2.cvtColor", "cv2.resize" ]
[((511, 549), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2HSV'], {}), '(image, cv2.COLOR_BGR2HSV)\n', (523, 549), False, 'import cv2\n'), ((558, 626), 'cv2.calcHist', 'cv2.calcHist', (['[hsv]', '[0, 1, 2]', 'None', 'bins', '[0, 180, 0, 256, 0, 256]'], {}), '([hsv], [0, 1, 2], None, bins, [0, 180, 0, 256, 0, 256])\n', (570, 626), False, 'import cv2\n'), ((628, 653), 'cv2.normalize', 'cv2.normalize', (['hist', 'hist'], {}), '(hist, hist)\n', (641, 653), False, 'import cv2\n'), ((757, 773), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (765, 773), True, 'import numpy as np\n'), ((812, 829), 'numpy.zeros', 'np.zeros', (['(N, 10)'], {}), '((N, 10))\n', (820, 829), True, 'import numpy as np\n'), ((1079, 1102), 'utils.unserialize', 'unserialize', (['train_data'], {}), '(train_data)\n', (1090, 1102), False, 'from utils import unpickle, unserialize\n'), ((1279, 1309), 'utils.unpickle', 'unpickle', (['"""cifar10/test_batch"""'], {}), "('cifar10/test_batch')\n", (1287, 1309), False, 'from utils import unpickle, unserialize\n'), ((1362, 1384), 'utils.unserialize', 'unserialize', (['test_data'], {}), '(test_data)\n', (1373, 1384), False, 'from utils import unpickle, unserialize\n'), ((1618, 1637), 'tensorflow.keras.datasets.cifar10.load_data', 'cifar10.load_data', ([], {}), '()\n', (1635, 1637), False, 'from tensorflow.keras.datasets import cifar10\n'), ((1868, 1900), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['labels_train', '(10)'], {}), '(labels_train, 10)\n', (1882, 1900), False, 'from tensorflow.keras.utils import to_categorical\n'), ((1920, 1951), 'tensorflow.keras.utils.to_categorical', 'to_categorical', (['labels_test', '(10)'], {}), '(labels_test, 10)\n', (1934, 1951), False, 'from tensorflow.keras.utils import to_categorical\n'), ((416, 439), 'cv2.resize', 'cv2.resize', (['image', 'size'], {}), '(image, size)\n', (426, 439), False, 'import cv2\n')]
""" Basic Equations for solving shallow water problems ##################### """ from pysph.sph.equation import Equation from pysph.sph.integrator_step import IntegratorStep from pysph.sph.integrator import Integrator from compyle.api import declare from pysph.sph.wc.linalg import gj_solve, augmented_matrix from numpy import sqrt, cos, sin, zeros, pi, exp import numpy as np import numpy M_PI = pi class CheckForParticlesToSplit(Equation): r"""Particles are tagged for splitting if the following condition is satisfied: .. math:: (A_i > A_max) and (h_i < h_max) and (x_min < x_i < x_max) and (y_min < y_i < y_max) References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def __init__(self, dest, h_max=1e9, A_max=1e9, x_min=-1e9, x_max=1e9, y_min=-1e9, y_max=1e9): r""" Parameters ---------- h_max : float maximum smoothing length beyond which splitting is deactivated A_max : float maximum area beyond which splitting is activated x_min : float minimum distance along x-direction beyond which splitting is activated x_max : float maximum distance along x-direction beyond which splitting is deactivated y_min : float minimum distance along y-direction beyond which splitting is activated y_max : float maximum distance along y-direction beyond which splitting is deactivated """ self.A_max = A_max self.h_max = h_max self.x_min = x_min self.x_max = x_max self.y_min = y_min self.y_max = y_max super(CheckForParticlesToSplit, self).__init__(dest, None) def initialize(self, d_idx, d_A, d_h, d_x, d_y, d_pa_to_split): if (d_A[d_idx] > self.A_max and d_h[d_idx] < self.h_max and (self.x_min < d_x[d_idx] < self.x_max) and (self.y_min < d_y[d_idx] < self.y_max)): d_pa_to_split[d_idx] = 1 else: d_pa_to_split[d_idx] = 0 class ParticleSplit(object): r"""**Hexagonal particle splitting algorithm** References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def __init__(self, pa_arr): r""" Parameters ---------- pa_arr : pysph.base.particle_array.ParticleArray particle array of fluid """ self.pa_arr = pa_arr # Ratio of mass of daughter particle located at center of hexagon to # that of its parents mass self.center_pa_mass_frac = 0.178705766141917 # Ratio of mass of daughter particle located at vertex of hexagon to # that of its parents mass self.vertex_pa_mass_frac = 0.136882287617319 # Ratio of smoothing length of daughter particle to that of its parents # smoothing length self.pa_h_ratio = 0.9 # Ratio of distance between center daughter particle and vertex # daughter particle to that of its parents smoothing length self.center_and_vertex_pa_separation_frac = 0.4 # Get index of the parent particles to split self.idx_pa_to_split = self._get_idx_of_particles_to_split() # Number of daughter particles located at the vertices of hexagon after # splitting self.num_vertex_pa_after_single_split = 6 def do_particle_split(self, solver=None): if not self.idx_pa_to_split.size: # If no particles to split then return return else: # Properties of parent particles to split h_parent = self.pa_arr.h[self.idx_pa_to_split] h0_parent = self.pa_arr.h0[self.idx_pa_to_split] m_parent = self.pa_arr.m[self.idx_pa_to_split] x_parent = self.pa_arr.x[self.idx_pa_to_split] y_parent = self.pa_arr.y[self.idx_pa_to_split] u_parent = self.pa_arr.u[self.idx_pa_to_split] v_parent = self.pa_arr.v[self.idx_pa_to_split] u_prev_step_parent = self.pa_arr.u_prev_step[self.idx_pa_to_split] v_prev_step_parent = self.pa_arr.v_prev_step[self.idx_pa_to_split] rho_parent = self.pa_arr.rho[self.idx_pa_to_split] rho0_parent = self.pa_arr.rho0[self.idx_pa_to_split] alpha_parent = self.pa_arr.alpha[self.idx_pa_to_split] # Vertex daughter particle properties update n = self.num_vertex_pa_after_single_split h_vertex_pa = self.pa_h_ratio * np.repeat(h_parent, n) h0_vertex_pa = self.pa_h_ratio * np.repeat(h0_parent, n) u_prev_step_vertex_pa = np.repeat(u_prev_step_parent, n) v_prev_step_vertex_pa = np.repeat(v_prev_step_parent, n) m_vertex_pa = self.vertex_pa_mass_frac * np.repeat(m_parent, n) vertex_pa_pos = self._get_vertex_pa_positions(h_parent, u_parent, v_parent) x_vertex_pa = vertex_pa_pos[0] + np.repeat(x_parent, n) y_vertex_pa = vertex_pa_pos[1] + np.repeat(y_parent, n) rho0_vertex_pa = np.repeat(rho0_parent, n) rho_vertex_pa = np.repeat(rho_parent, n) alpha_vertex_pa = np.repeat(alpha_parent, n) parent_idx_vertex_pa = np.repeat(self.idx_pa_to_split, n) # Note: # The center daughter particle properties are set at index of # parent. The properties of parent needed for further calculations # are not changed for now # Center daughter particle properties update for idx in self.idx_pa_to_split: self.pa_arr.m[idx] *= self.center_pa_mass_frac self.pa_arr.h[idx] *= self.pa_h_ratio self.pa_arr.h0[idx] *= self.pa_h_ratio self.pa_arr.parent_idx[idx] = int(idx) # Update particle array to include vertex daughter particles self._add_vertex_pa_prop( h0_vertex_pa, h_vertex_pa, m_vertex_pa, x_vertex_pa, y_vertex_pa, rho0_vertex_pa, rho_vertex_pa, u_prev_step_vertex_pa, v_prev_step_vertex_pa, alpha_vertex_pa, parent_idx_vertex_pa) def _get_idx_of_particles_to_split(self): idx_pa_to_split = [] for idx, val in enumerate(self.pa_arr.pa_to_split): if val: idx_pa_to_split.append(idx) return np.array(idx_pa_to_split) def _get_vertex_pa_positions(self, h_parent, u_parent, v_parent): # Number of particles to split num_of_pa_to_split = len(self.idx_pa_to_split) n = self.num_vertex_pa_after_single_split theta_vertex_pa = zeros(n) r = self.center_and_vertex_pa_separation_frac for i, theta in enumerate(range(0, 360, 60)): theta_vertex_pa[i] = (pi/180)*theta # Angle of velocity vector with horizontal angle_vel = np.where( (np.abs(u_parent) > 1e-3) | (np.abs(v_parent) > 1e-3), np.arctan2(v_parent, u_parent), 0 ) # Rotates the hexagon such that its horizontal axis aligns with the # direction of velocity vector angle_actual = (np.tile(theta_vertex_pa, num_of_pa_to_split) + np.repeat(angle_vel, n)) x = r * cos(angle_actual) * np.repeat(h_parent, n) y = r * sin(angle_actual) * np.repeat(h_parent, n) return x.copy(), y.copy() def _add_vertex_pa_prop(self, h0_vertex_pa, h_vertex_pa, m_vertex_pa, x_vertex_pa, y_vertex_pa, rho0_vertex_pa, rho_vertex_pa, u_prev_step_vertex_pa, v_prev_step_vertex_pa, alpha_vertex_pa, parent_idx_vertex_pa): vertex_pa_props = { 'm': m_vertex_pa, 'h': h_vertex_pa, 'h0': h0_vertex_pa, 'x': x_vertex_pa, 'y': y_vertex_pa, 'u_prev_step': u_prev_step_vertex_pa, 'v_prev_step': v_prev_step_vertex_pa, 'rho0': rho0_vertex_pa, 'rho': rho_vertex_pa, 'alpha': alpha_vertex_pa, 'parent_idx': parent_idx_vertex_pa.astype(int) } # Add vertex daughter particles to particle array self.pa_arr.add_particles(**vertex_pa_props) class DaughterVelocityEval(Equation): r"""**Evaluation of the daughter particle velocity after splitting procedure** .. math:: \boldsymbol{v_k} = c_v\frac{d_N}{d_k}\boldsymbol{v_N} where, .. math:: c_v = \dfrac{A_N}{\sum_{k=1}^{M}A_k} References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def __init__(self, dest, sources, rhow=1000.0): r"""" Parameters ---------- rhow : float constant 3-D density of water (kg/m3) Notes ----- This equation should be called before the equation SWEOS, as the parent particle area is required for calculating velocities. On calling the SWEOS equation, the parent properties are changed to the center daughter particle properties. """ self.rhow = rhow super(DaughterVelocityEval, self).__init__(dest, sources) def initialize(self, d_sum_Ak, d_idx, d_m, d_rho, d_u, d_v, d_uh, d_vh, d_u_parent, d_v_parent, d_uh_parent, d_vh_parent, d_parent_idx): # Stores sum of areas of daughter particles d_sum_Ak[d_idx] = 0.0 d_u_parent[d_idx] = d_u[d_parent_idx[d_idx]] d_uh_parent[d_idx] = d_uh[d_parent_idx[d_idx]] d_v_parent[d_idx] = d_v[d_parent_idx[d_idx]] d_vh_parent[d_idx] = d_vh[d_parent_idx[d_idx]] def loop_all(self, d_sum_Ak, d_pa_to_split, d_parent_idx, d_idx, s_m, s_rho, s_parent_idx, NBRS, N_NBRS): i = declare('int') s_idx = declare('long') if d_pa_to_split[d_idx]: for i in range(N_NBRS): s_idx = NBRS[i] if s_parent_idx[s_idx] == d_parent_idx[d_idx]: # Sums the area of daughter particles who have same parent # idx d_sum_Ak[d_idx] += s_m[s_idx] / s_rho[s_idx] def post_loop(self, d_idx, d_parent_idx, d_A, d_sum_Ak, d_dw, d_rho, d_u, d_uh, d_vh, d_v, d_u_parent, d_v_parent, d_uh_parent, d_vh_parent, t): # True only for daughter particles if d_parent_idx[d_idx]: # Ratio of parent area (before split) to sum of areas of its # daughters (after split) cv = d_A[d_parent_idx[d_idx]] / d_sum_Ak[d_parent_idx[d_idx]] # The denominator (d_rho[d_idx]/self.rhow) represents the water # depth of daughter particle. d_dw[d_idx] cannot be used as # equation of state is called after this equation (Refer Notes in # the constructor) dw_ratio = d_dw[d_parent_idx[d_idx]] / (d_rho[d_idx]/self.rhow) d_u[d_idx] = cv * dw_ratio * d_u_parent[d_idx] d_uh[d_idx] = cv * dw_ratio * d_uh_parent[d_idx] d_v[d_idx] = cv * dw_ratio * d_v_parent[d_idx] d_vh[d_idx] = cv * dw_ratio * d_vh_parent[d_idx] d_parent_idx[d_idx] = 0 class FindMergeable(Equation): r"""**Particle merging algorithm** Particles are tagged for merging if the following condition is satisfied: .. math:: (A_i < A_min) and (x_min < x_i < x_max) and (y_min < y_i < y_max) References ---------- .. [Vacondio2013] <NAME> et al., "Shallow water SPH for flooding with dynamic particle coalescing and splitting", Advances in Water Resources, 58 (2013), pp. 10-23 """ def __init__(self, dest, sources, A_min, x_min=-1e9, x_max=1e9, y_min=-1e9, y_max=1e9): r""" Parameters ---------- A_min : float minimum area below which merging is activated x_min : float minimum distance along x-direction beyond which merging is activated x_max : float maximum distance along x-direction beyond which merging is deactivated y_min : float minimum distance along y-direction beyond which merging is activated y_max : float maximum distance along y-direction beyond which merging is deactivated Notes ----- The merging algorithm merges two particles 'a' and 'b' if the following conditions are satisfied: #. Both particles have area less than A_min #. Both particles lies within :math:`x_min < x_i < x_max` and :math:`y_min < y_i < y_max` #. if 'a' is the closest neighbor of 'b' and vice versa The merging algorithm is run every timestep """ self.A_min = A_min self.x_min = x_min self.x_max = x_max self.y_min = y_min self.y_max = y_max super(FindMergeable, self).__init__(dest, sources) def loop_all(self, d_idx, d_merge, d_closest_idx, d_x, d_y, d_h, d_A, d_is_merged_pa, s_x, s_y, s_A, NBRS, N_NBRS): # Finds the closest neighbor of a particle and stores the index of that # neighbor in d_closest_idx[d_idx] i, closest = declare('int', 2) s_idx = declare('unsigned int') d_merge[d_idx] = 0 d_is_merged_pa[d_idx] = 0 xi = d_x[d_idx] yi = d_y[d_idx] rmin = d_h[d_idx] * 10.0 closest = -1 if (d_A[d_idx] < self.A_min and ((self.x_min < d_x[d_idx] < self.x_max) and (self.y_min < d_y[d_idx] < self.y_max))): for i in range(N_NBRS): s_idx = NBRS[i] if s_idx == d_idx: continue xij = xi - s_x[s_idx] yij = yi - s_y[s_idx] rij = sqrt(xij*xij + yij*yij) if rij < rmin: closest = s_idx rmin = rij d_closest_idx[d_idx] = closest def post_loop(self, d_idx, d_m, d_u, d_v, d_h, d_uh, d_vh, d_closest_idx, d_is_merged_pa, d_merge, d_x, d_y, SPH_KERNEL): idx = declare('int') xma = declare('matrix(3)') xmb = declare('matrix(3)') idx = d_closest_idx[d_idx] if idx > -1: # If particle 'a' is closest neighbor of 'b' and vice versa if d_idx == d_closest_idx[idx]: if d_idx < idx: # The newly merged particle properties are set at index of # particle 'a' m_merged = d_m[d_idx] + d_m[idx] x_merged = ((d_m[d_idx]*d_x[d_idx] + d_m[idx]*d_x[idx]) / m_merged) y_merged = ((d_m[d_idx]*d_y[d_idx] + d_m[idx]*d_y[idx]) / m_merged) xma[0] = x_merged - d_x[d_idx] xma[1] = y_merged - d_y[d_idx] xmb[0] = x_merged - d_x[idx] xmb[1] = y_merged - d_y[idx] rma = sqrt(xma[0]*xma[0] + xma[1]*xma[1]) rmb = sqrt(xmb[0]*xmb[0] + xmb[1]*xmb[1]) d_u[d_idx] = ((d_m[d_idx]*d_u[d_idx] + d_m[idx]*d_u[idx]) / m_merged) d_uh[d_idx] = (d_m[d_idx]*d_uh[d_idx] + d_m[idx]*d_uh[idx]) / m_merged d_v[d_idx] = ((d_m[d_idx]*d_v[d_idx] + d_m[idx]*d_v[idx]) / m_merged) d_vh[d_idx] = (d_m[d_idx]*d_vh[d_idx] + d_m[idx]*d_vh[idx]) / m_merged const1 = d_m[d_idx] * SPH_KERNEL.kernel(xma, rma, d_h[d_idx]) const2 = d_m[idx] * SPH_KERNEL.kernel(xmb, rmb, d_h[idx]) d_h[d_idx] = sqrt((7*M_PI/10.) * (m_merged/(const1+const2))) d_m[d_idx] = m_merged # Tags the newly formed particle after merging d_is_merged_pa[d_idx] = 1 else: # Tags particle 'b' for removal after merging d_merge[d_idx] = 1 def reduce(self, dst, t, dt): # The indices of particle 'b' are removed from particle array after # merging is done indices = declare('object') indices = numpy.where(dst.merge > 0)[0] if len(indices) > 0: dst.remove_particles(indices) class InitialDensityEvalAfterMerge(Equation): r"""**Initial density of the newly formed particle after merging** .. math :: \rho_M = \sum_{j}^{}m_jW_{M,j} References ---------- .. [Vacondio2013] R. Vacondio et al., "Shallow water SPH for flooding with dynamic particle coalescing and splitting", Advances in Water Resources, 58 (2013), pp. 10-23 """ def loop_all(self, d_rho, d_idx, d_is_merged_pa, d_x, d_y, s_h, s_m, s_x, d_merge, d_closest_idx, s_y, SPH_KERNEL, NBRS, N_NBRS): i = declare('int') s_idx = declare('long') xij = declare('matrix(3)') # Evaluates the initial density of the newly formed particle after # merging if d_is_merged_pa[d_idx] == 1: d_rho[d_idx] = 0.0 rij = 0.0 rho_sum = 0.0 for i in range(N_NBRS): s_idx = NBRS[i] xij[0] = d_x[d_idx] - s_x[s_idx] xij[1] = d_y[d_idx] - s_y[s_idx] rij = sqrt(xij[0]*xij[0] + xij[1]*xij[1]) rho_sum += s_m[s_idx] * SPH_KERNEL.kernel(xij, rij, s_h[s_idx]) d_rho[d_idx] += rho_sum class EulerStep(IntegratorStep): """Fast but inaccurate integrator. Use this for testing""" def initialize(self, d_u, d_v, d_u_prev_step, d_v_prev_step, d_idx): d_u_prev_step[d_idx] = d_u[d_idx] d_v_prev_step[d_idx] = d_v[d_idx] def stage1(self, d_idx, d_u, d_v, d_au, d_av, d_x, d_y, dt): d_u[d_idx] += dt * d_au[d_idx] d_v[d_idx] += dt * d_av[d_idx] d_x[d_idx] += dt * d_u[d_idx] d_y[d_idx] += dt * d_v[d_idx] class SWEStep(IntegratorStep): """Leap frog time integration scheme""" def initialize(self, t, d_u, d_v, d_uh, d_vh, d_u_prev_step, d_v_prev_step, d_idx): # Stores the velocities at previous time step d_u_prev_step[d_idx] = d_u[d_idx] d_v_prev_step[d_idx] = d_v[d_idx] def stage1(self, d_uh, d_vh, d_idx, d_au, d_av, dt): # Velocities at half time step d_uh[d_idx] += dt * d_au[d_idx] d_vh[d_idx] += dt * d_av[d_idx] def stage2(self, d_u, d_v, d_uh, d_vh, d_idx, d_au, d_av, d_x, d_y, dt): d_x[d_idx] += dt * d_uh[d_idx] d_y[d_idx] += dt * d_vh[d_idx] d_u[d_idx] = d_uh[d_idx] + dt/2.*d_au[d_idx] d_v[d_idx] = d_vh[d_idx] + dt/2.*d_av[d_idx] class SWEIntegrator(Integrator): """Integrator for shallow water problems""" def one_timestep(self, t, dt): self.compute_accelerations() self.initialize() # Predict self.stage1() # Call any post-stage functions. self.do_post_stage(0.5*dt, 1) # Correct self.stage2() # Call any post-stage functions. self.do_post_stage(dt, 2) class GatherDensityEvalNextIteration(Equation): r"""**Gather formulation for evaluating the density of a particle** .. math:: \rho_i = \sum_{j}{m_jW(\textbf{x}_i - \textbf{x}_j, h_i)} References ---------- .. [Hernquist and Katz, 1988] <NAME> and <NAME>, "TREESPH: A unification of SPH with the hierarcgical tree method", The Astrophysical Journal Supplement Series, 70 (1989), pp 419-446. """ def initialize(self, d_rho, d_idx, d_rho_prev_iter): # Stores density of particle i of the previous iteration d_rho_prev_iter[d_idx] = d_rho[d_idx] d_rho[d_idx] = 0.0 def loop(self, d_rho, d_idx, s_m, s_idx, WI): d_rho[d_idx] += s_m[s_idx] * WI class ScatterDensityEvalNextIteration(Equation): r"""**Scatter formulation for evaluating the density of a particle** .. math:: \rho_i = \sum_{J}{m_JW(\textbf{x}_i - \textbf{x}_j, h_j)} References ---------- .. [Hernquist and Katz, 1988] <NAME> and <NAME>, "TREESPH: A unification of SPH with the hierarcgical tree method", The Astrophysical Journal Supplement Series, 70 (1989), pp 419-446. """ def initialize(self, t, d_rho, d_idx, d_rho_prev_iter): # Stores density of particle i of the previous iteration d_rho_prev_iter[d_idx] = d_rho[d_idx] d_rho[d_idx] = 0.0 def loop(self, d_rho, d_idx, s_m, s_idx, WJ): d_rho[d_idx] += s_m[s_idx] * WJ class NonDimensionalDensityResidual(Equation): r"""**Non-dimensional density residual** .. math:: \psi^{k+1} = \dfrac{|\rho_i^{k+1} - \rho_i^k|}{\rho_i^k} References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def __init__(self, dest, sources=None): super(NonDimensionalDensityResidual, self).__init__(dest, sources) def post_loop(self, d_psi, d_rho, d_rho_prev_iter, d_idx): # Non-dimensional residual d_psi[d_idx] = abs(d_rho[d_idx] - d_rho_prev_iter[d_idx]) \ / d_rho_prev_iter[d_idx] class CheckConvergenceDensityResidual(Equation): r"""The iterative process is stopped once the following condition is met .. math:: \psi^{k+1} < \epsilon_{\psi} where, \epsilon_{\psi} = 1e-3 References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 Notes ----- If particle splitting is activated, better to use this convergence criteria. It can be used even if particle splitting is not activated. """ def __init__(self, dest, sources=None): super(CheckConvergenceDensityResidual, self).__init__(dest, sources) self.eqn_has_converged = 0 def initialize(self): self.eqn_has_converged = 0 def reduce(self, dst, t, dt): epsilon = max(dst.psi) if epsilon <= 1e-3: self.eqn_has_converged = 1 def converged(self): return self.eqn_has_converged class CorrectionFactorVariableSmoothingLength(Equation): r"""**Correction factor in internal force due to variable smoothing length** .. math:: \alpha_i = -\sum_j m_j r_{ij}\frac{dW_i}{dr_{ij}} References ---------- .. [<NAME>, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def initialize(self, d_idx, d_alpha): d_alpha[d_idx] = 0.0 def loop(self, d_alpha, d_idx, DWIJ, XIJ, s_idx, s_m): d_alpha[d_idx] += -s_m[s_idx] * (DWIJ[0]*XIJ[0] + DWIJ[1]*XIJ[1]) class RemoveParticlesWithZeroAlpha(Equation): r"""Removes particles if correction factor (alpha) in internal force due to variable smoothing length is zero """ def __init__(self, dest): super(RemoveParticlesWithZeroAlpha, self).__init__(dest, None) def post_loop(self, d_alpha, d_pa_alpha_zero, d_idx): if d_alpha[d_idx] == 0: d_pa_alpha_zero[d_idx] = 1 def reduce(self, dst, t, dt): indices = declare('object') indices = numpy.where(dst.pa_alpha_zero > 0)[0] if len(indices) > 0: dst.remove_particles(indices) class SummationDensity(Equation): r"""**Summation Density** .. math:: \rho_i = \sum_{j}{m_jW(\textbf{x}_i - \textbf{x}_j, h_i)} """ def initialize(self, d_summation_rho, d_idx): d_summation_rho[d_idx] = 0.0 def loop(self, d_summation_rho, d_idx, s_m, s_idx, WI): d_summation_rho[d_idx] += s_m[s_idx] * WI class InitialGuessDensityVacondio(Equation): r"""**Initial guess density to start the iterative evaluation of density for time step n+1** .. math:: \rho_{i(0)}^{n+1} = \rho_i^n + dt\dfrac{d\rho_i}{dt}\\ h_{i(0)}^{n+1} = h_i^n + -\dfrac{h_i^n}{\rho_i^n}\dfrac{dt}{dm} \dfrac{d\rho_i}{dt} where, .. math:: \frac{d\rho_i}{dt} = \rho_i^n\sum_j\dfrac{m_j}{\rho_j} (\textbf{v}_i-\textbf{v}_j).\nabla W_i References ---------- .. [VacondioSWE-SPHysics, 2013] <NAME> et al., SWE-SPHysics source code, File: SWE_SPHYsics/SWE-SPHysics_2D_v1.0.00/source/SPHYSICS_SWE_2D/ ac_dw_var_hj_2D.f Note: If particle splitting is activated, better to use this method. It can be used even if particle splitting is not activated. """ def __init__(self, dest, sources, dim=2): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) """ self.dim = dim super(InitialGuessDensityVacondio, self).__init__(dest, sources) def initialize(self, d_arho, d_idx): d_arho[d_idx] = 0 def loop(self, d_arho, d_rho, d_idx, s_m, s_rho, s_idx, d_u_prev_step, d_v_prev_step, s_u_prev_step, s_v_prev_step, DWI): tmp1 = (d_u_prev_step[d_idx]-s_u_prev_step[s_idx]) * DWI[0] tmp2 = (d_v_prev_step[d_idx]-s_v_prev_step[s_idx]) * DWI[1] d_arho[d_idx] += d_rho[d_idx] * ((s_m[s_idx]/s_rho[s_idx])*(tmp1+tmp2)) def post_loop(self, d_rho, d_h, dt, d_arho, d_idx): d_rho[d_idx] += dt * d_arho[d_idx] d_h[d_idx] += -(dt/self.dim)*d_h[d_idx]*(d_arho[d_idx]/d_rho[d_idx]) class InitialGuessDensity(Equation): r"""**Initial guess density to start the iterative evaluation of density for time step n+1 based on properties of time step n** .. math:: \rho_{I, n+1}^{(0)} = \rho_{I,n}e^{\lambda_n} where, \lambda = \dfrac{\rho_Id_m}{\alpha_I}\sum_{J}^{}m_J (\textbf{v}_J - \textbf{v}_I).\nabla W_I(\textbf{x}_I - \textbf{x}_J, h_I) References ---------- .. [Rodriguez and Bonet, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def __init__(self, dest, sources, dim=2): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) """ self.dim = dim super(InitialGuessDensity, self).__init__(dest, sources) def initialize(self, d_exp_lambda, d_idx): d_exp_lambda[d_idx] = 0.0 def loop(self, d_exp_lambda, d_u_prev_step, d_v_prev_step, d_alpha, d_idx, s_m, s_u_prev_step, s_v_prev_step, s_idx, DWI, dt, t): a1 = (d_u_prev_step[d_idx]-s_u_prev_step[s_idx]) * DWI[0] a2 = (d_v_prev_step[d_idx]-s_v_prev_step[s_idx]) * DWI[1] const = (self.dim*dt) / d_alpha[d_idx] d_exp_lambda[d_idx] += const * (s_m[s_idx]*(a1+a2)) def post_loop(self, t, d_rho, d_exp_lambda, d_idx): d_rho[d_idx] = d_rho[d_idx] * exp(d_exp_lambda[d_idx]) class UpdateSmoothingLength(Equation): r"""**Update smoothing length based on density** .. math:: h_I^{(k)} = h_I^{0}\biggl(\dfrac{\rho_I^0}{\rho_I^{(k)}} \biggl)^\frac{1}{d_m} References ---------- .. [<NAME>, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def __init__(self, dest, dim=2): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) """ self.dim = dim super(UpdateSmoothingLength, self).__init__(dest, None) def post_loop(self, d_h, d_h0, d_rho0, d_rho, d_idx): d_h[d_idx] = d_h0[d_idx] * (d_rho0[d_idx]/d_rho[d_idx])**(1./self.dim) class DensityResidual(Equation): r"""**Residual of density** .. math:: R(\rho^{(k)}) = \rho_I^{(k)} - \sum_{J}^{}m_J W_I(\textbf{x}_I - \textbf{x}_J, h_I^{(k)}) References ---------- .. [Rodriguez and Bonet, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def __init__(self, dest, sources=None): super(DensityResidual, self).__init__(dest, sources) def post_loop(self, d_rho, d_idx, d_rho_residual, d_summation_rho, t): d_rho_residual[d_idx] = d_rho[d_idx] - d_summation_rho[d_idx] class DensityNewtonRaphsonIteration(Equation): r"""**Newton-Raphson approximate solution for the density equation at iteration k+1** .. math:: \rho^{(k+1)} = \rho_I^{(k)}\biggl[1 - \dfrac{R_I^{(k)}d_m}{( R_I^{(k)} d_m + \alpha_I^k)}\biggr] References ---------- .. [Rodriguez and Bonet, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def __init__(self, dest, sources=None, dim=2): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) """ self.dim = dim super(DensityNewtonRaphsonIteration, self).__init__(dest, sources) def initialize(self, d_rho, d_rho_prev_iter, d_idx): d_rho_prev_iter[d_idx] = d_rho[d_idx] def post_loop(self, d_rho, d_idx, d_alpha, d_rho_residual): a1 = d_rho_residual[d_idx] * self.dim a2 = a1 + d_alpha[d_idx] const = 1 - (a1/a2) d_rho[d_idx] = d_rho[d_idx] * const class CheckConvergence(Equation): r"""Stops the Newton-Raphson iterative procedure if the following convergence criteria is satisfied: .. math:: \dfrac{|R_I^{(k+1)}|}{\rho_I^{(k)}} \leq \epsilon where, \epsilon = 1e-15 References ---------- .. [<NAME>, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 Notes ----- Use this convergence criteria when using the Newton-Raphson iterative procedure. """ def __init__(self, dest, sources=None): super(CheckConvergence, self).__init__(dest, sources) self.eqn_has_converged = 0 def initialize(self): self.eqn_has_converged = 0 def post_loop(self, d_positive_rho_residual, d_rho_residual, d_rho_prev_iter, d_idx, t): d_positive_rho_residual[d_idx] = abs(d_rho_residual[d_idx]) def reduce(self, dst, t, dt): max_epsilon = max(dst.positive_rho_residual / dst.rho_prev_iter) if max_epsilon <= 1e-15: self.eqn_has_converged = 1 def converged(self): return self.eqn_has_converged class SWEOS(Equation): r"""**Update fluid properties based on density** References ---------- .. [Rodriguez and Bonet, 2005] <NAME> and <NAME>, "A corrected smooth particle hydrodynamics formulation of the shallow-water equations", Computers and Structures, 83 (2005), pp. 1396-1410 """ def __init__(self, dest, sources=None, g=9.81, rhow=1000.0): r""" Parameters ---------- g : float acceleration due to gravity rhow : float constant 3-D density of water """ self.rhow = rhow self.g = g self.fac = 0.5 * (g/rhow) super(SWEOS, self).__init__(dest, sources) def post_loop(self, d_rho, d_cs, d_u, d_v, d_idx, d_p, d_dw, d_dt_cfl, d_m, d_A, d_alpha): # Pressure d_p[d_idx] = self.fac * (d_rho[d_idx])**2 # Wave speed d_cs[d_idx] = sqrt(self.g * d_rho[d_idx]/self.rhow) # Area d_A[d_idx] = d_m[d_idx] / d_rho[d_idx] # Depth of water d_dw[d_idx] = d_rho[d_idx] / self.rhow # dt = CFL * (h_min / max(dt_cfl)) d_dt_cfl[d_idx] = d_cs[d_idx] + (d_u[d_idx]**2 + d_v[d_idx]**2)**0.5 def mu_calc(hi=1.0, hj=1.0, velij_dot_rij=1.0, rij2=1.0): r"""Term present in the artificial viscosity formulation (Monaghan) .. math:: \mu_{ij} = \dfrac{\bar h_{ij}\textbf{v}_{ij}.\textbf{x}_{ij}} {|\textbf{x}_{ij}|^2 + \zeta^2} References ---------- .. [Monaghan2005] <NAME>, "Smoothed particle hydrodynamics", Reports on Progress in Physics, 68 (2005), pp. 1703-1759. """ h_bar = (hi+hj) / 2.0 eta2 = 0.01 * hi**2 muij = (h_bar*velij_dot_rij) / (rij2+eta2) return muij def artificial_visc(alpha=1.0, rij2=1.0, hi=1.0, hj=1.0, rhoi=1.0, rhoj=1.0, csi=1.0, csj=1.0, muij=1.0): r"""**Artificial viscosity based stabilization term (Monaghan)** Activated when :math:`\textbf{v}_{ij}.\textbf{x}_{ij} < 0` Given by .. math:: \Pi_{ij} = \dfrac{-a\bar c_{ij}\mu_{ij}+b\bar c_{ij}\mu_{ij}^2}{\rho_{ij}} References ---------- .. [Monaghan2005] <NAME>, "Smoothed particle hydrodynamics", Reports on Progress in Physics, 68 (2005), pp. 1703-1759. """ cs_bar = (csi+csj) / 2.0 rho_bar = (rhoi+rhoj) / 2.0 pi_visc = -(alpha*cs_bar*muij) / rho_bar return pi_visc def viscosity_LF(alpha=1.0, rij2=1.0, hi=1.0, hj=1.0, rhoi=1.0, rhoj=1.0, csi=1.0, csj=1.0, muij=1.0): r"""**Lax-Friedrichs flux based stabilization term (Ata and Soulaimani)** .. math:: \Pi_{ij} = \dfrac{\bar c_{ij}\textbf{v}_{ij}.\textbf{x}_{ij}} {\bar\rho_{ij}\sqrt{|x_{ij}|^2 + \zeta^2}} References ---------- .. [Ata and Soulaimani, 2004] <NAME> and <NAME>, "A stabilized SPH method for inviscid shallow water", Int. J. Numer. Meth. Fluids, 47 (2005), pp. 139-159. Notes ----- The advantage of this term is that it automatically sets the required level of numerical viscosity based on the Lax-Friedrichs flux. This is the default stabilization method. """ cs_bar = (csi+csj) / 2.0 rho_bar = (rhoi+rhoj) / 2.0 eta2 = 0.01 * hi**2 h_bar = (hi+hj) / 2.0 tmp = (muij*(rij2+eta2)**0.5) / h_bar pi_visc = -(cs_bar*tmp) / rho_bar return pi_visc class ParticleAcceleration(Equation): r"""**Acceleration of a particle** .. math:: \textbf{a}_i = -\frac{g+\textbf{v}_i.\textbf{k}_i\textbf{v}_i -\textbf{t}_i.\nabla H_i}{1+\nabla H_i.\nabla H_i} \nabla H_i - \textbf{t}_i - \textbf{S}_{fi} where, .. math:: \textbf{t}_i &= \sum_j m_j\ \biggl[\biggl(\frac{p_j}{ \alpha_j \rho_j^2}+0.5\Pi_{ij}\biggr)\nabla W_j(\textbf{x}_i, h_j) - \biggl(\frac{p_i}{\alpha_i \rho_i^2}+0.5\Pi_{ij}\biggr)\nabla W_i(\textbf{x}_j, h_i)\biggr] .. math:: \textbf{S}_f = \textbf{v}\dfrac{gn^2|\textbf{v}|}{d^{\frac{4}{3}}} with, .. math:: \alpha_i = -\sum_j m_j r_{ij}\frac{dW_i}{dr_{ij}} .. math:: n_i = \sum_jn_j^b\overline W_i(x_i - x_j^b, h^b)V_j References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 Notes ----- The acceleration term given in [Vacondio2010] has incorrect sign. """ def __init__(self, dest, sources, dim=2, u_only=False, v_only=False, alpha=0.0, visc_option=2, rhow=1000.0): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) u_only : bool motion of fluid column in x-direction only evaluated (Default: False) v_only : bool motion of fluid column in y-direction only evaluated (Default: False) alpha : float coefficient to control amount of artificial viscosity (Monaghan) (Default: 0.0) visc_option : int artifical viscosity (1) or Lax-Friedrichs flux (2) based stabilization term (Default: 2) rhow : float constant 3-D density of water """ self.g = 9.81 self.rhow = rhow self.ct = self.g / (2*self.rhow) self.dim = dim self.u_only = u_only self.v_only = v_only self.alpha = alpha if visc_option == 1: self.viscous_func = artificial_visc else: self.viscous_func = viscosity_LF super(ParticleAcceleration, self).__init__(dest, sources) def initialize(self, d_idx, d_tu, d_tv): d_tu[d_idx] = 0.0 d_tv[d_idx] = 0.0 def loop(self, d_x, d_y, s_x, s_y, d_rho, d_idx, s_m, s_idx, s_rho, d_m, DWI, DWJ, d_au, d_av, s_alpha, d_alpha, s_p, d_p, d_tu, s_dw, d_dw, t, s_is_wall_boun_pa, s_tu, d_tv, s_tv, d_h, s_h, d_u, s_u, d_v, s_v, d_cs, s_cs): # True if neighbor is wall boundary particle if s_is_wall_boun_pa[s_idx] == 1: # Setting artificial viscosity to zero when a particle interacts # with wall boundary particles pi_visc = 0.0 # Setting water depth of wall boundary particles same as particle # interacting with it (For sufficient pressure to prevent wall # penetration) s_dw[s_idx] = d_dw[d_idx] else: uij = d_u[d_idx] - s_u[s_idx] vij = d_v[d_idx] - s_v[s_idx] xij = d_x[d_idx] - s_x[s_idx] yij = d_y[d_idx] - s_y[s_idx] rij2 = xij**2 + yij**2 uij_dot_xij = uij * xij vij_dot_yij = vij * yij velij_dot_rij = uij_dot_xij + vij_dot_yij muij = mu_calc(d_h[d_idx], s_h[s_idx], velij_dot_rij, rij2) if velij_dot_rij < 0: # Stabilization term pi_visc = self.viscous_func(self.alpha, rij2, d_h[d_idx], s_h[s_idx], d_rho[d_idx], s_rho[s_idx], d_cs[d_idx], s_cs[s_idx], muij) else: pi_visc = 0 tmp1 = (s_dw[s_idx]*self.rhow*self.dim) / s_alpha[s_idx] tmp2 = (d_dw[d_idx]*self.rhow*self.dim) / d_alpha[d_idx] # Internal force per unit mass d_tu[d_idx] += s_m[s_idx] * ((self.ct*tmp1 + 0.5*pi_visc)*DWJ[0] + (self.ct*tmp2 + 0.5*pi_visc)*DWI[0]) d_tv[d_idx] += s_m[s_idx] * ((self.ct*tmp1 + 0.5*pi_visc)*DWJ[1] + (self.ct*tmp2 + 0.5*pi_visc)*DWI[1]) def _get_helpers_(self): return [mu_calc, artificial_visc, viscosity_LF] def post_loop(self, d_idx, d_u, d_v, d_tu, d_tv, d_au, d_av, d_Sfx, d_Sfy, d_bx, d_by, d_bxx, d_bxy, d_byy): vikivi = d_u[d_idx]*d_u[d_idx]*d_bxx[d_idx] \ + 2*d_u[d_idx]*d_v[d_idx]*d_bxy[d_idx] \ + d_v[d_idx]*d_v[d_idx]*d_byy[d_idx] tidotgradbi = d_tu[d_idx]*d_bx[d_idx] + d_tv[d_idx]*d_by[d_idx] gradbidotgradbi = d_bx[d_idx]**2 + d_by[d_idx]**2 temp3 = self.g + vikivi - tidotgradbi temp4 = 1 + gradbidotgradbi if not self.v_only: # Acceleration along x-direction d_au[d_idx] = -(temp3/temp4)*d_bx[d_idx] - d_tu[d_idx] \ - d_Sfx[d_idx] if not self.u_only: # Acceleration along y-direction d_av[d_idx] = -(temp3/temp4)*d_by[d_idx] - d_tv[d_idx] \ - d_Sfy[d_idx] class FluidBottomElevation(Equation): r"""**Bottom elevation of fluid** .. math:: b_i = \sum_jb_j^b\overline{W_i}(\textbf{x}_i - \textbf{x}_j^b, h^b)V_j References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def initialize(self, d_b, d_idx): d_b[d_idx] = 0.0 def loop_all(self, d_shep_corr, d_x, d_y, d_idx, s_x, s_y, s_V, s_idx, s_h, SPH_KERNEL, NBRS, N_NBRS): # Shepard filter i = declare('int') xij = declare('matrix(3)') rij = 0.0 corr_sum = 0.0 for i in range(N_NBRS): s_idx = NBRS[i] xij[0] = d_x[d_idx] - s_x[s_idx] xij[1] = d_y[d_idx] - s_y[s_idx] rij = sqrt(xij[0]*xij[0] + xij[1]*xij[1]) corr_sum += s_V[s_idx] * SPH_KERNEL.kernel(xij, rij, s_h[s_idx]) d_shep_corr[d_idx] = corr_sum def loop(self, d_b, d_idx, s_b, s_idx, WJ, s_V, RIJ): d_b[d_idx] += s_b[s_idx] * WJ * s_V[s_idx] def post_loop(self, d_b, d_shep_corr, d_idx): if d_shep_corr[d_idx] > 1e-14: d_b[d_idx] /= d_shep_corr[d_idx] class FluidBottomGradient(Equation): r"""**Bottom gradient of fluid** .. math:: \nabla b_i &=& \sum_j\nabla b_j^b W_i(\textbf{x}_i - \textbf{x}_j^b, h^b)V_j Notes: It is obtained from a simple SPH interpolation from the gradient of bed particles """ def initialize(self, d_idx, d_bx, d_by): d_bx[d_idx] = 0.0 d_by[d_idx] = 0.0 def loop(self, d_idx, d_bx, d_by, WJ, s_idx, s_bx, s_by, s_V): # Bottom gradient of fluid d_bx[d_idx] += s_bx[s_idx] * WJ * s_V[s_idx] d_by[d_idx] += s_by[s_idx] * WJ * s_V[s_idx] class FluidBottomCurvature(Equation): r"""Bottom curvature of fluid** .. math:: \nabla^2 b_i = \sum_j\nabla^2 b_j^b W_i(\textbf{x}_i - \textbf{x}_j^b, h^b)V_j Notes: It is obtained from a simple SPH interpolation from the curvature of bed particles """ def initialize(self, d_idx, d_bx, d_by, d_bxx, d_bxy, d_byy): d_bxx[d_idx] = 0.0 d_bxy[d_idx] = 0.0 d_byy[d_idx] = 0.0 def loop(self, d_idx, d_bxx, d_bxy, d_byy, WJ, s_idx, s_bxx, s_bxy, s_byy, s_V): # Bottom curvature of fluid d_bxx[d_idx] += s_bxx[s_idx] * WJ * s_V[s_idx] d_bxy[d_idx] += s_bxy[s_idx] * WJ * s_V[s_idx] d_byy[d_idx] += s_byy[s_idx] * WJ * s_V[s_idx] class BedGradient(Equation): r"""**Gradient of bed** .. math:: \nabla b_i = \sum_jb_j^b\tilde{\nabla}W_i(\textbf{x}_i - \textbf{x}_j^b, h^b)V_j References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def initialize(self, d_bx, d_by, d_idx): d_bx[d_idx] = 0.0 d_by[d_idx] = 0.0 def loop(self, d_bx, d_by, d_idx, s_b, s_idx, DWJ, s_V, RIJ): if RIJ > 1e-6: # Gradient of bed d_bx[d_idx] += s_b[s_idx] * DWJ[0] * s_V[s_idx] d_by[d_idx] += s_b[s_idx] * DWJ[1] * s_V[s_idx] class BedCurvature(Equation): r"""**Curvature of bed** .. math:: \biggl(\dfrac{\partial^2b}{\partial x^\alpha \partial x^\beta} \biggr)_i = \sum_{j}^{}\biggl(4\dfrac{x_{ij}^\alphax_{ij}^\beta} {r_{ij}^2}-\delta^{\alpha\beta}\biggr)\dfrac{b_i - b_j^b}{ \textbf{r}_{ij}\textbf{r}_{ij} + \eta^2}\textbf{r}_{ij}.\tilde{\nabla} W_i(\textbf{x}_i - \textbf{x}_j^b, h^b)V_j References ---------- .. [Vacondio2010] <NAME>, <NAME> and <NAME>, "Accurate particle splitting for smoothed particle hydrodynamics in shallow water with shock capturing", Int. J. Numer. Meth. Fluids, 69 (2012), pp. 1377-1410 """ def initialize(self, d_bxx, d_bxy, d_byy, d_idx): d_bxx[d_idx] = 0.0 d_bxy[d_idx] = 0.0 d_byy[d_idx] = 0.0 def loop(self, d_bxx, d_bxy, d_byy, d_b, d_idx, s_h, s_b, s_idx, XIJ, RIJ, DWJ, s_V): if RIJ > 1e-6: eta = 0.01 * s_h[s_idx] temp1 = (d_b[d_idx]-s_b[s_idx]) / (RIJ**2+eta**2) temp2 = XIJ[0]*DWJ[0] + XIJ[1]*DWJ[1] temp_bxx = ((4*XIJ[0]**2/RIJ**2)-1) * temp1 temp_bxy = (4*XIJ[0]*XIJ[1]/RIJ**2) * temp1 temp_byy = ((4*XIJ[1]**2/RIJ**2)-1) * temp1 # Curvature of bed d_bxx[d_idx] += temp_bxx * temp2 * s_V[s_idx] d_bxy[d_idx] += temp_bxy * temp2 * s_V[s_idx] d_byy[d_idx] += temp_byy * temp2 * s_V[s_idx] class BedFrictionSourceEval(Equation): r"""**Friction source term** .. math:: \textbf{S}_f = \textbf{v}\dfrac{gn^2|\textbf{v}|}{d^{\frac{4}{3}}} where, .. math:: n_i = \sum_jn_j^b\overline W_i(x_i - x_j^b, h^b)V_j """ def __init__(self, dest, sources): self.g = 9.8 super(BedFrictionSourceEval, self).__init__(dest, sources) def initialize(self, d_n, d_idx): d_n[d_idx] = 0.0 def loop(self, d_n, d_idx, s_n, s_idx, WJ, s_V, RIJ): if RIJ > 1e-6: # Manning coefficient d_n[d_idx] += s_n[s_idx] * WJ * s_V[s_idx] def post_loop(self, d_idx, d_Sfx, d_Sfy, d_u, d_v, d_n, d_dw): vmag = sqrt(d_u[d_idx]**2 + d_v[d_idx]**2) temp = (self.g*d_n[d_idx]**2*vmag) / d_dw[d_idx]**(4.0/3.0) # Friction source term d_Sfx[d_idx] = d_u[d_idx] * temp d_Sfy[d_idx] = d_v[d_idx] * temp class BoundaryInnerReimannStateEval(Equation): r"""Evaluates the inner Riemann state of velocity and depth .. math:: \textbf{v}_i^o = \sum_j\dfrac{m_j^f}{\rho_j^f}\textbf{v}_j^f\bar W_i(\textbf{x}_i^o - \textbf{x}_j^f, h_o)\\ {d}_i^o = \sum_j\dfrac{m_j^f}{\rho_j^f}d_j^f\bar W_i(\textbf{x}_i^o - \textbf{x}_j^f, h_o) References ---------- .. [Vacondio2012] <NAME> et al., "SPH modeling of shallow flow with open boundaries for practical flood simulation", J. Hydraul. Eng., 2012, 138(6), pp. 530-541. """ def initialize(self, d_u_inner_reimann, d_v_inner_reimann, d_dw_inner_reimann, d_idx): d_u_inner_reimann[d_idx] = 0.0 d_v_inner_reimann[d_idx] = 0.0 d_dw_inner_reimann[d_idx] = 0.0 def loop_all(self, d_shep_corr, d_x, d_y, d_idx, s_x, s_y, s_m, s_rho, s_idx, d_h, SPH_KERNEL, NBRS, N_NBRS): # Shepard filter i = declare('int') xij = declare('matrix(3)') rij = 0.0 corr_sum = 0.0 for i in range(N_NBRS): s_idx = NBRS[i] xij[0] = d_x[d_idx] - s_x[s_idx] xij[1] = d_y[d_idx] - s_y[s_idx] rij = sqrt(xij[0]*xij[0] + xij[1]*xij[1]) corr_sum += ((s_m[s_idx]/s_rho[s_idx]) * SPH_KERNEL.kernel(xij, rij, d_h[d_idx])) d_shep_corr[d_idx] = corr_sum def loop(self, d_u_inner_reimann, d_v_inner_reimann, d_dw_inner_reimann, d_idx, WI, s_m, s_u, s_v, s_rho, s_dw, s_idx): tmp = WI * (s_m[s_idx]/s_rho[s_idx]) # Riemann invariants at open boundaries d_u_inner_reimann[d_idx] += s_u[s_idx] * tmp d_v_inner_reimann[d_idx] += s_v[s_idx] * tmp d_dw_inner_reimann[d_idx] += s_dw[s_idx] * tmp def post_loop(self, d_u_inner_reimann, d_v_inner_reimann, d_dw_inner_reimann, d_shep_corr, d_idx): if d_shep_corr[d_idx] > 1e-14: d_u_inner_reimann[d_idx] /= d_shep_corr[d_idx] d_v_inner_reimann[d_idx] /= d_shep_corr[d_idx] d_dw_inner_reimann[d_idx] /= d_shep_corr[d_idx] class SubCriticalInFlow(Equation): r"""**Subcritical inflow condition** ..math :: d_B = \biggl[\frac{1}{2\sqrt{g}}(v_{B,n}-v_{I,n}) + \sqrt{d_I}\biggr]^2 References ---------- .. [Vacondio2012] <NAME> et al., "SPH modeling of shallow flow with open boundaries for practical flood simulation", J. Hydraul. Eng., 2012, 138(6), pp. 530-541. Notes ----- The velocity is imposed at the open boundary. """ def __init__(self, dest, dim=2, rhow=1000.0): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) rhow : float constant 3-D density of water """ self.g = 9.8 self.dim = dim self.rhow = rhow super(SubCriticalInFlow, self).__init__(dest, None) def post_loop(self, d_dw, d_dw_inner_reimann, d_u, d_u_inner_reimann, d_rho, d_alpha, d_cs, d_idx): const = 1. / (2.*sqrt(self.g)) # Properties of open boundary particles d_dw[d_idx] = (const*(d_u_inner_reimann[d_idx] - d_u[d_idx]) + sqrt(d_dw_inner_reimann[d_idx]))**2 d_rho[d_idx] = d_dw[d_idx] * self.rhow d_alpha[d_idx] = self.dim * d_rho[d_idx] d_cs[d_idx] = sqrt(self.g * d_dw[d_idx]) class SubCriticalOutFlow(Equation): r"""**Subcritical outflow condition** ..math :: v_{B,n} = v_{I,n} + 2\sqrt{g}(\sqrt{d_I} - \sqrt{d_B}), v_{B,t} = v_{I,t} References ---------- .. [Vacondio2012] <NAME> et al., "SPH modeling of shallow flow with open boundaries for practical flood simulation", J. Hydraul. Eng., 2012, 138(6), pp. 530-541. Notes: ----- The constant water depth is imposed at the open boundary. """ def __init__(self, dest, dim=2, rhow=1000.0): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) rhow : float constant 3-D density of water """ self.g = 9.8 self.dim = dim self.rhow = rhow super(SubCriticalOutFlow, self).__init__(dest, None) def post_loop(self, d_dw, d_dw_inner_reimann, d_u, d_u_inner_reimann, d_rho, d_cs, d_alpha, d_v, d_v_inner_reimann, d_idx): const = 2. * sqrt(self.g) # Velocities of open boundary particles d_u[d_idx] = (d_u_inner_reimann[d_idx] + const*(sqrt(d_dw_inner_reimann[d_idx]) - sqrt(d_dw[d_idx]))) d_v[d_idx] = d_v_inner_reimann[d_idx] class SubCriticalTimeVaryingOutFlow(Equation): r"""**Subcritical outflow condition** ..math :: v_{B,n} = v_{I,n} + 2\sqrt{g}(\sqrt{d_I} - \sqrt{d_B}), v_{B,t} = v_{I,t} References ---------- .. [Vacondio2012] <NAME> et al., "SPH modeling of shallow flow with open boundaries for practical flood simulation", J. Hydraul. Eng., 2012, 138(6), pp. 530-541. Notes: ----- The time varying water depth is imposed at the open boundary. """ def __init__(self, dest, dim=2, rhow=1000.0): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) rhow : float constant 3-D density of water """ self.g = 9.8 self.dim = dim self.rhow = rhow super(SubCriticalTimeVaryingOutFlow, self).__init__(dest, None) def post_loop(self, d_dw, d_dw_inner_reimann, d_u, d_u_inner_reimann, d_rho, d_cs, d_alpha, d_v, d_v_inner_reimann, d_idx, d_dw_at_t): # Properties of open boundary particles # Time varying water depth imposed d_dw[d_idx] = d_dw_at_t[d_idx] d_rho[d_idx] = d_dw[d_idx] * self.rhow d_cs[d_idx] = sqrt(d_dw[d_idx] * self.g) d_alpha[d_idx] = d_rho[d_idx] * self.dim const = 2. * sqrt(self.g) d_u[d_idx] = (d_u_inner_reimann[d_idx] + const*(sqrt(d_dw_inner_reimann[d_idx]) - sqrt(d_dw[d_idx]))) d_v[d_idx] = d_v_inner_reimann[d_idx] class SuperCriticalOutFlow(Equation): r"""**Supercritical outflow condition** .. math:: v_{B,n} = v_{I,n}, v_{B,t} = v_{I,t}, d_B = d_I References ---------- .. [Vacondio2012] <NAME> et al., "SPH modeling of shallow flow with open boundaries for practical flood simulation", J. Hydraul. Eng., 2012, 138(6), pp. 530-541. Notes: ----- For supercritical outflow condition, the velocity and water depth at the open boundary equals the respective inner Riemann state values. For supercritical inflow condition, both the velocity and water depth at the open boundary have to be imposed. """ def __init__(self, dest, dim=2, rhow=1000.0): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) rhow : float constant 3-D density of water """ self.g = 9.8 self.dim = dim self.rhow = rhow super(SuperCriticalOutFlow, self).__init__(dest, None) def post_loop(self, d_dw, d_rho, d_dw_inner_reimann, d_u_inner_reimann, d_u, d_v, d_v_inner_reimann, d_alpha, d_cs, d_idx): # Properties of open boundary particles d_u[d_idx] = d_u_inner_reimann[d_idx] d_v[d_idx] = d_v_inner_reimann[d_idx] d_dw[d_idx] = d_dw_inner_reimann[d_idx] d_rho[d_idx] = d_dw[d_idx] * self.rhow d_alpha[d_idx] = self.dim * d_rho[d_idx] d_cs[d_idx] = sqrt(self.g * d_dw[d_idx]) class GradientCorrectionPreStep(Equation): def __init__(self, dest, sources, dim=2): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) """ self.dim = dim super(GradientCorrectionPreStep, self).__init__(dest, sources) def initialize(self, d_idx, d_m_mat): i = declare('int') for i in range(9): d_m_mat[9*d_idx + i] = 0.0 def loop_all(self, d_idx, d_m_mat, s_V, d_x, d_y, d_z, d_h, s_x, s_y, s_z, s_h, SPH_KERNEL, NBRS, N_NBRS): x = d_x[d_idx] y = d_y[d_idx] z = d_z[d_idx] h = d_h[d_idx] i, j, s_idx, n = declare('int', 4) xij = declare('matrix(3)') dwij = declare('matrix(3)') n = self.dim for k in range(N_NBRS): s_idx = NBRS[k] xij[0] = x - s_x[s_idx] xij[1] = y - s_y[s_idx] xij[2] = z - s_z[s_idx] hij = (h + s_h[s_idx]) * 0.5 r = sqrt(xij[0]*xij[0] + xij[1]*xij[1] + xij[2]*xij[2]) SPH_KERNEL.gradient(xij, r, hij, dwij) dw = sqrt(dwij[0]*dwij[0] + dwij[1]*dwij[1] + dwij[2]*dwij[2]) V = s_V[s_idx] if r >= 1.0e-12: for i in range(n): xi = xij[i] for j in range(n): xj = xij[j] d_m_mat[9*d_idx + 3*i + j] += (dw*V*xi*xj) / r class GradientCorrection(Equation): r"""**Kernel Gradient Correction** .. math:: \nabla \tilde{W}_{ab} = L_{a}\nabla W_{ab} .. math:: L_{a} = \left(\sum \frac{m_{b}}{\rho_{b}}\nabla W_{ab} \mathbf{\times}x_{ab} \right)^{-1} References ---------- .. [<NAME> Lok, 1999] <NAME> and <NAME>, "Variational and Momentum Preservation Aspects of Smoothed Particle Hydrodynamic Formulations", Comput. Methods Appl. Mech. Engrg., 180 (1999), pp. 97-115 """ def _get_helpers_(self): return [gj_solve, augmented_matrix] def __init__(self, dest, sources, dim=2, tol=0.5): r""" Parameters ---------- dim : int number of space dimensions (Default: 2) tol : float tolerance for gradient correction (Default: 0.5) """ self.dim = dim self.tol = tol super(GradientCorrection, self).__init__(dest, sources) def loop(self, d_idx, d_m_mat, DWJ, s_h, s_idx): i, j, n = declare('int', 3) n = self.dim temp = declare('matrix(9)') aug_m = declare('matrix(12)') res = declare('matrix(3)') eps = 1.0e-04 * s_h[s_idx] for i in range(n): for j in range(n): temp[n*i + j] = d_m_mat[9*d_idx + 3*i + j] augmented_matrix(temp, DWJ, n, 1, n, aug_m) gj_solve(aug_m, n, 1, res) change = 0.0 for i in range(n): change += abs(DWJ[i]-res[i]) / (abs(DWJ[i])+eps) if change <= self.tol: for i in range(n): DWJ[i] = res[i] class RemoveOutofDomainParticles(Equation): r"""Removes particles if the following condition is satisfied: .. math:: (x_i < x_min) or (x_i > x_max) or (y_i < y_min) or (y_i > y_max) """ def __init__(self, dest, x_min=-1e9, x_max=1e9, y_min=-1e9, y_max=1e9): r""" Parameters ---------- x_min : float minimum distance along x-direction below which particles are removed x_max : float maximum distance along x-direction above which particles are removed y_min : float minimum distance along y-direction below which particles are removed y_max : float maximum distance along x-direction above which particles are removed """ self.x_min = x_min self.x_max = x_max self.y_min = y_min self.y_max = y_max super(RemoveOutofDomainParticles, self).__init__(dest, None) def initialize(self, d_pa_out_of_domain, d_x, d_y, d_idx): if ( (d_x[d_idx] < self.x_min or d_x[d_idx] > self.x_max) or (d_y[d_idx] < self.y_min or d_y[d_idx] > self.y_max) ): d_pa_out_of_domain[d_idx] = 1 else: d_pa_out_of_domain[d_idx] = 0 def reduce(self, dst, t, dt): indices = declare('object') indices = numpy.where(dst.pa_out_of_domain > 0)[0] # Removes the out of domain particles if len(indices) > 0: dst.remove_particles(indices) class RemoveCloseParticlesAtOpenBoundary(Equation): r"""Removes the newly created open boundary particle if the distance between this particle and any of its neighbor is less than min_dist_ob The following cases creates new open boundary particles * Particles which are moved back to the inlet after exiting the inlet. * Particles which have moved from another domain into the open boundary and have been converted to open boundary particles. References ---------- .. [VacondioSWE-SPHysics, 2013] <NAME> et al., SWE-SPHysics source code, File: SWE_SPHYsics/SWE-SPHysics_2D_v1.0.00/source/SPHYSICS_SWE_2D/ check_limits_2D.f """ def __init__(self, dest, sources, min_dist_ob=0.0): """ Parameters ---------- min_dist_ob : float minimum distance of a newly created open boundary particle and its neighbor below which the particle is removed """ self.min_dist_ob = min_dist_ob super(RemoveCloseParticlesAtOpenBoundary, self).__init__(dest, sources) def loop_all(self, d_idx, d_ob_pa_to_tag, d_ob_pa_to_remove, d_x, d_y, s_x, s_y, NBRS, N_NBRS): i = declare('int') s_idx = declare('unsigned int') # ob_pa_to_tag is 1 for newly created open boundary particles if d_ob_pa_to_tag[d_idx]: xi = d_x[d_idx] yi = d_y[d_idx] for i in range(N_NBRS): s_idx = NBRS[i] if s_idx == d_idx: continue xij = xi - s_x[s_idx] yij = yi - s_y[s_idx] rij = sqrt(xij*xij + yij*yij) if rij < self.min_dist_ob: d_ob_pa_to_remove[d_idx] = 1 def reduce(self, dst, t, dt): indices = declare('object') indices = numpy.where(dst.ob_pa_to_remove > 0)[0] if len(indices) > 0: dst.remove_particles(indices) dst.ob_pa_to_tag = numpy.zeros_like(dst.ob_pa_to_tag) class RemoveFluidParticlesWithNoNeighbors(Equation): r"""Removes fluid particles if there exists no neighboring particles within its kernel radius (2*smoothing length) """ def loop_all(self, d_idx, d_ob_pa_to_tag, d_fluid_pa_to_remove, d_x, d_y, s_x, s_y, d_h, NBRS, N_NBRS): i, n_nbrs_outside_ker = declare('int', 2) s_idx = declare('unsigned int') xi = d_x[d_idx] yi = d_y[d_idx] # Number of neighbors outside the particles kernel radius n_nbrs_outside_ker = 0 for i in range(N_NBRS): s_idx = NBRS[i] if s_idx == d_idx: continue xij = xi - s_x[s_idx] yij = yi - s_y[s_idx] rij = sqrt(xij*xij + yij*yij) if rij > 2*d_h[d_idx]: n_nbrs_outside_ker += 1 # If all neighbors outside its kernel then tag particle for removal if n_nbrs_outside_ker == N_NBRS-1: d_fluid_pa_to_remove[d_idx] = 1 else: d_fluid_pa_to_remove[d_idx] = 0 def reduce(self, dst, t, dt): indices = declare('object') indices = numpy.where(dst.fluid_pa_to_remove > 0)[0] if len(indices) > 0: dst.remove_particles(indices) class SWEInletOutletStep(IntegratorStep): r"""Stepper for both inlet and outlet particles for the cases dealing with shallow water flows """ def initialize(self): pass def stage1(self, d_idx, d_x, d_y, d_uh, d_vh, d_u, d_v, dt): dtb2 = 0.5*dt d_uh[d_idx] = d_u[d_idx] d_vh[d_idx] = d_v[d_idx] d_x[d_idx] += dtb2 * d_u[d_idx] d_y[d_idx] += dtb2 * d_v[d_idx] def stage2(self, d_idx, d_x, d_y, d_u, d_v, dt): dtb2 = 0.5*dt d_x[d_idx] += dtb2 * d_u[d_idx] d_y[d_idx] += dtb2 * d_v[d_idx] class SWEInlet(object): """This inlet is used for shallow water flows. It has particles stacked along a particular axis (defaults to 'x'). These particles can move along any direction and as they flow out of the domain they are copied into the destination particle array at each timestep. Inlet particles are stacked by subtracting the spacing amount from the existing inlet array. These are copied when the inlet is created. The particles that cross the inlet domain are copied over to the destination particle array and moved back to the other side of the inlet. The particles from the source particle array which have moved to the inlet domain are removed from the source and added to the inlet particle array. The motion of the particles can be along any direction required. One can set the 'u' velocity to have a parabolic profile in the 'y' direction if so desired. """ def __init__(self, inlet_pa, dest_pa, source_pa, spacing, n=5, axis='x', xmin=-1.0, xmax=1.0, ymin=-1.0, ymax=1.0, callback=None): """Constructor. Note that the inlet must be defined such that the spacing times the number of stacks of particles is equal to the length of the domain in the stacked direction. For example, if particles are stacked along the 'x' axis and n=5 with spacing 0.1, then xmax - xmin should be 0.5. Parameters ---------- inlet_pa: ParticleArray Particle array for the inlet particles. dest_pa: ParticleArray Particle array for the destination into which inlet flows. source_pa : ParticleArray Particle array from which the particles flow in. spacing: float Spacing of particles in the inlet domain. n: int Total number of copies of the initial particles. axis: str Axis along which to stack particles, one of 'x', 'y'. xmin, xmax, ymin, ymax : float Domain of the outlet. """ self.inlet_pa = inlet_pa self.dest_pa = dest_pa self.spacing = spacing self.source_pa = source_pa self.callback = callback assert axis in ('x', 'y') self.axis = axis self.n = n self.xmin, self.xmax = xmin, xmax self.ymin, self.ymax = ymin, ymax self._create_inlet_particles() def _create_inlet_particles(self): props = self.inlet_pa.get_property_arrays() inlet_props = {} for prop, array in props.items(): new_array = np.array([], dtype=array.dtype) for i in range(1, self.n): if prop == self.axis: new_array = np.append(new_array, array - i*self.spacing) else: new_array = np.append(new_array, array) inlet_props[prop] = new_array self.inlet_pa.add_particles(**inlet_props) def update(self, t, dt, stage): """This is called by the solver after each timestep and is passed the solver instance. """ pa_add = {} inlet_pa = self.inlet_pa xmin, xmax, ymin, ymax = self.xmin, self.xmax, self.ymin, self.ymax lx, ly = xmax - xmin, ymax - ymin x, y = inlet_pa.x, inlet_pa.y xcond = (x > xmax) ycond = (y > ymax) # All the indices of particles which have left. all_idx = np.where(xcond | ycond)[0] # The indices which need to be wrapped around. x_idx = np.where(xcond)[0] y_idx = np.where(ycond)[0] # Adding particles to the destination array. props = inlet_pa.get_property_arrays() for prop, array in props.items(): pa_add[prop] = np.array(array[all_idx]) self.dest_pa.add_particles(**pa_add) # Moving the moved particles back to the array beginning. inlet_pa.x[x_idx] -= np.sign(inlet_pa.x[x_idx] - xmax)*lx inlet_pa.y[y_idx] -= np.sign(inlet_pa.y[y_idx] - ymax)*ly # Tags the particles which have been moved back to inlet. These tagged # particles are then used for checking minimum spacing condition # with other open boundary particles. inlet_pa.ob_pa_to_tag[all_idx] = 1 source_pa = self.source_pa x, y = source_pa.x, source_pa.y idx = np.where((x <= xmax) & (x >= xmin) & (y <= ymax) & (y >= ymin))[0] # Adding particles to the destination array. pa_add = {} props = source_pa.get_property_arrays() for prop, array in props.items(): pa_add[prop] = np.array(array[idx]) # Tags the particles which have been added to the destination array # from the source array. These tagged particles are then used for # checking minimum spacing condition with other open boundary # particles. pa_add['ob_pa_to_tag'] = np.ones_like(pa_add['ob_pa_to_tag']) if self.callback is not None: self.callback(inlet_pa, pa_add) inlet_pa.add_particles(**pa_add) source_pa.remove_particles(idx) # Removing the particles that moved out of inlet x, y = inlet_pa.x, inlet_pa.y idx = np.where((x > xmax) | (x < xmin) | (y > ymax) | (y < ymin))[0] inlet_pa.remove_particles(idx)
[ "numpy.ones_like", "numpy.tile", "numpy.abs", "numpy.sqrt", "numpy.repeat", "numpy.where", "pysph.sph.wc.linalg.augmented_matrix", "compyle.api.declare", "pysph.sph.wc.linalg.gj_solve", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.append", "numpy.arctan2", "numpy.sign", "numpy.cos...
[((6891, 6916), 'numpy.array', 'np.array', (['idx_pa_to_split'], {}), '(idx_pa_to_split)\n', (6899, 6916), True, 'import numpy as np\n'), ((7159, 7167), 'numpy.zeros', 'zeros', (['n'], {}), '(n)\n', (7164, 7167), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((10557, 10571), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (10564, 10571), False, 'from compyle.api import declare\n'), ((10588, 10603), 'compyle.api.declare', 'declare', (['"""long"""'], {}), "('long')\n", (10595, 10603), False, 'from compyle.api import declare\n'), ((14069, 14086), 'compyle.api.declare', 'declare', (['"""int"""', '(2)'], {}), "('int', 2)\n", (14076, 14086), False, 'from compyle.api import declare\n'), ((14103, 14126), 'compyle.api.declare', 'declare', (['"""unsigned int"""'], {}), "('unsigned int')\n", (14110, 14126), False, 'from compyle.api import declare\n'), ((14977, 14991), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (14984, 14991), False, 'from compyle.api import declare\n'), ((15006, 15026), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (15013, 15026), False, 'from compyle.api import declare\n'), ((15041, 15061), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (15048, 15061), False, 'from compyle.api import declare\n'), ((17235, 17252), 'compyle.api.declare', 'declare', (['"""object"""'], {}), "('object')\n", (17242, 17252), False, 'from compyle.api import declare\n'), ((17931, 17945), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (17938, 17945), False, 'from compyle.api import declare\n'), ((17962, 17977), 'compyle.api.declare', 'declare', (['"""long"""'], {}), "('long')\n", (17969, 17977), False, 'from compyle.api import declare\n'), ((17992, 18012), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (17999, 18012), False, 'from compyle.api import declare\n'), ((24623, 24640), 'compyle.api.declare', 'declare', (['"""object"""'], {}), "('object')\n", (24630, 24640), False, 'from compyle.api import declare\n'), ((33099, 33138), 'numpy.sqrt', 'sqrt', (['(self.g * d_rho[d_idx] / self.rhow)'], {}), '(self.g * d_rho[d_idx] / self.rhow)\n', (33103, 33138), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((41693, 41707), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (41700, 41707), False, 'from compyle.api import declare\n'), ((41722, 41742), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (41729, 41742), False, 'from compyle.api import declare\n'), ((46634, 46673), 'numpy.sqrt', 'sqrt', (['(d_u[d_idx] ** 2 + d_v[d_idx] ** 2)'], {}), '(d_u[d_idx] ** 2 + d_v[d_idx] ** 2)\n', (46638, 46673), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((47824, 47838), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (47831, 47838), False, 'from compyle.api import declare\n'), ((47853, 47873), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (47860, 47873), False, 'from compyle.api import declare\n'), ((50300, 50326), 'numpy.sqrt', 'sqrt', (['(self.g * d_dw[d_idx])'], {}), '(self.g * d_dw[d_idx])\n', (50304, 50326), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((52888, 52914), 'numpy.sqrt', 'sqrt', (['(d_dw[d_idx] * self.g)'], {}), '(d_dw[d_idx] * self.g)\n', (52892, 52914), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((54696, 54722), 'numpy.sqrt', 'sqrt', (['(self.g * d_dw[d_idx])'], {}), '(self.g * d_dw[d_idx])\n', (54700, 54722), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((55097, 55111), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (55104, 55111), False, 'from compyle.api import declare\n'), ((55424, 55441), 'compyle.api.declare', 'declare', (['"""int"""', '(4)'], {}), "('int', 4)\n", (55431, 55441), False, 'from compyle.api import declare\n'), ((55456, 55476), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (55463, 55476), False, 'from compyle.api import declare\n'), ((55492, 55512), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (55499, 55512), False, 'from compyle.api import declare\n'), ((57279, 57296), 'compyle.api.declare', 'declare', (['"""int"""', '(3)'], {}), "('int', 3)\n", (57286, 57296), False, 'from compyle.api import declare\n'), ((57333, 57353), 'compyle.api.declare', 'declare', (['"""matrix(9)"""'], {}), "('matrix(9)')\n", (57340, 57353), False, 'from compyle.api import declare\n'), ((57370, 57391), 'compyle.api.declare', 'declare', (['"""matrix(12)"""'], {}), "('matrix(12)')\n", (57377, 57391), False, 'from compyle.api import declare\n'), ((57406, 57426), 'compyle.api.declare', 'declare', (['"""matrix(3)"""'], {}), "('matrix(3)')\n", (57413, 57426), False, 'from compyle.api import declare\n'), ((57587, 57630), 'pysph.sph.wc.linalg.augmented_matrix', 'augmented_matrix', (['temp', 'DWJ', 'n', '(1)', 'n', 'aug_m'], {}), '(temp, DWJ, n, 1, n, aug_m)\n', (57603, 57630), False, 'from pysph.sph.wc.linalg import gj_solve, augmented_matrix\n'), ((57639, 57665), 'pysph.sph.wc.linalg.gj_solve', 'gj_solve', (['aug_m', 'n', '(1)', 'res'], {}), '(aug_m, n, 1, res)\n', (57647, 57665), False, 'from pysph.sph.wc.linalg import gj_solve, augmented_matrix\n'), ((59246, 59263), 'compyle.api.declare', 'declare', (['"""object"""'], {}), "('object')\n", (59253, 59263), False, 'from compyle.api import declare\n'), ((60652, 60666), 'compyle.api.declare', 'declare', (['"""int"""'], {}), "('int')\n", (60659, 60666), False, 'from compyle.api import declare\n'), ((60683, 60706), 'compyle.api.declare', 'declare', (['"""unsigned int"""'], {}), "('unsigned int')\n", (60690, 60706), False, 'from compyle.api import declare\n'), ((61266, 61283), 'compyle.api.declare', 'declare', (['"""object"""'], {}), "('object')\n", (61273, 61283), False, 'from compyle.api import declare\n'), ((61440, 61474), 'numpy.zeros_like', 'numpy.zeros_like', (['dst.ob_pa_to_tag'], {}), '(dst.ob_pa_to_tag)\n', (61456, 61474), False, 'import numpy\n'), ((61819, 61836), 'compyle.api.declare', 'declare', (['"""int"""', '(2)'], {}), "('int', 2)\n", (61826, 61836), False, 'from compyle.api import declare\n'), ((61853, 61876), 'compyle.api.declare', 'declare', (['"""unsigned int"""'], {}), "('unsigned int')\n", (61860, 61876), False, 'from compyle.api import declare\n'), ((62597, 62614), 'compyle.api.declare', 'declare', (['"""object"""'], {}), "('object')\n", (62604, 62614), False, 'from compyle.api import declare\n'), ((68299, 68335), 'numpy.ones_like', 'np.ones_like', (["pa_add['ob_pa_to_tag']"], {}), "(pa_add['ob_pa_to_tag'])\n", (68311, 68335), True, 'import numpy as np\n'), ((5080, 5112), 'numpy.repeat', 'np.repeat', (['u_prev_step_parent', 'n'], {}), '(u_prev_step_parent, n)\n', (5089, 5112), True, 'import numpy as np\n'), ((5149, 5181), 'numpy.repeat', 'np.repeat', (['v_prev_step_parent', 'n'], {}), '(v_prev_step_parent, n)\n', (5158, 5181), True, 'import numpy as np\n'), ((5570, 5595), 'numpy.repeat', 'np.repeat', (['rho0_parent', 'n'], {}), '(rho0_parent, n)\n', (5579, 5595), True, 'import numpy as np\n'), ((5624, 5648), 'numpy.repeat', 'np.repeat', (['rho_parent', 'n'], {}), '(rho_parent, n)\n', (5633, 5648), True, 'import numpy as np\n'), ((5679, 5705), 'numpy.repeat', 'np.repeat', (['alpha_parent', 'n'], {}), '(alpha_parent, n)\n', (5688, 5705), True, 'import numpy as np\n'), ((5741, 5775), 'numpy.repeat', 'np.repeat', (['self.idx_pa_to_split', 'n'], {}), '(self.idx_pa_to_split, n)\n', (5750, 5775), True, 'import numpy as np\n'), ((7486, 7516), 'numpy.arctan2', 'np.arctan2', (['v_parent', 'u_parent'], {}), '(v_parent, u_parent)\n', (7496, 7516), True, 'import numpy as np\n'), ((7674, 7718), 'numpy.tile', 'np.tile', (['theta_vertex_pa', 'num_of_pa_to_split'], {}), '(theta_vertex_pa, num_of_pa_to_split)\n', (7681, 7718), True, 'import numpy as np\n'), ((7745, 7768), 'numpy.repeat', 'np.repeat', (['angle_vel', 'n'], {}), '(angle_vel, n)\n', (7754, 7768), True, 'import numpy as np\n'), ((7807, 7829), 'numpy.repeat', 'np.repeat', (['h_parent', 'n'], {}), '(h_parent, n)\n', (7816, 7829), True, 'import numpy as np\n'), ((7866, 7888), 'numpy.repeat', 'np.repeat', (['h_parent', 'n'], {}), '(h_parent, n)\n', (7875, 7888), True, 'import numpy as np\n'), ((17271, 17297), 'numpy.where', 'numpy.where', (['(dst.merge > 0)'], {}), '(dst.merge > 0)\n', (17282, 17297), False, 'import numpy\n'), ((24659, 24693), 'numpy.where', 'numpy.where', (['(dst.pa_alpha_zero > 0)'], {}), '(dst.pa_alpha_zero > 0)\n', (24670, 24693), False, 'import numpy\n'), ((28299, 28323), 'numpy.exp', 'exp', (['d_exp_lambda[d_idx]'], {}), '(d_exp_lambda[d_idx])\n', (28302, 28323), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((41952, 41991), 'numpy.sqrt', 'sqrt', (['(xij[0] * xij[0] + xij[1] * xij[1])'], {}), '(xij[0] * xij[0] + xij[1] * xij[1])\n', (41956, 41991), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((48083, 48122), 'numpy.sqrt', 'sqrt', (['(xij[0] * xij[0] + xij[1] * xij[1])'], {}), '(xij[0] * xij[0] + xij[1] * xij[1])\n', (48087, 48122), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((51356, 51368), 'numpy.sqrt', 'sqrt', (['self.g'], {}), '(self.g)\n', (51360, 51368), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((52986, 52998), 'numpy.sqrt', 'sqrt', (['self.g'], {}), '(self.g)\n', (52990, 52998), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((55759, 55816), 'numpy.sqrt', 'sqrt', (['(xij[0] * xij[0] + xij[1] * xij[1] + xij[2] * xij[2])'], {}), '(xij[0] * xij[0] + xij[1] * xij[1] + xij[2] * xij[2])\n', (55763, 55816), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((55879, 55942), 'numpy.sqrt', 'sqrt', (['(dwij[0] * dwij[0] + dwij[1] * dwij[1] + dwij[2] * dwij[2])'], {}), '(dwij[0] * dwij[0] + dwij[1] * dwij[1] + dwij[2] * dwij[2])\n', (55883, 55942), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((59282, 59319), 'numpy.where', 'numpy.where', (['(dst.pa_out_of_domain > 0)'], {}), '(dst.pa_out_of_domain > 0)\n', (59293, 59319), False, 'import numpy\n'), ((61302, 61338), 'numpy.where', 'numpy.where', (['(dst.ob_pa_to_remove > 0)'], {}), '(dst.ob_pa_to_remove > 0)\n', (61313, 61338), False, 'import numpy\n'), ((62224, 62251), 'numpy.sqrt', 'sqrt', (['(xij * xij + yij * yij)'], {}), '(xij * xij + yij * yij)\n', (62228, 62251), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((62633, 62672), 'numpy.where', 'numpy.where', (['(dst.fluid_pa_to_remove > 0)'], {}), '(dst.fluid_pa_to_remove > 0)\n', (62644, 62672), False, 'import numpy\n'), ((65948, 65979), 'numpy.array', 'np.array', (['[]'], {'dtype': 'array.dtype'}), '([], dtype=array.dtype)\n', (65956, 65979), True, 'import numpy as np\n'), ((66799, 66822), 'numpy.where', 'np.where', (['(xcond | ycond)'], {}), '(xcond | ycond)\n', (66807, 66822), True, 'import numpy as np\n'), ((66897, 66912), 'numpy.where', 'np.where', (['xcond'], {}), '(xcond)\n', (66905, 66912), True, 'import numpy as np\n'), ((66932, 66947), 'numpy.where', 'np.where', (['ycond'], {}), '(ycond)\n', (66940, 66947), True, 'import numpy as np\n'), ((67121, 67145), 'numpy.array', 'np.array', (['array[all_idx]'], {}), '(array[all_idx])\n', (67129, 67145), True, 'import numpy as np\n'), ((67287, 67320), 'numpy.sign', 'np.sign', (['(inlet_pa.x[x_idx] - xmax)'], {}), '(inlet_pa.x[x_idx] - xmax)\n', (67294, 67320), True, 'import numpy as np\n'), ((67353, 67386), 'numpy.sign', 'np.sign', (['(inlet_pa.y[y_idx] - ymax)'], {}), '(inlet_pa.y[y_idx] - ymax)\n', (67360, 67386), True, 'import numpy as np\n'), ((67722, 67785), 'numpy.where', 'np.where', (['((x <= xmax) & (x >= xmin) & (y <= ymax) & (y >= ymin))'], {}), '((x <= xmax) & (x >= xmin) & (y <= ymax) & (y >= ymin))\n', (67730, 67785), True, 'import numpy as np\n'), ((68003, 68023), 'numpy.array', 'np.array', (['array[idx]'], {}), '(array[idx])\n', (68011, 68023), True, 'import numpy as np\n'), ((68612, 68671), 'numpy.where', 'np.where', (['((x > xmax) | (x < xmin) | (y > ymax) | (y < ymin))'], {}), '((x > xmax) | (x < xmin) | (y > ymax) | (y < ymin))\n', (68620, 68671), True, 'import numpy as np\n'), ((4952, 4974), 'numpy.repeat', 'np.repeat', (['h_parent', 'n'], {}), '(h_parent, n)\n', (4961, 4974), True, 'import numpy as np\n'), ((5020, 5043), 'numpy.repeat', 'np.repeat', (['h0_parent', 'n'], {}), '(h0_parent, n)\n', (5029, 5043), True, 'import numpy as np\n'), ((5235, 5257), 'numpy.repeat', 'np.repeat', (['m_parent', 'n'], {}), '(m_parent, n)\n', (5244, 5257), True, 'import numpy as np\n'), ((5449, 5471), 'numpy.repeat', 'np.repeat', (['x_parent', 'n'], {}), '(x_parent, n)\n', (5458, 5471), True, 'import numpy as np\n'), ((5517, 5539), 'numpy.repeat', 'np.repeat', (['y_parent', 'n'], {}), '(y_parent, n)\n', (5526, 5539), True, 'import numpy as np\n'), ((7787, 7804), 'numpy.cos', 'cos', (['angle_actual'], {}), '(angle_actual)\n', (7790, 7804), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((7846, 7863), 'numpy.sin', 'sin', (['angle_actual'], {}), '(angle_actual)\n', (7849, 7863), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((14657, 14684), 'numpy.sqrt', 'sqrt', (['(xij * xij + yij * yij)'], {}), '(xij * xij + yij * yij)\n', (14661, 14684), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((18412, 18451), 'numpy.sqrt', 'sqrt', (['(xij[0] * xij[0] + xij[1] * xij[1])'], {}), '(xij[0] * xij[0] + xij[1] * xij[1])\n', (18416, 18451), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((49990, 50002), 'numpy.sqrt', 'sqrt', (['self.g'], {}), '(self.g)\n', (49994, 50002), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((50146, 50177), 'numpy.sqrt', 'sqrt', (['d_dw_inner_reimann[d_idx]'], {}), '(d_dw_inner_reimann[d_idx])\n', (50150, 50177), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((61097, 61124), 'numpy.sqrt', 'sqrt', (['(xij * xij + yij * yij)'], {}), '(xij * xij + yij * yij)\n', (61101, 61124), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((7420, 7436), 'numpy.abs', 'np.abs', (['u_parent'], {}), '(u_parent)\n', (7426, 7436), True, 'import numpy as np\n'), ((7448, 7464), 'numpy.abs', 'np.abs', (['v_parent'], {}), '(v_parent)\n', (7454, 7464), True, 'import numpy as np\n'), ((15899, 15938), 'numpy.sqrt', 'sqrt', (['(xma[0] * xma[0] + xma[1] * xma[1])'], {}), '(xma[0] * xma[0] + xma[1] * xma[1])\n', (15903, 15938), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((15961, 16000), 'numpy.sqrt', 'sqrt', (['(xmb[0] * xmb[0] + xmb[1] * xmb[1])'], {}), '(xmb[0] * xmb[0] + xmb[1] * xmb[1])\n', (15965, 16000), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((16750, 16804), 'numpy.sqrt', 'sqrt', (['(7 * M_PI / 10.0 * (m_merged / (const1 + const2)))'], {}), '(7 * M_PI / 10.0 * (m_merged / (const1 + const2)))\n', (16754, 16804), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((51495, 51526), 'numpy.sqrt', 'sqrt', (['d_dw_inner_reimann[d_idx]'], {}), '(d_dw_inner_reimann[d_idx])\n', (51499, 51526), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((51560, 51577), 'numpy.sqrt', 'sqrt', (['d_dw[d_idx]'], {}), '(d_dw[d_idx])\n', (51564, 51577), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((53077, 53108), 'numpy.sqrt', 'sqrt', (['d_dw_inner_reimann[d_idx]'], {}), '(d_dw_inner_reimann[d_idx])\n', (53081, 53108), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((53142, 53159), 'numpy.sqrt', 'sqrt', (['d_dw[d_idx]'], {}), '(d_dw[d_idx])\n', (53146, 53159), False, 'from numpy import sqrt, cos, sin, zeros, pi, exp\n'), ((66089, 66135), 'numpy.append', 'np.append', (['new_array', '(array - i * self.spacing)'], {}), '(new_array, array - i * self.spacing)\n', (66098, 66135), True, 'import numpy as np\n'), ((66188, 66215), 'numpy.append', 'np.append', (['new_array', 'array'], {}), '(new_array, array)\n', (66197, 66215), True, 'import numpy as np\n')]
""" NonParametric statistical tests Created by <NAME> on 27-02-2018. Copyright (c) 2018 DvM. All rights reserved. """ import cv2 import numpy as np from math import sqrt from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp from IPython import embed def permutationTTest(X1, X2, nr_perm): ''' ''' # check whether X2 is a chance variable or a data array if isinstance(X2, (float, int)): X2 = np.tile(X2, X1.shape) X = X1 - X2 # calculate T statistic nr_obs = X.shape[0] nr_test = X.shape[1:] T_0 = X.mean(axis = 0)/(X.std(axis = 0)/sqrt(nr_obs)) # calculate surrogate T distribution surr = np.copy(X) T_p = np.stack([np.zeros(nr_test) for i in range(nr_perm)], axis = 0) for p in range(nr_perm): perms = np.array(np.random.randint(2,size = X.shape), dtype = bool) surr[perms] *= -1 T_p[p] = surr.mean(axis = 0)/(surr.std(axis = 0)/sqrt(nr_obs)) # check how often surrogate T exceeds real T value thresh = np.sum(np.array((T_p > T_0),dtype = float), axis = 0) p_value = thresh/nr_perm return p_value, T_0 def clusterBasedPermutation(X1, X2, p_val = 0.05, cl_p_val = 0.05, paired = True, tail = 'both', nr_perm = 1000, mask = None, conn = None): ''' Implements Maris, E., & Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG- data. Journal of Neurosience Methods, 164(1), 177?190. http://doi.org/10.1016/J.Jneumeth.2007.03.024 Arguments - - - - - X1 (array): subject X dim1 X dim2 (optional), where dim1 and dim2 can be any type of dimension (time, frequency, electrode, etc). Values in array represent some dependent measure (e.g classification accuracy or power) X2 (array | float): either a datamatrix with same dimensions as X1, or a single value against which X1 will be tested p_val (float): p_value used for inclusion into the cluster cl_p_val (float): p_value for evaluation overall cluster significance paired (bool): paired t testing (True) or independent t testing (False) tail (str): apply one- or two- tailed t testing nr_perm (int): number of permutations mask (array): dim1 X dim2 array. Can be used to restrict cluster based test to a specific region. conn (array): outlines which dim1 points are connected to other dim1 points. Usefull when doing a cluster based permutation test across electrodes Returns - - - - cl_p_vals (array): dim1 X dim2 with p-values < cl_p_val for significant clusters and 1's for all other clusters ''' # if no mask is provided include all datapoints in analysis if mask == None: mask = np.array(np.ones(X1.shape[1:]),dtype = bool) print('\nUsing all {} datapoints in cluster based permutation'.format(mask.size), end = '\r') elif mask.shape != X1[0].shape: print('\nMask does not have the same shape as X1. Adjust mask!') else: print('\nThere are {} out of {} datapoints in your mask during cluster based permutation'.format(int(mask.sum()), mask.size)) # check whether X2 is a chance variable or a data array if isinstance(X2, (float, int)): X2 = np.tile(X2, X1.shape) # compute observed cluster statistics pos_sizes, neg_sizes, pos_labels, neg_labels, sig_cl = computeClusterSizes(X1, X2, p_val, paired, tail, mask, conn) cl_p_vals = np.ones(sig_cl.shape) # iterate to determine how often permuted clusters exceed the observed cluster threshold c_pos_cl = np.zeros(np.max(np.unique(pos_labels))) c_neg_cl = np.zeros(np.max(np.unique(neg_labels))) # initiate random arrays X1_rand = np.zeros(X1.shape) X2_rand = np.zeros(X1.shape) for p in range(nr_perm): #print("\r{0}% of permutations".format((float(p)/nr_perm)*100),) # create random partitions if paired: # keep observations paired under permutation rand_idx = np.random.rand(X1.shape[0])<0.5 X1_rand[rand_idx,:] = X1[rand_idx,:] X1_rand[~rand_idx,:] = X2[~rand_idx,:] X2_rand[rand_idx,:] = X2[rand_idx,:] X2_rand[~rand_idx,:] = X1[~rand_idx,:] else: # fully randomize observations under permutation all_X = np.vstack((X1,X2)) all_X = all_X[np.random.permutation(all_X.shape[0]),:] X1_rand = all_X[:X1.shape[0],:] X2_rand = all_X[X1.shape[0]:,:] # compute cluster statistics under random permutation rand_pos_sizes, rand_neg_sizes, _, _, _ = computeClusterSizes(X1_rand, X2_rand, p_val, paired, tail, mask, conn) max_rand = np.max(np.hstack((rand_pos_sizes, rand_neg_sizes))) # count cluster p values c_pos_cl += max_rand > pos_sizes c_neg_cl += max_rand > neg_sizes # compute cluster p values p_pos = c_pos_cl / nr_perm p_neg = c_neg_cl / nr_perm # remove clusters that do not pass threshold if tail == 'both': for i, cl in enumerate(np.unique(pos_labels)[1:]): # 0 is not a cluster if p_pos[i] < cl_p_val/2: cl_p_vals[pos_labels == cl] = p_pos[i] else: pos_labels[pos_labels == cl] = 0 for i, cl in enumerate(np.unique(neg_labels)[1:]): # 0 is not a cluster if p_neg[i] < cl_p_val/2: cl_p_vals[neg_labels == cl] = p_neg[i] else: neg_labels[neg_labels == cl] = 0 elif tail == 'right': for i, cl in enumerate(np.unique(pos_labels)[1:]): # 0 is not a cluster if p_pos[i] < cl_p_val: cl_p_vals[pos_labels == cl] = p_pos[i] else: pos_labels[pos_labels == cl] = 0 elif tail == 'left': for i, cl in enumerate(np.unique(neg_labels)[1:]): # 0 is not a cluster if p_neg[i] < cl_p_val: cl_p_vals[neg_labels == cl] = p_neg[i] else: neg_labels[neg_labels == cl] = 0 # ADD FUNCTION TO GET return cl_p_vals def computeClusterSizes(X1, X2, p_val, paired, tail, mask, conn): ''' Helper function for clusterBasedPermutation (see documentation) NOTE!!! Add the moment only supports two tailed tests Add the moment does not support connectivity ''' # STEP 1: determine 'actual' p value # apply the mask to restrict the data X1_mask = X1[:,mask] X2_mask = X2[:,mask] p_vals = np.ones(mask.shape) t_vals = np.zeros(mask.shape) if paired: t_vals[mask], p_vals[mask] = ttest_rel(X1_mask, X2_mask) else: t_vals[mask], p_vals[mask] = ttest_ind(X1_mask, X2_mask) # initialize clusters and use mask to restrict relevant info sign_cl = np.mean(X1,0) - np.mean(X2,0) sign_cl[~mask] = 0 p_vals[~mask] = 1 # STEP 2: apply threshold and determine positive and negative clusters cl_mask = p_vals < p_val pos_cl = np.zeros(cl_mask.shape) neg_cl = np.zeros(cl_mask.shape) pos_cl[sign_cl > 0] = cl_mask[sign_cl > 0] neg_cl[sign_cl < 0] = cl_mask[sign_cl < 0] # STEP 3: label clusters if conn == None: nr_p, pos_labels = cv2.connectedComponents(np.uint8(pos_cl)) nr_n, neg_labels = cv2.connectedComponents(np.uint8(neg_cl)) pos_labels = np.squeeze(pos_labels) # hack to control for onedimensional data (CHECK whether correct) neg_labels = np.squeeze(neg_labels) else: print('Function does not yet support connectivity') # STEP 4: compute the sum of t stats in each cluster (pos and neg) pos_sizes, neg_sizes = np.zeros(nr_p - 1), np.zeros(nr_n - 1) for i, label in enumerate(np.unique(pos_labels)[1:]): pos_sizes[i] = np.sum(t_vals[pos_labels == label]) for i, label in enumerate(np.unique(neg_labels)[1:]): neg_sizes[i] = abs(np.sum(t_vals[neg_labels == label])) if sum(pos_sizes) == 0: pos_sizes = 0 if sum(neg_sizes) == 0: neg_sizes = 0 return pos_sizes, neg_sizes, pos_labels, neg_labels, p_vals def clusterMask(X1, X2, p_val, paired = True): ''' add docstring ''' # indicate significant clusters of individual timecourses sig_cl = clusterBasedPermutation(X1, X2, p_val = p_val, paired = paired) cluster_mask = ~np.array(sig_cl, dtype = bool) return cluster_mask def permTTest(X_real, X_perm, p_thresh = 0.05): ''' permTTest calculates p-values for the one-sample t-stat for each sample point across frequencies using a surrogate distribution generated with permuted data. The p-value is calculated by comparing the t distribution of the real and the permuted slope data across sample points. The t-stats for both distribution is calculated with t = (m - 0)/SEm , where m is the sample mean slope and SEm is the standard error of the mean slope (i.e. stddev/sqrt(n)). The p value is then derived by dividing the number of instances where the surrogate T value across permutations is larger then the real T value by the number of permutations. Arguments - - - - - X_real(array): subject X dim1 X dim2 (optional), where dim1 and dim2 can be any type of dimension (time, frequency, electrode, etc). Values in array represent some dependent measure (e.g classification accuracy or power) X_perm(array): subject X nr_permutation X dim1 X dim2 (optional) p_thresh (float): threshold for significance. All p values below this value are considered to be significant Returns - - - - p_val (array): array with p_values across frequencies and sample points sig (array): array with significance indices (i.e. 0 or 1) across frequencies and sample points ''' # FUNCTION DOES NOT YET SUPPORT ONE DIMENSIONAL DATA # preallocate arrays nr_perm = X_perm.shape [1] nr_obs = X_real.shape[0] p_val = np.zeros(X_real.shape[1:]) sig = np.zeros(X_real.shape[1:]) # will be filled with 0s (non-significant) and 1s (significant) # calculate the real and the surrogate one-sample t-stats r_M = np.mean(X_real, axis = 0); p_M = np.mean(X_perm, axis = 0) r_SE = np.std(X_real, axis = 0)/sqrt(nr_obs); p_SE = np.std(X_perm, axis = 0)/sqrt(nr_obs) r_T = r_M/r_SE; p_T = p_M/p_SE # calculate p-values for f in range(X_real.shape[1]): for s in range(X_real.shape[2]): surr_T = p_T[f,s,:] p_val[f,s] = len(surr_T[surr_T>r_T[f,s]])/float(nr_perm) if p_val[f,s] < p_thresh: sig[f,s] = 1 return p_val, sig def FDR(p_vals, q = 0.05, method = 'pdep', adjust_p = False, report = True): ''' Functions controls the false discovery rate of a family of hypothesis tests. FDR is the expected proportion of rejected hypotheses that are mistakingly rejected (i.e., the null hypothesis is actually true for those tests). FDR is less conservative/more powerfull method for correcting for multiple comparisons than procedures like Bonferroni correction that provide strong control of the familiy-wise error rate (i.e. the probability that one or more null hypotheses are mistakingly rejected) Arguments - - - - - p_vals (array): an array (one or multi-demensional) containing the p_values of each individual test in a family f tests q (float): the desired false discovery rate method (str): If 'pdep' the original Bejnamini & Hochberg (1995) FDR procedure is used, which is guaranteed to be accurate if the individual tests are independent or positively dependent (e.g., Gaussian variables that are positively correlated or independent). If 'dep,' the FDR procedure described in Benjamini & Yekutieli (2001) that is guaranteed to be accurate for any test dependency structure (e.g.,Gaussian variables with any covariance matrix) is used. 'dep' is always appropriate to use but is less powerful than 'pdep.' adjust_p (bool): If True, adjusted p-values are computed (can be computationally intensive) report (bool): If True, a brief summary of FDR results is printed Returns - - - - h (array): a boolean matrix of the same size as the input p_vals, specifying whether the test that produced the corresponding p-value is significant crit_p (float): All uncorrected p-values less than or equal to crit_p are significant. If no p-values are significant, crit_p = 0 adj_ci_cvrg (float): he FCR-adjusted BH- or BY-selected confidence interval coverage. adj_p (array): All adjusted p-values less than or equal to q are significant. Note, adjusted p-values can be greater than 1 ''' orig = p_vals.shape # check whether p_vals contains valid input (i.e. between 0 and 1) if np.sum(p_vals > 1) or np.sum(p_vals < 0): print ('Input contains invalid p values') # sort p_values if p_vals.ndim > 1: p_vect = np.squeeze(np.reshape(p_vals,(1,-1))) else: p_vect = p_vals sort = np.argsort(p_vect) # for sorting rev_sort = np.argsort(sort) # to reverse sorting p_sorted = p_vect[sort] nr_tests = p_sorted.size tests = np.arange(1.0,nr_tests + 1) if method == 'pdep': # BH procedure for independence or positive independence if report: print('FDR/FCR procedure used is guaranteed valid for independent or positively dependent tests') thresh = tests * (q/nr_tests) wtd_p = nr_tests * p_sorted / tests elif method == 'dep': # BH procedure for any dependency structure if report: print('FDR/FCR procedure used is guaranteed valid for independent or dependent tests') denom = nr_tests * sum(1/tests) thresh = tests * (q/denom) wtd_p = denom * p_sorted / tests # Note this method can produce adjusted p values > 1 (Compute adjusted p values) # Chec whether p values need to be adjusted if adjust_p: adj_p = np.empty(nr_tests) * np.nan wtd_p_sortidx = np.argsort(wtd_p) wtd_p_sorted = wtd_p[wtd_p_sortidx] next_fill = 0 for i in range(nr_tests): if wtd_p_sortidx[i] >= next_fill: adj_p[next_fill:wtd_p_sortidx[i]+1] = wtd_p_sorted[i] next_fill = wtd_p_sortidx[i] + 1 if next_fill > nr_tests: break adj_p = np.reshape(adj_p[rev_sort], (orig)) else: adj_p = np.nan rej = np.where(p_sorted <= thresh)[0] if rej.size == 0: crit_p = 0 h = np.array(p_vals * 0, dtype = bool) adj_ci_cvrg = np.nan else: max_idx = rej[-1] # find greatest significant pvalue crit_p = p_sorted[max_idx] h = p_vals <= crit_p adj_ci_cvrg = 1 - thresh[max_idx] if report: nr_sig = np.sum(p_sorted <= crit_p) if nr_sig == 1: print('Out of {} tests, {} is significant using a false discovery rate of {}\n'.format(nr_tests,nr_sig,q)) else: print('Out of {} tests, {} are significant using a false discovery rate of {}\n'.format(nr_tests,nr_sig,q)) return h, crit_p, adj_ci_cvrg, adj_p def threshArray(X, chance, method = 'ttest', paired = True, p_value = 0.05): ''' Two step thresholding of a two dimensional data array. Step 1: use group level testing for each individual data point Step 2: apply clusterbased permutation on the thresholded data from step 1 Arguments - - - - - X (array): subject X dim1 X dim2, where dim1 and dim2 can be any type of dimension (time, frequency, electrode, etc). Values in array represent some dependent measure (e.g classification accuracy or power) chance (int | float): chance value. All non-significant values will be reset to this value method (str): statistical test used in first step of thresholding paired (bool): specifies whether ttest is a paired sampled test or not p_value (float) | p_value used for thresholding Returns - - - - X (array): thresholded data ''' X_ = np.copy(X) # make sure original data remains unchanged p_vals = signedRankArray(X_, chance, method) X_[:,p_vals > p_value] = chance p_vals = clusterBasedPermutation(X_,chance, paired = paired) X_ = X_.mean(axis = 0) X_[p_vals > p_value] = chance return X_ def signedRankArray(X, Y, method = 'ttest_rel'): ''' Arguments - - - - - X1 (array): subject X dim1 X dim2, where dim1 and dim2 can be any type of dimension (time, frequency, electrode, etc). Values in array represent some dependent measure (e.g classification accuracy or power) Y (array | float): either a datamatrix with same dimensions as X1, or a single value against which X1 will be tested method (str): type of test to calculate p values ''' # check whether X2 is a chance variable or a data array if isinstance(Y, (float, int)): Y = np.tile(Y, X.shape) p_vals = np.ones(X[0].shape) for i in range(p_vals.shape[0]): for j in range(p_vals.shape[1]): if method == 'wilcoxon': _, p_vals[i,j] = wilcoxon(X[:,i,j], Y[:,i,j]) elif method == 'ttest_rel': _, p_vals[i,j] = ttest_rel(X[:,i,j], Y[:,i,j]) elif method == 'ttest_1samp': _, p_vals[i,j] = ttest_1samp(X[:,i,j], Y[0,i,j]) return p_vals def bootstrap(X, b_iter = 1000): ''' bootstrap uses a bootstrap procedure to calculate standard error of data in X. Arguments - - - - - test Returns - - - - ''' nr_obs = X.shape[0] bootstrapped = np.zeros((b_iter,X.shape[1])) for b in range(b_iter): idx = np.random.choice(nr_obs,nr_obs,replace = True) # sample nr subjects observations from the slopes sample (with replacement) bootstrapped[b,:] = np.mean(X[idx,:],axis = 0) error = np.std(bootstrapped, axis = 0) mean = X.mean(axis = 0) return error, mean def jacklatency(x1, x2, thresh_1, thresh_2, times, info = False): ''' Helper function of jackknife. Calculates the latency difference between threshold crosses using linear interpolation Arguments - - - - - x1 (array): subject X time. Values in array represent some dependent measure. (e.g. ERP voltages) x2 (array): array with same dimensions as X1 thresh_1 (float): criterion value thresh_2 (float): criterion value times (array): timing of samples in X1 and X2 times (str): calculate onset or offset latency differences Returns - - - - D (float): latency difference ''' # get latency exceeding thresh idx_1 = np.where(x1 >= thresh_1)[0][0] lat_1 = times[idx_1 - 1] + (times[idx_1] - times[idx_1 - 1]) * \ (thresh_1 - x1[idx_1 - 1])/(x1[idx_1] - x1[idx_1-1]) idx_2 = np.where(x2 >= thresh_2)[0][0] lat_2 = times[idx_2 - 1] + (times[idx_2] - times[idx_2 - 1]) * \ (thresh_2 - x2[idx_2 - 1])/(x2[idx_2] - x2[idx_2-1]) D = lat_2 - lat_1 if info: print('Estimated onset latency X1 = {0:.2f} and X2: {1:.2f}'.format(lat_1, lat_2)) return D def jackknife(X1, X2, times, peak_window, percent_amp = 50, timing = 'onset'): ''' Implements <NAME>., <NAME>., & <NAME>. (1998). Jackknife-based method for measuring LRP onset latency differences. Psychophysiology, 35(1), 99-115. Compares onset latencies between two grand-average waveforms. For each waveform a criterion is determined based on a set percentage of the grand average peak. The latency at which this criterion is first reached is then determined using linear interpolation. Next the jackknife estimate of the standard error of the difference is used, which is then used to calculate the t value corresponding to the null hypothesis of no differences in onset latencies Arguments - - - - - X1 (array): subject X time. Values in array represent some dependent measure. (e.g. ERP voltages) X2 (array): array with same dimensions as X1 times (array): timing of samples in X1 and X2 peak_window (tuple | list): time window that contains peak of interest percent_amp (int): used to calculate criterion value timing (str): calculate onset or offset latency differnces Returns - - - - onset (float): onset differnce between grand waveform of X1 and X2 t_value (float): corresponding to the null hypothesis of no differences in onset latencies ''' # set number of observations nr_sj = X1.shape[0] # flip arrays if necessary if timing == 'offset': X1 = np.fliplr(X1) X2 = np.fliplr(X2) times = np.flipud(times) # get time window of interest s,e = np.sort([np.argmin(abs(times - t)) for t in peak_window]) t = times[s:e] # slice data containing the peak average x1 = np.mean(X1[:,s:e], axis = 0) x2 = np.mean(X2[:,s:e], axis = 0) # get the criterion based on peak amplitude percentage c_1 = max(x1) * percent_amp/ 100.0 c_2 = max(x2) * percent_amp/ 100.0 onset = jacklatency(x1, x2, c_1, c_2, t, info = True) # repeat previous steps but exclude all data points once D = [] idx = np.arange(nr_sj) for i in range(nr_sj): x1 = np.mean(abs(X1[np.where(idx != i)[0],s:e]), axis = 0) x2 = np.mean(abs(X2[:,s:e]), axis = 0) c_1 = max(x1) * percent_amp/ 100.0 c_2 = max(x2) * percent_amp/ 100.0 D.append(jacklatency(x1, x2, c_1, c_2, t) ) # compute the jackknife estimate of the standard error of the differnce Sd = np.sqrt((nr_sj - 1.0)/ nr_sj * np.sum([(d - np.mean(D))**2 for d in np.array(D)])) t_value = onset/ Sd return onset, t_value
[ "numpy.uint8", "numpy.random.rand", "numpy.hstack", "math.sqrt", "numpy.argsort", "numpy.array", "scipy.stats.ttest_rel", "scipy.stats.ttest_ind", "numpy.arange", "numpy.mean", "numpy.reshape", "numpy.where", "scipy.stats.wilcoxon", "numpy.empty", "numpy.vstack", "numpy.random.permutat...
[((626, 636), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (633, 636), True, 'import numpy as np\n'), ((3228, 3249), 'numpy.ones', 'np.ones', (['sig_cl.shape'], {}), '(sig_cl.shape)\n', (3235, 3249), True, 'import numpy as np\n'), ((3483, 3501), 'numpy.zeros', 'np.zeros', (['X1.shape'], {}), '(X1.shape)\n', (3491, 3501), True, 'import numpy as np\n'), ((3513, 3531), 'numpy.zeros', 'np.zeros', (['X1.shape'], {}), '(X1.shape)\n', (3521, 3531), True, 'import numpy as np\n'), ((5882, 5901), 'numpy.ones', 'np.ones', (['mask.shape'], {}), '(mask.shape)\n', (5889, 5901), True, 'import numpy as np\n'), ((5912, 5932), 'numpy.zeros', 'np.zeros', (['mask.shape'], {}), '(mask.shape)\n', (5920, 5932), True, 'import numpy as np\n'), ((6326, 6349), 'numpy.zeros', 'np.zeros', (['cl_mask.shape'], {}), '(cl_mask.shape)\n', (6334, 6349), True, 'import numpy as np\n'), ((6360, 6383), 'numpy.zeros', 'np.zeros', (['cl_mask.shape'], {}), '(cl_mask.shape)\n', (6368, 6383), True, 'import numpy as np\n'), ((9114, 9140), 'numpy.zeros', 'np.zeros', (['X_real.shape[1:]'], {}), '(X_real.shape[1:])\n', (9122, 9140), True, 'import numpy as np\n'), ((9148, 9174), 'numpy.zeros', 'np.zeros', (['X_real.shape[1:]'], {}), '(X_real.shape[1:])\n', (9156, 9174), True, 'import numpy as np\n'), ((9307, 9330), 'numpy.mean', 'np.mean', (['X_real'], {'axis': '(0)'}), '(X_real, axis=0)\n', (9314, 9330), True, 'import numpy as np\n'), ((9340, 9363), 'numpy.mean', 'np.mean', (['X_perm'], {'axis': '(0)'}), '(X_perm, axis=0)\n', (9347, 9363), True, 'import numpy as np\n'), ((12087, 12105), 'numpy.argsort', 'np.argsort', (['p_vect'], {}), '(p_vect)\n', (12097, 12105), True, 'import numpy as np\n'), ((12132, 12148), 'numpy.argsort', 'np.argsort', (['sort'], {}), '(sort)\n', (12142, 12148), True, 'import numpy as np\n'), ((12231, 12259), 'numpy.arange', 'np.arange', (['(1.0)', '(nr_tests + 1)'], {}), '(1.0, nr_tests + 1)\n', (12240, 12259), True, 'import numpy as np\n'), ((14830, 14840), 'numpy.copy', 'np.copy', (['X'], {}), '(X)\n', (14837, 14840), True, 'import numpy as np\n'), ((15696, 15715), 'numpy.ones', 'np.ones', (['X[0].shape'], {}), '(X[0].shape)\n', (15703, 15715), True, 'import numpy as np\n'), ((16268, 16298), 'numpy.zeros', 'np.zeros', (['(b_iter, X.shape[1])'], {}), '((b_iter, X.shape[1]))\n', (16276, 16298), True, 'import numpy as np\n'), ((16518, 16546), 'numpy.std', 'np.std', (['bootstrapped'], {'axis': '(0)'}), '(bootstrapped, axis=0)\n', (16524, 16546), True, 'import numpy as np\n'), ((19313, 19340), 'numpy.mean', 'np.mean', (['X1[:, s:e]'], {'axis': '(0)'}), '(X1[:, s:e], axis=0)\n', (19320, 19340), True, 'import numpy as np\n'), ((19348, 19375), 'numpy.mean', 'np.mean', (['X2[:, s:e]'], {'axis': '(0)'}), '(X2[:, s:e], axis=0)\n', (19355, 19375), True, 'import numpy as np\n'), ((19640, 19656), 'numpy.arange', 'np.arange', (['nr_sj'], {}), '(nr_sj)\n', (19649, 19656), True, 'import numpy as np\n'), ((419, 440), 'numpy.tile', 'np.tile', (['X2', 'X1.shape'], {}), '(X2, X1.shape)\n', (426, 440), True, 'import numpy as np\n'), ((960, 992), 'numpy.array', 'np.array', (['(T_p > T_0)'], {'dtype': 'float'}), '(T_p > T_0, dtype=float)\n', (968, 992), True, 'import numpy as np\n'), ((3035, 3056), 'numpy.tile', 'np.tile', (['X2', 'X1.shape'], {}), '(X2, X1.shape)\n', (3042, 3056), True, 'import numpy as np\n'), ((5977, 6004), 'scipy.stats.ttest_rel', 'ttest_rel', (['X1_mask', 'X2_mask'], {}), '(X1_mask, X2_mask)\n', (5986, 6004), False, 'from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp\n'), ((6043, 6070), 'scipy.stats.ttest_ind', 'ttest_ind', (['X1_mask', 'X2_mask'], {}), '(X1_mask, X2_mask)\n', (6052, 6070), False, 'from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp\n'), ((6147, 6161), 'numpy.mean', 'np.mean', (['X1', '(0)'], {}), '(X1, 0)\n', (6154, 6161), True, 'import numpy as np\n'), ((6163, 6177), 'numpy.mean', 'np.mean', (['X2', '(0)'], {}), '(X2, 0)\n', (6170, 6177), True, 'import numpy as np\n'), ((6658, 6680), 'numpy.squeeze', 'np.squeeze', (['pos_labels'], {}), '(pos_labels)\n', (6668, 6680), True, 'import numpy as np\n'), ((6762, 6784), 'numpy.squeeze', 'np.squeeze', (['neg_labels'], {}), '(neg_labels)\n', (6772, 6784), True, 'import numpy as np\n'), ((6940, 6958), 'numpy.zeros', 'np.zeros', (['(nr_p - 1)'], {}), '(nr_p - 1)\n', (6948, 6958), True, 'import numpy as np\n'), ((6960, 6978), 'numpy.zeros', 'np.zeros', (['(nr_n - 1)'], {}), '(nr_n - 1)\n', (6968, 6978), True, 'import numpy as np\n'), ((7051, 7086), 'numpy.sum', 'np.sum', (['t_vals[pos_labels == label]'], {}), '(t_vals[pos_labels == label])\n', (7057, 7086), True, 'import numpy as np\n'), ((7591, 7619), 'numpy.array', 'np.array', (['sig_cl'], {'dtype': 'bool'}), '(sig_cl, dtype=bool)\n', (7599, 7619), True, 'import numpy as np\n'), ((9374, 9396), 'numpy.std', 'np.std', (['X_real'], {'axis': '(0)'}), '(X_real, axis=0)\n', (9380, 9396), True, 'import numpy as np\n'), ((9399, 9411), 'math.sqrt', 'sqrt', (['nr_obs'], {}), '(nr_obs)\n', (9403, 9411), False, 'from math import sqrt\n'), ((9420, 9442), 'numpy.std', 'np.std', (['X_perm'], {'axis': '(0)'}), '(X_perm, axis=0)\n', (9426, 9442), True, 'import numpy as np\n'), ((9445, 9457), 'math.sqrt', 'sqrt', (['nr_obs'], {}), '(nr_obs)\n', (9449, 9457), False, 'from math import sqrt\n'), ((11876, 11894), 'numpy.sum', 'np.sum', (['(p_vals > 1)'], {}), '(p_vals > 1)\n', (11882, 11894), True, 'import numpy as np\n'), ((11898, 11916), 'numpy.sum', 'np.sum', (['(p_vals < 0)'], {}), '(p_vals < 0)\n', (11904, 11916), True, 'import numpy as np\n'), ((12993, 13010), 'numpy.argsort', 'np.argsort', (['wtd_p'], {}), '(wtd_p)\n', (13003, 13010), True, 'import numpy as np\n'), ((13276, 13309), 'numpy.reshape', 'np.reshape', (['adj_p[rev_sort]', 'orig'], {}), '(adj_p[rev_sort], orig)\n', (13286, 13309), True, 'import numpy as np\n'), ((13346, 13374), 'numpy.where', 'np.where', (['(p_sorted <= thresh)'], {}), '(p_sorted <= thresh)\n', (13354, 13374), True, 'import numpy as np\n'), ((13419, 13451), 'numpy.array', 'np.array', (['(p_vals * 0)'], {'dtype': 'bool'}), '(p_vals * 0, dtype=bool)\n', (13427, 13451), True, 'import numpy as np\n'), ((13651, 13677), 'numpy.sum', 'np.sum', (['(p_sorted <= crit_p)'], {}), '(p_sorted <= crit_p)\n', (13657, 13677), True, 'import numpy as np\n'), ((15665, 15684), 'numpy.tile', 'np.tile', (['Y', 'X.shape'], {}), '(Y, X.shape)\n', (15672, 15684), True, 'import numpy as np\n'), ((16332, 16378), 'numpy.random.choice', 'np.random.choice', (['nr_obs', 'nr_obs'], {'replace': '(True)'}), '(nr_obs, nr_obs, replace=True)\n', (16348, 16378), True, 'import numpy as np\n'), ((16481, 16507), 'numpy.mean', 'np.mean', (['X[idx, :]'], {'axis': '(0)'}), '(X[idx, :], axis=0)\n', (16488, 16507), True, 'import numpy as np\n'), ((19087, 19100), 'numpy.fliplr', 'np.fliplr', (['X1'], {}), '(X1)\n', (19096, 19100), True, 'import numpy as np\n'), ((19108, 19121), 'numpy.fliplr', 'np.fliplr', (['X2'], {}), '(X2)\n', (19117, 19121), True, 'import numpy as np\n'), ((19132, 19148), 'numpy.flipud', 'np.flipud', (['times'], {}), '(times)\n', (19141, 19148), True, 'import numpy as np\n'), ((565, 577), 'math.sqrt', 'sqrt', (['nr_obs'], {}), '(nr_obs)\n', (569, 577), False, 'from math import sqrt\n'), ((654, 671), 'numpy.zeros', 'np.zeros', (['nr_test'], {}), '(nr_test)\n', (662, 671), True, 'import numpy as np\n'), ((754, 788), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'X.shape'}), '(2, size=X.shape)\n', (771, 788), True, 'import numpy as np\n'), ((2568, 2589), 'numpy.ones', 'np.ones', (['X1.shape[1:]'], {}), '(X1.shape[1:])\n', (2575, 2589), True, 'import numpy as np\n'), ((3369, 3390), 'numpy.unique', 'np.unique', (['pos_labels'], {}), '(pos_labels)\n', (3378, 3390), True, 'import numpy as np\n'), ((3421, 3442), 'numpy.unique', 'np.unique', (['neg_labels'], {}), '(neg_labels)\n', (3430, 3442), True, 'import numpy as np\n'), ((3996, 4015), 'numpy.vstack', 'np.vstack', (['(X1, X2)'], {}), '((X1, X2))\n', (4005, 4015), True, 'import numpy as np\n'), ((4336, 4379), 'numpy.hstack', 'np.hstack', (['(rand_pos_sizes, rand_neg_sizes)'], {}), '((rand_pos_sizes, rand_neg_sizes))\n', (4345, 4379), True, 'import numpy as np\n'), ((6562, 6578), 'numpy.uint8', 'np.uint8', (['pos_cl'], {}), '(pos_cl)\n', (6570, 6578), True, 'import numpy as np\n'), ((6625, 6641), 'numpy.uint8', 'np.uint8', (['neg_cl'], {}), '(neg_cl)\n', (6633, 6641), True, 'import numpy as np\n'), ((7006, 7027), 'numpy.unique', 'np.unique', (['pos_labels'], {}), '(pos_labels)\n', (7015, 7027), True, 'import numpy as np\n'), ((7115, 7136), 'numpy.unique', 'np.unique', (['neg_labels'], {}), '(neg_labels)\n', (7124, 7136), True, 'import numpy as np\n'), ((7164, 7199), 'numpy.sum', 'np.sum', (['t_vals[neg_labels == label]'], {}), '(t_vals[neg_labels == label])\n', (7170, 7199), True, 'import numpy as np\n'), ((12024, 12051), 'numpy.reshape', 'np.reshape', (['p_vals', '(1, -1)'], {}), '(p_vals, (1, -1))\n', (12034, 12051), True, 'import numpy as np\n'), ((12946, 12964), 'numpy.empty', 'np.empty', (['nr_tests'], {}), '(nr_tests)\n', (12954, 12964), True, 'import numpy as np\n'), ((17236, 17260), 'numpy.where', 'np.where', (['(x1 >= thresh_1)'], {}), '(x1 >= thresh_1)\n', (17244, 17260), True, 'import numpy as np\n'), ((17399, 17423), 'numpy.where', 'np.where', (['(x2 >= thresh_2)'], {}), '(x2 >= thresh_2)\n', (17407, 17423), True, 'import numpy as np\n'), ((876, 888), 'math.sqrt', 'sqrt', (['nr_obs'], {}), '(nr_obs)\n', (880, 888), False, 'from math import sqrt\n'), ((3729, 3756), 'numpy.random.rand', 'np.random.rand', (['X1.shape[0]'], {}), '(X1.shape[0])\n', (3743, 3756), True, 'import numpy as np\n'), ((4659, 4680), 'numpy.unique', 'np.unique', (['pos_labels'], {}), '(pos_labels)\n', (4668, 4680), True, 'import numpy as np\n'), ((4852, 4873), 'numpy.unique', 'np.unique', (['neg_labels'], {}), '(neg_labels)\n', (4861, 4873), True, 'import numpy as np\n'), ((15835, 15867), 'scipy.stats.wilcoxon', 'wilcoxon', (['X[:, i, j]', 'Y[:, i, j]'], {}), '(X[:, i, j], Y[:, i, j])\n', (15843, 15867), False, 'from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp\n'), ((4033, 4070), 'numpy.random.permutation', 'np.random.permutation', (['all_X.shape[0]'], {}), '(all_X.shape[0])\n', (4054, 4070), True, 'import numpy as np\n'), ((5068, 5089), 'numpy.unique', 'np.unique', (['pos_labels'], {}), '(pos_labels)\n', (5077, 5089), True, 'import numpy as np\n'), ((15917, 15950), 'scipy.stats.ttest_rel', 'ttest_rel', (['X[:, i, j]', 'Y[:, i, j]'], {}), '(X[:, i, j], Y[:, i, j])\n', (15926, 15950), False, 'from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp\n'), ((5281, 5302), 'numpy.unique', 'np.unique', (['neg_labels'], {}), '(neg_labels)\n', (5290, 5302), True, 'import numpy as np\n'), ((16003, 16038), 'scipy.stats.ttest_1samp', 'ttest_1samp', (['X[:, i, j]', 'Y[0, i, j]'], {}), '(X[:, i, j], Y[0, i, j])\n', (16014, 16038), False, 'from scipy.stats import ttest_rel, ttest_ind, wilcoxon, ttest_1samp\n'), ((20055, 20066), 'numpy.array', 'np.array', (['D'], {}), '(D)\n', (20063, 20066), True, 'import numpy as np\n'), ((19703, 19721), 'numpy.where', 'np.where', (['(idx != i)'], {}), '(idx != i)\n', (19711, 19721), True, 'import numpy as np\n'), ((20031, 20041), 'numpy.mean', 'np.mean', (['D'], {}), '(D)\n', (20038, 20041), True, 'import numpy as np\n')]
import numpy as np from scipy.ndimage import filters from bidict import bidict def image_gradient(image, sigma): image = np.asfarray(image) gx = filters.gaussian_filter(image, sigma, order=[0, 1]) gy = filters.gaussian_filter(image, sigma, order=[1, 0]) return gx, gy class CurvePoint(object): __slots__ = ['x', 'y', 'valid'] def __init__(self, x, y, valid): self.x = x self.y = y self.valid = valid def __hash__(self): return hash((self.x, self.y)) def compute_edge_points(partial_gradients, min_magnitude=0): gx, gy = partial_gradients rows, cols = gx.shape edges = [] def mag(y, x): return np.hypot(gx[y, x], gy[y, x]) for y in range(1, rows - 1): for x in range(1, cols - 1): center_mag = mag(y, x) if center_mag < min_magnitude: continue left_mag = mag(y, x - 1) right_mag = mag(y, x + 1) top_mag = mag(y - 1, x) bottom_mag = mag(y + 1, x) theta_x, theta_y = 0, 0 if (left_mag < center_mag >= right_mag) and abs(gx[y, x]) >= abs(gy[y, x]): theta_x = 1 elif (top_mag < center_mag >= bottom_mag) and abs(gx[y, x]) <= abs(gy[y, x]): theta_y = 1 if theta_x != 0 or theta_y != 0: a = mag(y - theta_y, x - theta_x) b = mag(y, x) c = mag(y + theta_y, x + theta_x) lamda = (a - c) / (2 * (a - 2 * b + c)) ex = x + lamda * theta_x ey = y + lamda * theta_y edges.append(CurvePoint(ex, ey, valid=False)) return np.asarray(edges) def chain_edge_points(edges, g): gx, gy = g def neighborhood(p, max_dist): px, py = p.x, p.y for e in edges: ex, ey = e.x, e.y if abs(ex - px) <= max_dist and abs(ey - py) <= max_dist: yield e def gval(p): px, py = int(p.x), int(p.y) return [gx[py, px], gy[py, px]] def envec(e, n): return np.asanyarray([n.x, n.y]) - np.asanyarray([e.x, e.y]) def perp(v): x, y = gval(e) return np.asanyarray([y, -x]) def dist(a, b): a = [a.x, a.y] b = [b.x, b.y] return np.hypot(*(np.subtract(b, a))) links = bidict() for e in edges: nhood = [ n for n in neighborhood(e, 2) if np.dot(gval(e), gval(n)) > 0] nf = [n for n in nhood if np.dot(envec(e, n), perp(gval(e))) > 0] nb = [n for n in nhood if np.dot(envec(e, n), perp(gval(e))) < 0] if nf: f_idx = np.argmin([dist(e, n) for n in nf]) f = nf[f_idx] if f not in links.inv or dist(e,f) < dist(links.inv[f], f): if f in links.inv: del links.inv[f] if e in links: del links[e] links[e] = f if nb: b_idx = np.argmin([dist(e, n) for n in nb]) b = nb[b_idx] if b not in links or dist(b, e) < dist(b, links[b]): if b in links: del links[b] if e in links.inv: del links.inv[e] links[b] = e return links def thresholds_with_hysteresis(edges, links, grads, high_threshold, low_threshold): gx, gy = grads def mag(p): x, y = int(p.x), int(p.y) return np.hypot(gx[y, x], gy[y, x]) chains = [] for e in edges: if not e.valid and mag(e) >= high_threshold: forward = [] backward = [] e.valid = True f = e while f in links and not links[f].valid and mag(links[f]) >= low_threshold: n = links[f] n.valid = True f = n forward.append(f) b = e while b in links.inv and not links.inv[b].valid and mag(links.inv[f]) >= low_threshold: n = links.inv[b] n.valid = True b = n backward.insert(0, b) chain = backward + [e] + forward chains.append(np.asarray([(c.x, c.y) for c in chain])) return chains if __name__ == '__main__': import numpy as np from scipy.ndimage import filters import cv2 pad = 20 circle = cv2.imread("./kreis.png", 0) I = np.zeros((circle.shape[0] + 2 * pad, circle.shape[1] + 2 * pad), dtype=np.uint8) + 255 I[pad:circle.shape[0] + pad, pad:circle.shape[1] + pad] = circle I = I.astype(np.float32) I[20, 20] = 0 I[10:13, 10:40] = 0 grads = image_gradient(I, 2.0) edges = compute_edge_points(grads) links = chain_edge_points(edges, grads) chains = thresholds_with_hysteresis(edges, links, grads, 1, 0.1)
[ "scipy.ndimage.filters.gaussian_filter", "numpy.asarray", "numpy.subtract", "numpy.asanyarray", "numpy.asfarray", "numpy.zeros", "numpy.hypot", "cv2.imread", "bidict.bidict" ]
[((127, 145), 'numpy.asfarray', 'np.asfarray', (['image'], {}), '(image)\n', (138, 145), True, 'import numpy as np\n'), ((155, 206), 'scipy.ndimage.filters.gaussian_filter', 'filters.gaussian_filter', (['image', 'sigma'], {'order': '[0, 1]'}), '(image, sigma, order=[0, 1])\n', (178, 206), False, 'from scipy.ndimage import filters\n'), ((216, 267), 'scipy.ndimage.filters.gaussian_filter', 'filters.gaussian_filter', (['image', 'sigma'], {'order': '[1, 0]'}), '(image, sigma, order=[1, 0])\n', (239, 267), False, 'from scipy.ndimage import filters\n'), ((1698, 1715), 'numpy.asarray', 'np.asarray', (['edges'], {}), '(edges)\n', (1708, 1715), True, 'import numpy as np\n'), ((2366, 2374), 'bidict.bidict', 'bidict', ([], {}), '()\n', (2372, 2374), False, 'from bidict import bidict\n'), ((4318, 4346), 'cv2.imread', 'cv2.imread', (['"""./kreis.png"""', '(0)'], {}), "('./kreis.png', 0)\n", (4328, 4346), False, 'import cv2\n'), ((686, 714), 'numpy.hypot', 'np.hypot', (['gx[y, x]', 'gy[y, x]'], {}), '(gx[y, x], gy[y, x])\n', (694, 714), True, 'import numpy as np\n'), ((2217, 2239), 'numpy.asanyarray', 'np.asanyarray', (['[y, -x]'], {}), '([y, -x])\n', (2230, 2239), True, 'import numpy as np\n'), ((3395, 3423), 'numpy.hypot', 'np.hypot', (['gx[y, x]', 'gy[y, x]'], {}), '(gx[y, x], gy[y, x])\n', (3403, 3423), True, 'import numpy as np\n'), ((4355, 4440), 'numpy.zeros', 'np.zeros', (['(circle.shape[0] + 2 * pad, circle.shape[1] + 2 * pad)'], {'dtype': 'np.uint8'}), '((circle.shape[0] + 2 * pad, circle.shape[1] + 2 * pad), dtype=np.uint8\n )\n', (4363, 4440), True, 'import numpy as np\n'), ((2107, 2132), 'numpy.asanyarray', 'np.asanyarray', (['[n.x, n.y]'], {}), '([n.x, n.y])\n', (2120, 2132), True, 'import numpy as np\n'), ((2135, 2160), 'numpy.asanyarray', 'np.asanyarray', (['[e.x, e.y]'], {}), '([e.x, e.y])\n', (2148, 2160), True, 'import numpy as np\n'), ((2333, 2350), 'numpy.subtract', 'np.subtract', (['b', 'a'], {}), '(b, a)\n', (2344, 2350), True, 'import numpy as np\n'), ((4127, 4166), 'numpy.asarray', 'np.asarray', (['[(c.x, c.y) for c in chain]'], {}), '([(c.x, c.y) for c in chain])\n', (4137, 4166), True, 'import numpy as np\n')]
""" BiotSavart_CUDA module. """ # ISC License # # Copyright (c) 2020–2021, <NAME>, <NAME>. <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import math import numpy as np from numba import cuda from PyQt5.QtCore import QThread from magneticalc.Constants import Constants from magneticalc.Debug import Debug from magneticalc.Field_Types import A_FIELD, B_FIELD from magneticalc.Theme import Theme class BiotSavart_CUDA: """ Implements the Biot-Savart law for calculating the magnetic flux density (B-field) and vector potential (A-field). """ def __init__( self, field_type: int, distance_limit: float, length_scale: float, dc: float, current_elements, sampling_volume_points, sampling_volume_permeabilities, progress_callback ): """ Initializes the class attributes. @param field_type: Field type @param distance_limit: Distance limit (mitigating divisions by zero) @param length_scale: Length scale (m) @param dc: Wire current (A) @param current_elements: Ordered list of current elements (pairs: [element center, element direction]) @param sampling_volume_points: Ordered list of sampling volume points @param sampling_volume_permeabilities: Ordered list of sampling volume's relative permeabilities µ_r @param progress_callback: Progress callback """ self.field_type = field_type self._distance_limit = distance_limit self._length_scale = length_scale self._dc = dc self._current_elements = current_elements self._sampling_volume_points = sampling_volume_points self._sampling_volume_permeabilities = sampling_volume_permeabilities self._progress_callback = progress_callback @staticmethod def is_available(): """ Indicates the availability of this backend. @return: True if this backend is available, False otherwise """ return cuda.is_available() @staticmethod @cuda.jit def worker( field_type, distance_limit, length_scale, element_centers, element_directions, sampling_volume_points, sampling_volume_permeabilities, field_vectors, total_calculations, total_skipped_calculations ): """ Applies the Biot-Savart law for calculating the magnetic flux density (B-field) or vector potential (A-field) for all sampling volume points. @param field_type: Field type @param distance_limit: Distance limit (mitigating divisions by zero) @param length_scale: Length scale (m) @param element_centers: Ordered list of current elements centers @param element_directions: Ordered list of current elements directions @param sampling_volume_points: Sampling volume points @param sampling_volume_permeabilities: Ordered list of sampling volume's relative permeabilities µ_r @param field_vectors: Field vectors (output array) @param total_calculations: Total number of calculations (output array) @param total_skipped_calculations: Total number of skipped calculations (output array) """ # noinspection PyUnresolvedReferences sampling_volume_index = cuda.blockIdx.x * cuda.blockDim.x + cuda.threadIdx.x if sampling_volume_index >= sampling_volume_points.shape[0]: return total_calculations[sampling_volume_index] = 0 total_skipped_calculations[sampling_volume_index] = 0 vector_x = 0 vector_y = 0 vector_z = 0 for current_element_index in range(element_centers.shape[0]): vector_distance_x = (sampling_volume_points[sampling_volume_index][0] - element_centers[current_element_index][0]) * length_scale vector_distance_y = (sampling_volume_points[sampling_volume_index][1] - element_centers[current_element_index][1]) * length_scale vector_distance_z = (sampling_volume_points[sampling_volume_index][2] - element_centers[current_element_index][2]) * length_scale # Calculate distance (mitigating divisions by zero) scalar_distance = math.sqrt(vector_distance_x ** 2 + vector_distance_y ** 2 + vector_distance_z ** 2) if scalar_distance < distance_limit: scalar_distance = distance_limit total_skipped_calculations[sampling_volume_index] += 1 total_calculations[sampling_volume_index] += 1 if field_type == A_FIELD: # Calculate A-field (vector potential) vector_x += element_directions[current_element_index][0] * length_scale / scalar_distance vector_y += element_directions[current_element_index][1] * length_scale / scalar_distance vector_z += element_directions[current_element_index][2] * length_scale / scalar_distance elif field_type == B_FIELD: # Calculate B-field (flux density) a_1 = element_directions[current_element_index][0] * length_scale a_2 = element_directions[current_element_index][1] * length_scale a_3 = element_directions[current_element_index][2] * length_scale vector_x += (a_2 * vector_distance_z - a_3 * vector_distance_y) / (scalar_distance ** 3) vector_y += (a_3 * vector_distance_x - a_1 * vector_distance_z) / (scalar_distance ** 3) vector_z += (a_1 * vector_distance_y - a_2 * vector_distance_x) / (scalar_distance ** 3) field_vectors[sampling_volume_index, 0] = vector_x * sampling_volume_permeabilities[sampling_volume_index] field_vectors[sampling_volume_index, 1] = vector_y * sampling_volume_permeabilities[sampling_volume_index] field_vectors[sampling_volume_index, 2] = vector_z * sampling_volume_permeabilities[sampling_volume_index] def get_result(self): """ Calculates the field at every point of the sampling volume. @return: (Total # of calculations, total # of skipped calculations, field) if successful, None if interrupted """ Debug(self, ".get_result()", color=Theme.PrimaryColor) element_centers = [element[0] for element in self._current_elements] element_directions = [element[1] for element in self._current_elements] element_centers_global = cuda.to_device(element_centers) element_directions_global = cuda.to_device(element_directions) total_calculations = 0 total_skipped_calculations = 0 field_vectors = np.zeros(shape=(0, 3)) # Split the calculation into chunks for progress update and interruption handling chunk_size_max = 1024 * 16 chunk_start = 0 remaining = len(self._sampling_volume_points) while remaining > 0: if remaining >= chunk_size_max: chunk_size = chunk_size_max else: chunk_size = remaining sampling_volume_points_global = cuda.to_device( self._sampling_volume_points[chunk_start:chunk_start + chunk_size] ) sampling_volume_permeabilities_global = cuda.to_device( self._sampling_volume_permeabilities[chunk_start:chunk_start + chunk_size] ) # Signal progress update, handle interrupt self._progress_callback(100 * chunk_start / len(self._sampling_volume_points)) if QThread.currentThread().isInterruptionRequested(): Debug(self, ".get_result(): Interruption requested, exiting now", color=Theme.PrimaryColor) return None remaining -= chunk_size chunk_start += chunk_size total_calculations_global = cuda.to_device(np.zeros(chunk_size)) total_skipped_calculations_global = cuda.to_device(np.zeros(chunk_size)) field_vectors_global = cuda.device_array((chunk_size, 3)) TPB = 1024 # Maximum threads per block BPG = 65536 # Maximum blocks per grid BiotSavart_CUDA.worker[BPG, TPB]( self.field_type, self._distance_limit, self._length_scale, element_centers_global, element_directions_global, sampling_volume_points_global, sampling_volume_permeabilities_global, field_vectors_global, total_calculations_global, total_skipped_calculations_global ) total_calculations_local = total_calculations_global.copy_to_host() total_skipped_calculations_local = total_skipped_calculations_global.copy_to_host() field_vectors_local = field_vectors_global.copy_to_host() if self.field_type == A_FIELD or self.field_type == B_FIELD: # Field is A-field or B-field field_vectors_local = field_vectors_local * self._dc * Constants.mu_0 / 4 / np.pi total_calculations += int(sum(total_calculations_local)) total_skipped_calculations += int(sum(total_skipped_calculations_local)) field_vectors = np.append(field_vectors, field_vectors_local, axis=0) self._progress_callback(100) return total_calculations, total_skipped_calculations, np.array(field_vectors)
[ "numba.cuda.device_array", "math.sqrt", "numba.cuda.is_available", "numpy.append", "numpy.array", "numpy.zeros", "numba.cuda.to_device", "PyQt5.QtCore.QThread.currentThread", "magneticalc.Debug.Debug" ]
[((2761, 2780), 'numba.cuda.is_available', 'cuda.is_available', ([], {}), '()\n', (2778, 2780), False, 'from numba import cuda\n'), ((7116, 7170), 'magneticalc.Debug.Debug', 'Debug', (['self', '""".get_result()"""'], {'color': 'Theme.PrimaryColor'}), "(self, '.get_result()', color=Theme.PrimaryColor)\n", (7121, 7170), False, 'from magneticalc.Debug import Debug\n'), ((7363, 7394), 'numba.cuda.to_device', 'cuda.to_device', (['element_centers'], {}), '(element_centers)\n', (7377, 7394), False, 'from numba import cuda\n'), ((7431, 7465), 'numba.cuda.to_device', 'cuda.to_device', (['element_directions'], {}), '(element_directions)\n', (7445, 7465), False, 'from numba import cuda\n'), ((7561, 7583), 'numpy.zeros', 'np.zeros', ([], {'shape': '(0, 3)'}), '(shape=(0, 3))\n', (7569, 7583), True, 'import numpy as np\n'), ((5147, 5235), 'math.sqrt', 'math.sqrt', (['(vector_distance_x ** 2 + vector_distance_y ** 2 + vector_distance_z ** 2)'], {}), '(vector_distance_x ** 2 + vector_distance_y ** 2 + \n vector_distance_z ** 2)\n', (5156, 5235), False, 'import math\n'), ((8009, 8095), 'numba.cuda.to_device', 'cuda.to_device', (['self._sampling_volume_points[chunk_start:chunk_start + chunk_size]'], {}), '(self._sampling_volume_points[chunk_start:chunk_start +\n chunk_size])\n', (8023, 8095), False, 'from numba import cuda\n'), ((8174, 8268), 'numba.cuda.to_device', 'cuda.to_device', (['self._sampling_volume_permeabilities[chunk_start:chunk_start + chunk_size]'], {}), '(self._sampling_volume_permeabilities[chunk_start:chunk_start +\n chunk_size])\n', (8188, 8268), False, 'from numba import cuda\n'), ((8918, 8952), 'numba.cuda.device_array', 'cuda.device_array', (['(chunk_size, 3)'], {}), '((chunk_size, 3))\n', (8935, 8952), False, 'from numba import cuda\n'), ((10190, 10243), 'numpy.append', 'np.append', (['field_vectors', 'field_vectors_local'], {'axis': '(0)'}), '(field_vectors, field_vectors_local, axis=0)\n', (10199, 10243), True, 'import numpy as np\n'), ((10346, 10369), 'numpy.array', 'np.array', (['field_vectors'], {}), '(field_vectors)\n', (10354, 10369), True, 'import numpy as np\n'), ((8525, 8621), 'magneticalc.Debug.Debug', 'Debug', (['self', '""".get_result(): Interruption requested, exiting now"""'], {'color': 'Theme.PrimaryColor'}), "(self, '.get_result(): Interruption requested, exiting now', color=\n Theme.PrimaryColor)\n", (8530, 8621), False, 'from magneticalc.Debug import Debug\n'), ((8776, 8796), 'numpy.zeros', 'np.zeros', (['chunk_size'], {}), '(chunk_size)\n', (8784, 8796), True, 'import numpy as np\n'), ((8861, 8881), 'numpy.zeros', 'np.zeros', (['chunk_size'], {}), '(chunk_size)\n', (8869, 8881), True, 'import numpy as np\n'), ((8458, 8481), 'PyQt5.QtCore.QThread.currentThread', 'QThread.currentThread', ([], {}), '()\n', (8479, 8481), False, 'from PyQt5.QtCore import QThread\n')]
import numpy as np import pandas as pd import anndata as ad import squidpy as sq import eggplant as eg from scipy.spatial.distance import cdist import torch as t import unittest import gpytorch as gp from . import utils as ut class GetLandmarkDistance(unittest.TestCase): def test_default_wo_ref( self, ): adata = ut.create_adata() eg.pp.get_landmark_distance(adata) def test_standard_ref( self, ): adata = ut.create_adata() reference_input = ut.create_model_input() ref = eg.m.Reference( domain=reference_input["domain"], landmarks=pd.DataFrame(reference_input["landmarks"]), meta=reference_input["meta"], ) eg.pp.get_landmark_distance( adata, reference=ref, ) def test_np_ref( self, ): adata = ut.create_adata() reference_input = ut.create_model_input() eg.pp.get_landmark_distance( adata, reference=reference_input["landmarks"].numpy(), ) class ReferenceToGrid(unittest.TestCase): def test_default_bw_image( self, ): side_size = 500 ref_img, counts = ut.create_image( color=False, side_size=side_size, return_counts=True ) ref_crd, mta = eg.pp.reference_to_grid( ref_img, n_approx_points=int(side_size**2), n_regions=1, background_color="black", ) def test_default_color_image( self, ): side_size = 32 ref_img, counts = ut.create_image( color=True, side_size=side_size, return_counts=True, ) ref_crd, mta = eg.pp.reference_to_grid( ref_img, n_approx_points=int(side_size**2), n_regions=3, background_color="black", ) _, mta_counts = np.unique(mta, return_counts=True) obs_prop = np.sort(mta_counts / sum(mta_counts)) true_prop = np.sort(counts / sum(counts)) for ii in range(3): self.assertAlmostEqual( obs_prop[ii], true_prop[ii], places=0, ) class MatchScales(unittest.TestCase): def test_default( self, ): adata = ut.create_adata() reference_input = ut.create_model_input() ref = eg.m.Reference( domain=reference_input["domain"], landmarks=reference_input["landmarks"], meta=reference_input["meta"], ) eg.pp.match_scales(adata, ref) del adata.uns["spatial"] eg.pp.match_scales(adata, ref) def test_pd_lmk_obs( self, ): adata = ut.create_adata() adata.uns["curated_landmarks"] = pd.DataFrame(adata.uns["curated_landmarks"]) reference_input = ut.create_model_input() ref = eg.m.Reference( domain=reference_input["domain"], landmarks=pd.DataFrame(reference_input["landmarks"]), meta=reference_input["meta"], ) eg.pp.match_scales(adata, ref) def test_not_implemented_lmk_obs( self, ): adata = ut.create_adata() adata.uns["curated_landmarks"] = 0 reference_input = ut.create_model_input() ref = eg.m.Reference( domain=reference_input["domain"], landmarks=pd.DataFrame(reference_input["landmarks"]), meta=reference_input["meta"], ) self.assertRaises( NotImplementedError, eg.pp.match_scales, adata, ref, ) def test_no_landmarks( self, ): adata = ut.create_adata() del adata.uns["curated_landmarks"] reference_input = ut.create_model_input() ref = eg.m.Reference( domain=reference_input["domain"], landmarks=pd.DataFrame(reference_input["landmarks"]), meta=reference_input["meta"], ) self.assertRaises( Exception, eg.pp.match_scales, adata, ref, ) def test_ref_pd( self, ): adata = ut.create_adata() reference_input = ut.create_model_input() eg.pp.match_scales(adata, pd.DataFrame(reference_input["landmarks"].numpy())) def test_ref_np( self, ): adata = ut.create_adata() reference_input = ut.create_model_input() eg.pp.match_scales(adata, reference_input["landmarks"].numpy()) def test_ref_not_implemented( self, ): adata = ut.create_adata() self.assertRaises( NotImplementedError, eg.pp.match_scales, adata, 4, ) class Normalization(unittest.TestCase): def test_default( self, ): adata = ut.create_adata() eg.pp.default_normalization(adata) def test_custom( self, ): adata = ut.create_adata() eg.pp.default_normalization( adata, min_cells=0.1, total_counts=1e3, exclude_highly_expressed=True, ) class JoinAdatas(unittest.TestCase): def test_default( self, ): adata_1 = ut.create_adata(n_features=3, n_obs=4)[0:4, :] adata_2 = ut.create_adata(n_features=2, n_obs=4)[0:3, :] adata_1.obs.index = ["A1", "A2", "A3", "A4"] adata_2.obs.index = ["B1", "B2", "B3"] adata_1.var.index = ["fA1", "fA2", "fC1"] adata_2.var.index = ["fB1", "fC1"] new_adata = eg.pp.join_adatas((adata_1, adata_2)) n_nas = np.isnan(new_adata.X).sum() self.assertEqual(n_nas, 0) new_var_index_true = pd.Index(["fA1", "fA2", "fC1", "fB1", "fB1"]) new_obs_index_true = ["A1", "A2", "A3", "A4"] + ["B1", "B2", "B3"] self.assertTrue(all([x in new_var_index_true for x in new_adata.var.index])) self.assertTrue(all([x in new_obs_index_true for x in new_adata.obs.index])) class SpatialSmoothing(unittest.TestCase): def test_default( self, ): adata = ut.create_adata() eg.pp.spatial_smoothing(adata) def test_custom_structured( self, ): adata = ut.create_adata() adata.obsm["test"] = adata.obsm["spatial"].copy() del adata.obsm["spatial"] eg.pp.spatial_smoothing( adata, spatial_key="test", coord_type="generic", n_neigh=6, sigma=20, ) def test_custom_random( self, ): adata = ut.create_adata() adata.obsm["spatial"] = np.random.uniform(0, 1, size=(adata.shape[0], 2)) eg.pp.spatial_smoothing( adata, spatial_key="spatial", coord_type="generic", ) if __name__ == "__main__": unittest.main()
[ "eggplant.pp.join_adatas", "eggplant.pp.default_normalization", "eggplant.pp.spatial_smoothing", "numpy.unique", "pandas.DataFrame", "eggplant.pp.match_scales", "eggplant.m.Reference", "pandas.Index", "eggplant.pp.get_landmark_distance", "numpy.isnan", "numpy.random.uniform", "unittest.main" ]
[((6934, 6949), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6947, 6949), False, 'import unittest\n'), ((366, 400), 'eggplant.pp.get_landmark_distance', 'eg.pp.get_landmark_distance', (['adata'], {}), '(adata)\n', (393, 400), True, 'import eggplant as eg\n'), ((737, 786), 'eggplant.pp.get_landmark_distance', 'eg.pp.get_landmark_distance', (['adata'], {'reference': 'ref'}), '(adata, reference=ref)\n', (764, 786), True, 'import eggplant as eg\n'), ((1938, 1972), 'numpy.unique', 'np.unique', (['mta'], {'return_counts': '(True)'}), '(mta, return_counts=True)\n', (1947, 1972), True, 'import numpy as np\n'), ((2427, 2550), 'eggplant.m.Reference', 'eg.m.Reference', ([], {'domain': "reference_input['domain']", 'landmarks': "reference_input['landmarks']", 'meta': "reference_input['meta']"}), "(domain=reference_input['domain'], landmarks=reference_input[\n 'landmarks'], meta=reference_input['meta'])\n", (2441, 2550), True, 'import eggplant as eg\n'), ((2602, 2632), 'eggplant.pp.match_scales', 'eg.pp.match_scales', (['adata', 'ref'], {}), '(adata, ref)\n', (2620, 2632), True, 'import eggplant as eg\n'), ((2674, 2704), 'eggplant.pp.match_scales', 'eg.pp.match_scales', (['adata', 'ref'], {}), '(adata, ref)\n', (2692, 2704), True, 'import eggplant as eg\n'), ((2827, 2871), 'pandas.DataFrame', 'pd.DataFrame', (["adata.uns['curated_landmarks']"], {}), "(adata.uns['curated_landmarks'])\n", (2839, 2871), True, 'import pandas as pd\n'), ((3125, 3155), 'eggplant.pp.match_scales', 'eg.pp.match_scales', (['adata', 'ref'], {}), '(adata, ref)\n', (3143, 3155), True, 'import eggplant as eg\n'), ((4940, 4974), 'eggplant.pp.default_normalization', 'eg.pp.default_normalization', (['adata'], {}), '(adata)\n', (4967, 4974), True, 'import eggplant as eg\n'), ((5060, 5165), 'eggplant.pp.default_normalization', 'eg.pp.default_normalization', (['adata'], {'min_cells': '(0.1)', 'total_counts': '(1000.0)', 'exclude_highly_expressed': '(True)'}), '(adata, min_cells=0.1, total_counts=1000.0,\n exclude_highly_expressed=True)\n', (5087, 5165), True, 'import eggplant as eg\n'), ((5647, 5684), 'eggplant.pp.join_adatas', 'eg.pp.join_adatas', (['(adata_1, adata_2)'], {}), '((adata_1, adata_2))\n', (5664, 5684), True, 'import eggplant as eg\n'), ((5795, 5840), 'pandas.Index', 'pd.Index', (["['fA1', 'fA2', 'fC1', 'fB1', 'fB1']"], {}), "(['fA1', 'fA2', 'fC1', 'fB1', 'fB1'])\n", (5803, 5840), True, 'import pandas as pd\n'), ((6218, 6248), 'eggplant.pp.spatial_smoothing', 'eg.pp.spatial_smoothing', (['adata'], {}), '(adata)\n', (6241, 6248), True, 'import eggplant as eg\n'), ((6439, 6536), 'eggplant.pp.spatial_smoothing', 'eg.pp.spatial_smoothing', (['adata'], {'spatial_key': '"""test"""', 'coord_type': '"""generic"""', 'n_neigh': '(6)', 'sigma': '(20)'}), "(adata, spatial_key='test', coord_type='generic',\n n_neigh=6, sigma=20)\n", (6462, 6536), True, 'import eggplant as eg\n'), ((6720, 6769), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {'size': '(adata.shape[0], 2)'}), '(0, 1, size=(adata.shape[0], 2))\n', (6737, 6769), True, 'import numpy as np\n'), ((6778, 6853), 'eggplant.pp.spatial_smoothing', 'eg.pp.spatial_smoothing', (['adata'], {'spatial_key': '"""spatial"""', 'coord_type': '"""generic"""'}), "(adata, spatial_key='spatial', coord_type='generic')\n", (6801, 6853), True, 'import eggplant as eg\n'), ((633, 675), 'pandas.DataFrame', 'pd.DataFrame', (["reference_input['landmarks']"], {}), "(reference_input['landmarks'])\n", (645, 675), True, 'import pandas as pd\n'), ((3020, 3062), 'pandas.DataFrame', 'pd.DataFrame', (["reference_input['landmarks']"], {}), "(reference_input['landmarks'])\n", (3032, 3062), True, 'import pandas as pd\n'), ((3441, 3483), 'pandas.DataFrame', 'pd.DataFrame', (["reference_input['landmarks']"], {}), "(reference_input['landmarks'])\n", (3453, 3483), True, 'import pandas as pd\n'), ((3950, 3992), 'pandas.DataFrame', 'pd.DataFrame', (["reference_input['landmarks']"], {}), "(reference_input['landmarks'])\n", (3962, 3992), True, 'import pandas as pd\n'), ((5702, 5723), 'numpy.isnan', 'np.isnan', (['new_adata.X'], {}), '(new_adata.X)\n', (5710, 5723), True, 'import numpy as np\n')]
# Conventional Machine Learning Algorithms # Class of "NaiveBayes". # Author: <NAME> # Create on: 2018/04/23 # Modify on: 2018/04/25 # ,,, ,,, # ;" '; ;' ", # ; @.ss$$$$$$s.@ ; # `s$$$$$$$$$$$$$$$' # $$$$$$$$$$$$$$$$$$ # $$$$P""Y$$$Y""W$$$$$ # $$$$ p"$$$"q $$$$$ # $$$$ .$$$$$. $$$$' # $$$DaU$$O$$DaU$$$' # '$$$$'.^.'$$$$' # '&$$$$$&' from __future__ import division from __future__ import print_function import numpy as np class NaiveBayes(object): def __init__(self, alpha=1.0): '''__INIT__ Inialization of NaiveBayes Instance. Input: ------ - alpha : float, additive smoothing parameter. If it is negative, it will be set to 0. ''' # The additive smoothing parameter self.alpha = alpha if alpha >= 0 else 0 # Number of training sampels self.N = None # Number of features self.F = None # A list contains all labels self.labels = None # Three dictionaries that contain # prior probabilities # conditional probabilities # post probabilities self.prior_probs = None self.cond_probs = None self.post_probs = None # List indicates the index of feature # which is continuous self.cont_feat_idx = None return def _initialize(self, X, y, cont_feat_idx): '''_INITIALIZE Initialzie instance variables. Inputs: ------- - X : numpy ndarray in shape [n_samples, n_features], features array of training samples. - y : numpy ndarray in shape [n_samples, ], labels list of training samples. - cont_feat_idx : int list or None or "all", default if an empty list. It indicates the indices of features which are continuous. "all" means all features are continuous; None means all features are discrete. ''' # Set the number of samples # and the number of features self.N, self.F = X.shape # Extract all unique labels self.labels = list(set(y)) # Create empty dictionaries self.prior_probs = {} self.cond_probs = {} self.post_probs = {} if cont_feat_idx == "all": # All features are continuous self.cont_feat_idx = list(range(self.F)) elif cont_feat_idx is None: # All features are discrete self.cont_feat_idx = [] else: # Continuous features are indicated # in the given list self.cont_feat_idx = cont_feat_idx return def _compute_prior_probs(self, y): '''_COMPUTE_PRIOR_PROBS Compute prior probabilities from labels of training samples. Input: ------ - y : numpy ndarray in shape [n_samples, ], the labels list of training samples. Result: ------- The formation of self.prior_probs: { label-1: prob-1, : lebel-n: prob-n } ''' for label in self.labels: # For each label, compute probability # as Equation 1 prob = ((len(np.where(y == label)[0]) + self.alpha) / (self.N + len(self.labels) * self.alpha)) self.prior_probs[label] = prob return def _compute_cond_probs(self, X, y): '''_COMPUTE_COND_PROBS Compute conditional probabilities. Inputs: ------- - X : numpy ndarray in shape [n_samples, n_features], features array of training samples. - y : numpy ndarray in shape [n_samples, ], labels list of training samples. Result: ------- The formation of self.cond_probs: { feat-1: { >--------------------| group-1: { | label-1: prob-111, | : | label-n: prob-11n | }, | : |--> Discrete Feature group-n: { | label-1: prob-1n1, | : | label-n: prob-1nn | } | } >----------------------------| : feat-n: { >--------------------| label-1: { | mu: feature's mean, | sigma: feature's std | }, | : |--> Continuous Feature label-n: { | mu: feature's mean, | sigma: feature's std | } | } >----------------------------| } ''' for j in range(self.F): # Extract one feature over all samples Xf = X[:, j] feat_dict = {} if j not in self.cont_feat_idx: # The feature is discrete # Get unique groups feat_set = set(Xf) set_len = len(feat_set) for f in feat_set: f_dict = {} for l in self.labels: # Compute conditianl probability as Equation 2 f_dict[l] = ((len(np.where((Xf == f) & (y == l))[0]) + self.alpha) / (len(np.where(y == l)[0]) + set_len * self.alpha)) feat_dict[f] = f_dict else: # The feature is continuous for l in self.labels: l_dict = {} # Estimate parameters of Gaussian distribution # from training samples as Equation 5 and 6 l_dict["mu"] = np.mean(Xf[y == l]) l_dict["sigma"] = np.std(Xf[y == l]) feat_dict[l] = l_dict self.cond_probs[j] = feat_dict return def _compute_post_probs(self, X): '''_COMPUTE_POST_PROBS Compute post probabilities of given dataset. Input: ------ - X : numpy ndarray in shape [n_samples, n_features], feature array of test set to be predicted. Result: ------- The formation of self.post_probs: { sample-1: { label-1: prob-11, : leble-n: prob-1n }, : sample-n: { label-1: prob-n1, label-n: prob-nn } } ''' for i in range(len(X)): # For each sample in test set i_dict = {} for l in self.labels: post_prob = self.prior_probs[l] for j in range(self.F): # For each feature of one sample if j not in self.cont_feat_idx: # Compute as Equation 3 # if the feature is discrete post_prob *= self.cond_probs[j][X[i, j]][l] else: mu = self.cond_probs[j][l]["mu"] sigma = self.cond_probs[j][l]["sigma"] # Compute as Equation 7 # if the feature is continuous post_prob *= (np.exp(-(X[i, j] - mu) ** 2 / (2 * sigma ** 2)) / (np.sqrt(2 * np.pi * sigma ** 2))) i_dict[l] = post_prob self.post_probs[i] = i_dict return def fit(self, X, y, cont_feat_idx=[]): '''FIT Training Naive Bayes Classifier by the given data. Two steps are contained: -1- Compute prior-probabilities -2- Compute conditional probabilities Inputs: ------- - X : numpy ndarray in shape [n_samples, n_features], features array of training samples. - y : numpy ndarray in shape [n_samples, ], labels list of training samples. - cont_feat_idx : int list or None or "all", default if an empty list. It indicates the indices of features which are continuous. "all" means all features are continuous; None means all features are discrete. ''' print("Fitting Naive Bayes Classifier ...") self._initialize(X, y, cont_feat_idx) self._compute_prior_probs(y) self._compute_cond_probs(X, y) return def predict(self, X): '''PREDICT Make predictoins on given dataset. Input: ------ - X : numpy ndarray in shape [n_samples, n_features], feature array to be predicted. Output: ------- - numpy ndarray in shape [n_samples, ], classification results of given samples. ''' # Compute post-probabilities self._compute_post_probs(X) # Get the calssification result of each sample # by finding the maximum value among post-probs # of one sample as Equation 4 result = [] for i in self.post_probs: preds = list(self.post_probs[i].values()) idx = preds.index(max(preds)) result.append(self.labels[idx]) return np.array(result)
[ "numpy.mean", "numpy.sqrt", "numpy.where", "numpy.exp", "numpy.array", "numpy.std" ]
[((10275, 10291), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (10283, 10291), True, 'import numpy as np\n'), ((6472, 6491), 'numpy.mean', 'np.mean', (['Xf[y == l]'], {}), '(Xf[y == l])\n', (6479, 6491), True, 'import numpy as np\n'), ((6530, 6548), 'numpy.std', 'np.std', (['Xf[y == l]'], {}), '(Xf[y == l])\n', (6536, 6548), True, 'import numpy as np\n'), ((3518, 3538), 'numpy.where', 'np.where', (['(y == label)'], {}), '(y == label)\n', (3526, 3538), True, 'import numpy as np\n'), ((8144, 8191), 'numpy.exp', 'np.exp', (['(-(X[i, j] - mu) ** 2 / (2 * sigma ** 2))'], {}), '(-(X[i, j] - mu) ** 2 / (2 * sigma ** 2))\n', (8150, 8191), True, 'import numpy as np\n'), ((8233, 8264), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi * sigma ** 2)'], {}), '(2 * np.pi * sigma ** 2)\n', (8240, 8264), True, 'import numpy as np\n'), ((5993, 6023), 'numpy.where', 'np.where', (['((Xf == f) & (y == l))'], {}), '((Xf == f) & (y == l))\n', (6001, 6023), True, 'import numpy as np\n'), ((6086, 6102), 'numpy.where', 'np.where', (['(y == l)'], {}), '(y == l)\n', (6094, 6102), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created by JoeYip on 01/04/2019 :copyright: (c) 2019 by nesting.xyz :license: BSD, see LICENSE for more details. """ import os import numpy as np import collections from bnlp import project_dir class EmbeddingDictionary(object): def __init__(self, info, normalize=True, maybe_cache=None): self._size = info["size"] self._normalize = normalize self._path = os.path.join(project_dir, info["path"]) if maybe_cache is not None and maybe_cache._path == self._path: assert self._size == maybe_cache._size self._embeddings = maybe_cache._embeddings else: self._embeddings = self.load_embedding_dict(self._path) @property def size(self): return self._size def load_embedding_dict(self, path): print("Loading word embeddings from {}...".format(path)) default_embedding = np.zeros(self.size) embedding_dict = collections.defaultdict(lambda: default_embedding) if len(path) > 0: vocab_size = None with open(path, encoding='utf-8') as f: f.readline() # skip first line for i, line in enumerate(f.readlines()): word_end = line.find(" ") word = line[:word_end] embedding = np.fromstring(line[word_end + 1:], np.float32, sep=" ") assert len(embedding) == self.size embedding_dict[word] = embedding if vocab_size is not None: assert vocab_size == len(embedding_dict) print("Done loading word embeddings.") return embedding_dict def __getitem__(self, key): embedding = self._embeddings[key] if self._normalize: embedding = self.normalize(embedding) return embedding def normalize(self, v): norm = np.linalg.norm(v) if norm > 0: return v / norm else: return v
[ "os.path.join", "numpy.zeros", "collections.defaultdict", "numpy.linalg.norm", "numpy.fromstring" ]
[((428, 467), 'os.path.join', 'os.path.join', (['project_dir', "info['path']"], {}), "(project_dir, info['path'])\n", (440, 467), False, 'import os\n'), ((924, 943), 'numpy.zeros', 'np.zeros', (['self.size'], {}), '(self.size)\n', (932, 943), True, 'import numpy as np\n'), ((969, 1020), 'collections.defaultdict', 'collections.defaultdict', (['(lambda : default_embedding)'], {}), '(lambda : default_embedding)\n', (992, 1020), False, 'import collections\n'), ((1917, 1934), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (1931, 1934), True, 'import numpy as np\n'), ((1354, 1409), 'numpy.fromstring', 'np.fromstring', (['line[word_end + 1:]', 'np.float32'], {'sep': '""" """'}), "(line[word_end + 1:], np.float32, sep=' ')\n", (1367, 1409), True, 'import numpy as np\n')]
import copy import numpy as np import random from collections import namedtuple, deque from keras import layers, models, optimizers from keras import backend as K class ReplayBuffer: def __init__(self, buffer_size, batch_size): self.memory = deque(maxlen=buffer_size) self.batch_size = batch_size self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"]) def add(self, state, action, reward, next_state, done): e = self.experience(state, action, reward, next_state, done) self.memory.append(e) def sample(self, batch_size=64): return random.sample(self.memory, k=self.batch_size) def __len__(self): return len(self.memory) class Actor: def __init__(self, state_size, action_size, action_low, action_high): self.state_size = state_size self.action_size = action_size self.action_low = action_low self.action_high = action_high self.action_range = self.action_high - self.action_low self.build_model() def build_model(self): input_states = layers.Input(shape=(self.state_size,), name='states') layer_1 = layers.Dense(units=32, activation='relu')(input_states) layer_2 = layers.Dense(units=64, activation='relu')(layer_1) layer_3 = layers.Dense(units=32, activation='relu')(layer_2) raw_actions = layers.Dense(units=self.action_size, activation='sigmoid', name='raw_actions')(layer_3) actions = layers.Lambda(lambda x: (x * self.action_range) + self.action_low, name='actions')(raw_actions) self.model = models.Model(inputs=input_states, outputs=actions) gradients = layers.Input(shape=(self.action_size,)) loss = K.mean(-gradients * actions) optimizer = optimizers.Adam() updates_op = optimizer.get_updates(params=self.model.trainable_weights, loss=loss) self.train_fn = K.function( inputs=[self.model.input, gradients, K.learning_phase()], outputs=[], updates=updates_op) class Critic: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.build_model() def build_model(self): states = layers.Input(shape=(self.state_size,), name='states') actions = layers.Input(shape=(self.action_size,), name='actions') net_states = layers.Dense(units=32, activation='relu')(states) net_states = layers.Dense(units=64, activation='relu')(net_states) net_actions = layers.Dense(units=32, activation='relu')(actions) net_actions = layers.Dense(units=64, activation='relu')(net_actions) net = layers.Add()([net_states, net_actions]) net = layers.Activation('relu')(net) Q_values = layers.Dense(units=1, name='q_values')(net) self.model = models.Model(inputs=[states, actions], outputs=Q_values) optimizer = optimizers.Adam() self.model.compile(optimizer=optimizer, loss='mse') action_gradients = K.gradients(Q_values, actions) self.get_action_gradients = K.function( inputs=[*self.model.input, K.learning_phase()], outputs=action_gradients) class OUNoise: def __init__(self, size, mu, theta, sigma): self.mu = mu * np.ones(size) self.theta = theta self.sigma = sigma self.reset() def reset(self): self.state = copy.copy(self.mu) def sample(self): x = self.state dx = self.theta * (self.mu - x) + self.sigma * np.random.randn(len(x)) self.state = x + dx return self.state class DDPG(): episode_rewards = [] total_reward = 0 def __init__(self, task): self.task = task self.state_size = task.state_size self.action_size = task.action_size self.action_low = task.action_low self.action_high = task.action_high self.actor_local = Actor(self.state_size, self.action_size, self.action_low, self.action_high) self.actor_target = Actor(self.state_size, self.action_size, self.action_low, self.action_high) self.critic_local = Critic(self.state_size, self.action_size) self.critic_target = Critic(self.state_size, self.action_size) self.critic_target.model.set_weights(self.critic_local.model.get_weights()) self.actor_target.model.set_weights(self.actor_local.model.get_weights()) self.exploration_mu = 1.2 self.exploration_theta = 0.15 self.exploration_sigma = 0.3 self.noise = OUNoise(self.action_size, self.exploration_mu, self.exploration_theta, self.exploration_sigma) self.buffer_size = 1000000 self.batch_size = 64 self.memory = ReplayBuffer(self.buffer_size, self.batch_size) self.gamma = 0.99 self.tau = 0.001 self.episode_rewards = [] self.total_reward = 0 def reset_episode(self): self.noise.reset() state = self.task.reset() self.last_state = state return state def update_rewards(self): self.episode_rewards.append(self.total_reward) self.total_reward = 0 def step(self, action, reward, next_state, done): self.memory.add(self.last_state, action, reward, next_state, done) self.total_reward += reward if len(self.memory) > self.batch_size: experiences = self.memory.sample() self.learn(experiences) self.last_state = next_state def act(self, state): state = np.reshape(state, [-1, self.state_size]) action = self.actor_local.model.predict(state)[0] return list(action + self.noise.sample()) def learn(self, experiences): states = np.vstack([e.state for e in experiences if e is not None]) actions = np.array([e.action for e in experiences if e is not None]).astype(np.float32).reshape(-1, self.action_size) rewards = np.array([e.reward for e in experiences if e is not None]).astype(np.float32).reshape(-1, 1) dones = np.array([e.done for e in experiences if e is not None]).astype(np.uint8).reshape(-1, 1) next_states = np.vstack([e.next_state for e in experiences if e is not None]) actions_next = self.actor_target.model.predict_on_batch(next_states) Q_targets_next = self.critic_target.model.predict_on_batch([next_states, actions_next]) Q_targets = rewards + self.gamma * Q_targets_next * (1 - dones) self.critic_local.model.train_on_batch(x=[states, actions], y=Q_targets) action_gradients = np.reshape(self.critic_local.get_action_gradients([states, actions, 0]), (-1, self.action_size)) self.actor_local.train_fn([states, action_gradients, 1]) self.soft_update(self.critic_local.model, self.critic_target.model) self.soft_update(self.actor_local.model, self.actor_target.model) def soft_update(self, local_model, target_model): local_weights = np.array(local_model.get_weights()) target_weights = np.array(target_model.get_weights()) assert len(local_weights) == len(target_weights), "Local and target model parameters must have the same size" new_weights = self.tau * local_weights + (1 - self.tau) * target_weights target_model.set_weights(new_weights)
[ "keras.optimizers.Adam", "random.sample", "collections.namedtuple", "collections.deque", "numpy.reshape", "numpy.ones", "keras.backend.mean", "keras.layers.Lambda", "keras.backend.learning_phase", "keras.backend.gradients", "numpy.array", "keras.layers.Input", "keras.models.Model", "numpy....
[((261, 286), 'collections.deque', 'deque', ([], {'maxlen': 'buffer_size'}), '(maxlen=buffer_size)\n', (266, 286), False, 'from collections import namedtuple, deque\n'), ((350, 443), 'collections.namedtuple', 'namedtuple', (['"""Experience"""'], {'field_names': "['state', 'action', 'reward', 'next_state', 'done']"}), "('Experience', field_names=['state', 'action', 'reward',\n 'next_state', 'done'])\n", (360, 443), False, 'from collections import namedtuple, deque\n'), ((713, 758), 'random.sample', 'random.sample', (['self.memory'], {'k': 'self.batch_size'}), '(self.memory, k=self.batch_size)\n', (726, 758), False, 'import random\n'), ((1225, 1278), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(self.state_size,)', 'name': '"""states"""'}), "(shape=(self.state_size,), name='states')\n", (1237, 1278), False, 'from keras import layers, models, optimizers\n'), ((1796, 1846), 'keras.models.Model', 'models.Model', ([], {'inputs': 'input_states', 'outputs': 'actions'}), '(inputs=input_states, outputs=actions)\n', (1808, 1846), False, 'from keras import layers, models, optimizers\n'), ((1876, 1915), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(self.action_size,)'}), '(shape=(self.action_size,))\n', (1888, 1915), False, 'from keras import layers, models, optimizers\n'), ((1931, 1959), 'keras.backend.mean', 'K.mean', (['(-gradients * actions)'], {}), '(-gradients * actions)\n', (1937, 1959), True, 'from keras import backend as K\n'), ((1989, 2006), 'keras.optimizers.Adam', 'optimizers.Adam', ([], {}), '()\n', (2004, 2006), False, 'from keras import layers, models, optimizers\n'), ((2500, 2553), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(self.state_size,)', 'name': '"""states"""'}), "(shape=(self.state_size,), name='states')\n", (2512, 2553), False, 'from keras import layers, models, optimizers\n'), ((2572, 2627), 'keras.layers.Input', 'layers.Input', ([], {'shape': '(self.action_size,)', 'name': '"""actions"""'}), "(shape=(self.action_size,), name='actions')\n", (2584, 2627), False, 'from keras import layers, models, optimizers\n'), ((3202, 3258), 'keras.models.Model', 'models.Model', ([], {'inputs': '[states, actions]', 'outputs': 'Q_values'}), '(inputs=[states, actions], outputs=Q_values)\n', (3214, 3258), False, 'from keras import layers, models, optimizers\n'), ((3338, 3355), 'keras.optimizers.Adam', 'optimizers.Adam', ([], {}), '()\n', (3353, 3355), False, 'from keras import layers, models, optimizers\n'), ((3502, 3532), 'keras.backend.gradients', 'K.gradients', (['Q_values', 'actions'], {}), '(Q_values, actions)\n', (3513, 3532), True, 'from keras import backend as K\n'), ((3980, 3998), 'copy.copy', 'copy.copy', (['self.mu'], {}), '(self.mu)\n', (3989, 3998), False, 'import copy\n'), ((6649, 6689), 'numpy.reshape', 'np.reshape', (['state', '[-1, self.state_size]'], {}), '(state, [-1, self.state_size])\n', (6659, 6689), True, 'import numpy as np\n'), ((6855, 6913), 'numpy.vstack', 'np.vstack', (['[e.state for e in experiences if e is not None]'], {}), '([e.state for e in experiences if e is not None])\n', (6864, 6913), True, 'import numpy as np\n'), ((7278, 7341), 'numpy.vstack', 'np.vstack', (['[e.next_state for e in experiences if e is not None]'], {}), '([e.next_state for e in experiences if e is not None])\n', (7287, 7341), True, 'import numpy as np\n'), ((1306, 1347), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(32)', 'activation': '"""relu"""'}), "(units=32, activation='relu')\n", (1318, 1347), False, 'from keras import layers, models, optimizers\n'), ((1380, 1421), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(64)', 'activation': '"""relu"""'}), "(units=64, activation='relu')\n", (1392, 1421), False, 'from keras import layers, models, optimizers\n'), ((1449, 1490), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(32)', 'activation': '"""relu"""'}), "(units=32, activation='relu')\n", (1461, 1490), False, 'from keras import layers, models, optimizers\n'), ((1531, 1609), 'keras.layers.Dense', 'layers.Dense', ([], {'units': 'self.action_size', 'activation': '"""sigmoid"""', 'name': '"""raw_actions"""'}), "(units=self.action_size, activation='sigmoid', name='raw_actions')\n", (1543, 1609), False, 'from keras import layers, models, optimizers\n'), ((1658, 1743), 'keras.layers.Lambda', 'layers.Lambda', (['(lambda x: x * self.action_range + self.action_low)'], {'name': '"""actions"""'}), "(lambda x: x * self.action_range + self.action_low, name='actions'\n )\n", (1671, 1743), False, 'from keras import layers, models, optimizers\n'), ((2658, 2699), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(32)', 'activation': '"""relu"""'}), "(units=32, activation='relu')\n", (2670, 2699), False, 'from keras import layers, models, optimizers\n'), ((2729, 2770), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(64)', 'activation': '"""relu"""'}), "(units=64, activation='relu')\n", (2741, 2770), False, 'from keras import layers, models, optimizers\n'), ((2814, 2855), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(32)', 'activation': '"""relu"""'}), "(units=32, activation='relu')\n", (2826, 2855), False, 'from keras import layers, models, optimizers\n'), ((2887, 2928), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(64)', 'activation': '"""relu"""'}), "(units=64, activation='relu')\n", (2899, 2928), False, 'from keras import layers, models, optimizers\n'), ((2965, 2977), 'keras.layers.Add', 'layers.Add', ([], {}), '()\n', (2975, 2977), False, 'from keras import layers, models, optimizers\n'), ((3019, 3044), 'keras.layers.Activation', 'layers.Activation', (['"""relu"""'], {}), "('relu')\n", (3036, 3044), False, 'from keras import layers, models, optimizers\n'), ((3078, 3116), 'keras.layers.Dense', 'layers.Dense', ([], {'units': '(1)', 'name': '"""q_values"""'}), "(units=1, name='q_values')\n", (3090, 3116), False, 'from keras import layers, models, optimizers\n'), ((3839, 3852), 'numpy.ones', 'np.ones', (['size'], {}), '(size)\n', (3846, 3852), True, 'import numpy as np\n'), ((2183, 2201), 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (2199, 2201), True, 'from keras import backend as K\n'), ((3679, 3697), 'keras.backend.learning_phase', 'K.learning_phase', ([], {}), '()\n', (3695, 3697), True, 'from keras import backend as K\n'), ((6932, 6990), 'numpy.array', 'np.array', (['[e.action for e in experiences if e is not None]'], {}), '([e.action for e in experiences if e is not None])\n', (6940, 6990), True, 'import numpy as np\n'), ((7058, 7116), 'numpy.array', 'np.array', (['[e.reward for e in experiences if e is not None]'], {}), '([e.reward for e in experiences if e is not None])\n', (7066, 7116), True, 'import numpy as np\n'), ((7167, 7223), 'numpy.array', 'np.array', (['[e.done for e in experiences if e is not None]'], {}), '([e.done for e in experiences if e is not None])\n', (7175, 7223), True, 'import numpy as np\n')]
#https://teratail.com/questions/98319 # 2d img --> 3d img by luminance from PIL import Image, ImageOps import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt # 画像読み込み org_img = Image.open('4388281942_resized.jpg') # グレースケール化 img = ImageOps.grayscale(org_img) # 配列化 data = np.asarray(img) # データ表示 X,Y = np.mgrid[:data.shape[0], :data.shape[1]] ax = plt.gca(projection='3d') ax.plot_surface(X,Y,data,cmap='Reds',edgecolor='k',rcount=15,ccount=15) plt.show()
[ "PIL.Image.open", "matplotlib.pyplot.gca", "numpy.asarray", "PIL.ImageOps.grayscale", "matplotlib.pyplot.show" ]
[((215, 251), 'PIL.Image.open', 'Image.open', (['"""4388281942_resized.jpg"""'], {}), "('4388281942_resized.jpg')\n", (225, 251), False, 'from PIL import Image, ImageOps\n'), ((269, 296), 'PIL.ImageOps.grayscale', 'ImageOps.grayscale', (['org_img'], {}), '(org_img)\n', (287, 296), False, 'from PIL import Image, ImageOps\n'), ((310, 325), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (320, 325), True, 'import numpy as np\n'), ((387, 411), 'matplotlib.pyplot.gca', 'plt.gca', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (394, 411), True, 'import matplotlib.pyplot as plt\n'), ((484, 494), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (492, 494), True, 'import matplotlib.pyplot as plt\n')]
import threading import numpy as np class image_replay_buffer: def __init__(self, env_params, buffer_size): self.env_params = env_params self.size = buffer_size self.T = env_params['max_timesteps'] # memory management self.current_size = 0 self.n_transitions_stored = 0 # create the buffer to store info self.buffers = { 'obs_imgs': np.empty([buffer_size, 100, 100, 3], dtype=np.uint8), 'next_obs_imgs': np.empty([buffer_size, 100, 100, 3], dtype=np.uint8), 'rewards': np.empty([buffer_size], dtype=np.uint8), 'actions': np.empty([buffer_size, self.env_params['action']]), } # thread lock self.lock = threading.Lock() # store the episode def store_episode(self, obs_img, next_obs_img, action, rew): batch_size = obs_img.shape[0] with self.lock: idxs = self._get_storage_idx(inc=batch_size) # store the informations self.buffers['obs_imgs'][idxs] = obs_img self.buffers['next_obs_imgs'][idxs] = next_obs_img self.buffers['actions'][idxs] = action self.buffers['rewards'][idxs] = rew self.n_transitions_stored += self.T * batch_size # sample the data from the replay buffer def sample(self, batch_size): temp_buffers = {} with self.lock: for key in self.buffers.keys(): temp_buffers[key] = self.buffers[key][:self.current_size] return temp_buffers def _get_storage_idx(self, inc=None): inc = inc or 1 if self.current_size+inc <= self.size: idx = np.arange(self.current_size, self.current_size+inc) elif self.current_size < self.size: overflow = inc - (self.size - self.current_size) idx_a = np.arange(self.current_size, self.size) idx_b = np.random.randint(0, self.current_size, overflow) idx = np.concatenate([idx_a, idx_b]) else: idx = np.random.randint(0, self.size, inc) self.current_size = min(self.size, self.current_size+inc) if inc == 1: idx = idx[0] return idx class state_replay_buffer: def __init__(self, env_params, buffer_size): self.env_params = env_params self.size = buffer_size self.T = env_params['max_timesteps'] # memory management self.current_size = 0 self.n_transitions_stored = 0 # create the buffer to store info self.buffers = { 'obs_states': np.empty([buffer_size, self.env_params['obs']], dtype=np.uint8), 'obs_states_next': np.empty([buffer_size, self.env_params['obs']], dtype=np.uint8), 'r': np.empty([buffer_size], dtype=np.uint8), 'actions': np.empty([buffer_size, self.env_params['action']]), 'goal_states': np.empty([buffer_size, self.env_params['goal']]), 'goal_states_next': np.empty([buffer_size, self.env_params['goal']]) } # thread lock self.lock = threading.Lock() # store the episode def store_episode(self, obs_states, next_obs_states, actions, rewards, goal_states, next_goal_states): batch_size = obs_states.shape[0] with self.lock: idxs = self._get_storage_idx(inc=batch_size) # store the informations self.buffers['obs_states'][idxs] = obs_states self.buffers['obs_states_next'][idxs] = next_obs_states self.buffers['actions'][idxs] = actions self.buffers['r'][idxs] = rewards self.buffers['goal_states'][idxs] = goal_states self.buffers['goal_states_next'][idxs] = next_goal_states self.n_transitions_stored += self.T * batch_size # sample the data from the replay buffer def sample(self, batch_size): temp_buffers = {} with self.lock: for key in self.buffers.keys(): temp_buffers[key] = self.buffers[key][:self.current_size] return temp_buffers def _get_storage_idx(self, inc=None): inc = inc or 1 if self.current_size+inc <= self.size: idx = np.arange(self.current_size, self.current_size+inc) elif self.current_size < self.size: overflow = inc - (self.size - self.current_size) idx_a = np.arange(self.current_size, self.size) idx_b = np.random.randint(0, self.current_size, overflow) idx = np.concatenate([idx_a, idx_b]) else: idx = np.random.randint(0, self.size, inc) self.current_size = min(self.size, self.current_size+inc) if inc == 1: idx = idx[0] return idx
[ "threading.Lock", "numpy.random.randint", "numpy.empty", "numpy.concatenate", "numpy.arange" ]
[((806, 822), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (820, 822), False, 'import threading\n'), ((3270, 3286), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (3284, 3286), False, 'import threading\n'), ((426, 478), 'numpy.empty', 'np.empty', (['[buffer_size, 100, 100, 3]'], {'dtype': 'np.uint8'}), '([buffer_size, 100, 100, 3], dtype=np.uint8)\n', (434, 478), True, 'import numpy as np\n'), ((521, 573), 'numpy.empty', 'np.empty', (['[buffer_size, 100, 100, 3]'], {'dtype': 'np.uint8'}), '([buffer_size, 100, 100, 3], dtype=np.uint8)\n', (529, 573), True, 'import numpy as np\n'), ((610, 649), 'numpy.empty', 'np.empty', (['[buffer_size]'], {'dtype': 'np.uint8'}), '([buffer_size], dtype=np.uint8)\n', (618, 649), True, 'import numpy as np\n'), ((686, 736), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['action']]"], {}), "([buffer_size, self.env_params['action']])\n", (694, 736), True, 'import numpy as np\n'), ((1760, 1813), 'numpy.arange', 'np.arange', (['self.current_size', '(self.current_size + inc)'], {}), '(self.current_size, self.current_size + inc)\n', (1769, 1813), True, 'import numpy as np\n'), ((2690, 2753), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['obs']]"], {'dtype': 'np.uint8'}), "([buffer_size, self.env_params['obs']], dtype=np.uint8)\n", (2698, 2753), True, 'import numpy as np\n'), ((2798, 2861), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['obs']]"], {'dtype': 'np.uint8'}), "([buffer_size, self.env_params['obs']], dtype=np.uint8)\n", (2806, 2861), True, 'import numpy as np\n'), ((2892, 2931), 'numpy.empty', 'np.empty', (['[buffer_size]'], {'dtype': 'np.uint8'}), '([buffer_size], dtype=np.uint8)\n', (2900, 2931), True, 'import numpy as np\n'), ((2968, 3018), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['action']]"], {}), "([buffer_size, self.env_params['action']])\n", (2976, 3018), True, 'import numpy as np\n'), ((3059, 3107), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['goal']]"], {}), "([buffer_size, self.env_params['goal']])\n", (3067, 3107), True, 'import numpy as np\n'), ((3153, 3201), 'numpy.empty', 'np.empty', (["[buffer_size, self.env_params['goal']]"], {}), "([buffer_size, self.env_params['goal']])\n", (3161, 3201), True, 'import numpy as np\n'), ((4408, 4461), 'numpy.arange', 'np.arange', (['self.current_size', '(self.current_size + inc)'], {}), '(self.current_size, self.current_size + inc)\n', (4417, 4461), True, 'import numpy as np\n'), ((1937, 1976), 'numpy.arange', 'np.arange', (['self.current_size', 'self.size'], {}), '(self.current_size, self.size)\n', (1946, 1976), True, 'import numpy as np\n'), ((1997, 2046), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.current_size', 'overflow'], {}), '(0, self.current_size, overflow)\n', (2014, 2046), True, 'import numpy as np\n'), ((2065, 2095), 'numpy.concatenate', 'np.concatenate', (['[idx_a, idx_b]'], {}), '([idx_a, idx_b])\n', (2079, 2095), True, 'import numpy as np\n'), ((2128, 2164), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.size', 'inc'], {}), '(0, self.size, inc)\n', (2145, 2164), True, 'import numpy as np\n'), ((4585, 4624), 'numpy.arange', 'np.arange', (['self.current_size', 'self.size'], {}), '(self.current_size, self.size)\n', (4594, 4624), True, 'import numpy as np\n'), ((4645, 4694), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.current_size', 'overflow'], {}), '(0, self.current_size, overflow)\n', (4662, 4694), True, 'import numpy as np\n'), ((4713, 4743), 'numpy.concatenate', 'np.concatenate', (['[idx_a, idx_b]'], {}), '([idx_a, idx_b])\n', (4727, 4743), True, 'import numpy as np\n'), ((4776, 4812), 'numpy.random.randint', 'np.random.randint', (['(0)', 'self.size', 'inc'], {}), '(0, self.size, inc)\n', (4793, 4812), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """hategru.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fg_cClsHnbiRLknbfd1tVF2hTqP0UL4m """ from google.colab import drive drive.mount('/content/drive') import os import pickle import numpy as np import pandas as pd from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.layers import Dense from keras.layers import Dropout from keras.layers import concatenate from keras.layers.embeddings import Embedding from keras.layers import GRU from keras.layers import Input from keras.models import Model from keras.optimizers import Adam from sklearn import metrics from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from collections import defaultdict import pprint #from keras.models import load_model data = pd.read_csv("/content/drive/My Drive/Hate Speech Detection/Training/Datasets/hsfinal.csv") text_data = data["Comment"].tolist() text_labels = data["Hate"].tolist() # Split dataset in training and test X_train, X_test, y_train, y_test = train_test_split(text_data, text_labels, test_size=0.1, random_state=0) EMBEDDING_DIMENSION = 100 MAX_SENTENCE_LENGTH = 70 # One-hot-encoding the labels encoder = LabelEncoder() encoder.fit(y_train) encoded_labels_train = encoder.transform(y_train) labels_train = to_categorical(encoded_labels_train) # Tokenize the texts tokenizer = Tokenizer() tokenizer.fit_on_texts(X_train) sequences = tokenizer.texts_to_sequences(X_train) word_index_data = tokenizer.word_index # Padding to make all the texts of same length final_data = pad_sequences(sequences, maxlen=MAX_SENTENCE_LENGTH) # Get each word of Glove embeddings in a dictionary embeddings_index = {} with open(os.path.join('/content/drive/My Drive/Hate Speech Detection/Training/glove.6B.100d.txt')) as f: for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs print('Found %s word vectors.' % len(embeddings_index)) # Generate Embedding Matrix from the word vectors above embedding_matrix = np.zeros((len(word_index_data) + 1, EMBEDDING_DIMENSION)) for word, i in word_index_data.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: # words not found in embedding index will be all-zeros. embedding_matrix[i] = embedding_vector # Both the tasks should have same dimensions of inputs if(len(labels_train) % 2 != 0): labels_train = labels_train[:-1] final_data = final_data[:-1] # Task-1 training data and labels t1_y_train = labels_train[0:int(len(labels_train)/2)] t1_x_train = final_data[0:int(len(labels_train)/2)] # Task-2 training data and labels t2_y_train = labels_train[int(len(labels_train)/2):] t2_x_train = final_data[int(len(labels_train)/2):] t1_input_layer = Input(shape=(MAX_SENTENCE_LENGTH,)) t2_input_layer = Input(shape=(MAX_SENTENCE_LENGTH,)) shared_emb_layer = Embedding(len(word_index_data) + 1, EMBEDDING_DIMENSION, weights=[embedding_matrix] , input_length=MAX_SENTENCE_LENGTH, trainable=True) t1_emb_layer = shared_emb_layer(t1_input_layer) t2_emb_layer = shared_emb_layer(t2_input_layer) shared_grnn_layer = GRU(MAX_SENTENCE_LENGTH, activation='relu') t1_grnn_layer = shared_grnn_layer(t1_emb_layer) t2_grnn_layer = shared_grnn_layer(t2_emb_layer) # Merging layers merge_layer = concatenate([t1_grnn_layer, t2_grnn_layer], axis=-1) # Task-1 Specified Layers t1_dense_1 = Dense(30, activation='relu')(merge_layer) t1_dropout_layer = Dropout(0.3)(t1_dense_1) t1_dense_2 = Dense(30, activation='relu')(t1_dropout_layer) t1_dense_3 = Dense(30, activation='relu')(t1_dense_2) t1_prediction = Dense(labels_train.shape[1], activation='softmax')(t1_dense_3) # Task-2 Specified Layers t2_dense_1 = Dense(20, activation='relu')(merge_layer) t2_dropout_layer = Dropout(0.3)(t2_dense_1) t2_dense_2 = Dense(20, activation='relu')(t2_dropout_layer) t2_dense_3 = Dense(20, activation='relu')(t2_dense_2) t2_prediction = Dense(labels_train.shape[1], activation='softmax')(t2_dense_3) # Build the model hatespeech_model = Model(inputs=[t1_input_layer, t2_input_layer], outputs=[t1_prediction, t2_prediction]) # Compile the model hatespeech_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.001, clipvalue=1.0), metrics=['accuracy']) # Fitting the model hatespeech_model.fit([t1_x_train, t2_x_train], [t1_y_train, t2_y_train], epochs=3, batch_size=128) # saving the model hatespeech_model.save("/content/drive/My Drive/Hate Speech Detection/Production/Models/hate_model.h5") # saving the tokenizer with open('/content/drive/My Drive/Hate Speech Detection/Production/Models/tokenhater.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) print('Model and Tokenizer saved....') # Testing # Tokenize sequences_test = tokenizer.texts_to_sequences(X_test) # Padding to make all the texts of same length test_data = pad_sequences(sequences_test, maxlen=MAX_SENTENCE_LENGTH) # Both the tasks should have same dimensions of inputs if(len(y_test) % 2 != 0): y_test = y_test[:-1] test_data = test_data[:-1] # Task-1 training data and labels t1_y_test = y_test[0:int(len(y_test)/2)] t1_x_test = test_data[0:int(len(y_test)/2)] # Task-2 training data and labels t2_y_test = y_test[int(len(y_test)/2):] t2_x_test = test_data[int(len(y_test)/2):] y_pred_combined = hatespeech_model.predict([t1_x_test, t2_x_test]) t1_y_pred = np.argmax(y_pred_combined[0], axis=-1) t2_y_pred = np.argmax(y_pred_combined[1], axis=-1) t1_y_pred = encoder.inverse_transform(t1_y_pred) t2_y_pred = encoder.inverse_transform(t2_y_pred) t1_acc = metrics.accuracy_score(t1_y_test, t1_y_pred) print(f"Task 1 Accuracy: {t1_acc}") t2_acc = metrics.accuracy_score(t2_y_test, t2_y_pred) print(f"Task 2 Accuracy: {t2_acc}") t1_y_test t1_cf = metrics.confusion_matrix(t1_y_test, t1_y_pred) print(f'The confusion matrix for Task 1 is: \n {t1_cf}') t2_cf = metrics.confusion_matrix(t2_y_test, t2_y_pred) print(f'The confusion matrix for Task 2 is: \n {t2_cf}')
[ "sklearn.preprocessing.LabelEncoder", "pandas.read_csv", "google.colab.drive.mount", "keras.utils.to_categorical", "keras.layers.Dense", "keras.preprocessing.sequence.pad_sequences", "numpy.asarray", "keras.layers.concatenate", "keras.models.Model", "sklearn.metrics.confusion_matrix", "keras.opt...
[((226, 255), 'google.colab.drive.mount', 'drive.mount', (['"""/content/drive"""'], {}), "('/content/drive')\n", (237, 255), False, 'from google.colab import drive\n'), ((956, 1056), 'pandas.read_csv', 'pd.read_csv', (['"""/content/drive/My Drive/Hate Speech Detection/Training/Datasets/hsfinal.csv"""'], {}), "(\n '/content/drive/My Drive/Hate Speech Detection/Training/Datasets/hsfinal.csv'\n )\n", (967, 1056), True, 'import pandas as pd\n'), ((1194, 1265), 'sklearn.model_selection.train_test_split', 'train_test_split', (['text_data', 'text_labels'], {'test_size': '(0.1)', 'random_state': '(0)'}), '(text_data, text_labels, test_size=0.1, random_state=0)\n', (1210, 1265), False, 'from sklearn.model_selection import train_test_split\n'), ((1359, 1373), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (1371, 1373), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((1460, 1496), 'keras.utils.to_categorical', 'to_categorical', (['encoded_labels_train'], {}), '(encoded_labels_train)\n', (1474, 1496), False, 'from keras.utils import to_categorical\n'), ((1531, 1542), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (1540, 1542), False, 'from keras.preprocessing.text import Tokenizer\n'), ((1726, 1778), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['sequences'], {'maxlen': 'MAX_SENTENCE_LENGTH'}), '(sequences, maxlen=MAX_SENTENCE_LENGTH)\n', (1739, 1778), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((3014, 3049), 'keras.layers.Input', 'Input', ([], {'shape': '(MAX_SENTENCE_LENGTH,)'}), '(shape=(MAX_SENTENCE_LENGTH,))\n', (3019, 3049), False, 'from keras.layers import Input\n'), ((3067, 3102), 'keras.layers.Input', 'Input', ([], {'shape': '(MAX_SENTENCE_LENGTH,)'}), '(shape=(MAX_SENTENCE_LENGTH,))\n', (3072, 3102), False, 'from keras.layers import Input\n'), ((3377, 3420), 'keras.layers.GRU', 'GRU', (['MAX_SENTENCE_LENGTH'], {'activation': '"""relu"""'}), "(MAX_SENTENCE_LENGTH, activation='relu')\n", (3380, 3420), False, 'from keras.layers import GRU\n'), ((3549, 3601), 'keras.layers.concatenate', 'concatenate', (['[t1_grnn_layer, t2_grnn_layer]'], {'axis': '(-1)'}), '([t1_grnn_layer, t2_grnn_layer], axis=-1)\n', (3560, 3601), False, 'from keras.layers import concatenate\n'), ((4278, 4368), 'keras.models.Model', 'Model', ([], {'inputs': '[t1_input_layer, t2_input_layer]', 'outputs': '[t1_prediction, t2_prediction]'}), '(inputs=[t1_input_layer, t2_input_layer], outputs=[t1_prediction,\n t2_prediction])\n', (4283, 4368), False, 'from keras.models import Model\n'), ((5132, 5189), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['sequences_test'], {'maxlen': 'MAX_SENTENCE_LENGTH'}), '(sequences_test, maxlen=MAX_SENTENCE_LENGTH)\n', (5145, 5189), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((5646, 5684), 'numpy.argmax', 'np.argmax', (['y_pred_combined[0]'], {'axis': '(-1)'}), '(y_pred_combined[0], axis=-1)\n', (5655, 5684), True, 'import numpy as np\n'), ((5697, 5735), 'numpy.argmax', 'np.argmax', (['y_pred_combined[1]'], {'axis': '(-1)'}), '(y_pred_combined[1], axis=-1)\n', (5706, 5735), True, 'import numpy as np\n'), ((5845, 5889), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['t1_y_test', 't1_y_pred'], {}), '(t1_y_test, t1_y_pred)\n', (5867, 5889), False, 'from sklearn import metrics\n'), ((5936, 5980), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['t2_y_test', 't2_y_pred'], {}), '(t2_y_test, t2_y_pred)\n', (5958, 5980), False, 'from sklearn import metrics\n'), ((6037, 6083), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['t1_y_test', 't1_y_pred'], {}), '(t1_y_test, t1_y_pred)\n', (6061, 6083), False, 'from sklearn import metrics\n'), ((6150, 6196), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['t2_y_test', 't2_y_pred'], {}), '(t2_y_test, t2_y_pred)\n', (6174, 6196), False, 'from sklearn import metrics\n'), ((3642, 3670), 'keras.layers.Dense', 'Dense', (['(30)'], {'activation': '"""relu"""'}), "(30, activation='relu')\n", (3647, 3670), False, 'from keras.layers import Dense\n'), ((3703, 3715), 'keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (3710, 3715), False, 'from keras.layers import Dropout\n'), ((3741, 3769), 'keras.layers.Dense', 'Dense', (['(30)'], {'activation': '"""relu"""'}), "(30, activation='relu')\n", (3746, 3769), False, 'from keras.layers import Dense\n'), ((3801, 3829), 'keras.layers.Dense', 'Dense', (['(30)'], {'activation': '"""relu"""'}), "(30, activation='relu')\n", (3806, 3829), False, 'from keras.layers import Dense\n'), ((3858, 3908), 'keras.layers.Dense', 'Dense', (['labels_train.shape[1]'], {'activation': '"""softmax"""'}), "(labels_train.shape[1], activation='softmax')\n", (3863, 3908), False, 'from keras.layers import Dense\n'), ((3961, 3989), 'keras.layers.Dense', 'Dense', (['(20)'], {'activation': '"""relu"""'}), "(20, activation='relu')\n", (3966, 3989), False, 'from keras.layers import Dense\n'), ((4022, 4034), 'keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (4029, 4034), False, 'from keras.layers import Dropout\n'), ((4060, 4088), 'keras.layers.Dense', 'Dense', (['(20)'], {'activation': '"""relu"""'}), "(20, activation='relu')\n", (4065, 4088), False, 'from keras.layers import Dense\n'), ((4120, 4148), 'keras.layers.Dense', 'Dense', (['(20)'], {'activation': '"""relu"""'}), "(20, activation='relu')\n", (4125, 4148), False, 'from keras.layers import Dense\n'), ((4177, 4227), 'keras.layers.Dense', 'Dense', (['labels_train.shape[1]'], {'activation': '"""softmax"""'}), "(labels_train.shape[1], activation='softmax')\n", (4182, 4227), False, 'from keras.layers import Dense\n'), ((4889, 4953), 'pickle.dump', 'pickle.dump', (['tokenizer', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (4900, 4953), False, 'import pickle\n'), ((1864, 1957), 'os.path.join', 'os.path.join', (['"""/content/drive/My Drive/Hate Speech Detection/Training/glove.6B.100d.txt"""'], {}), "(\n '/content/drive/My Drive/Hate Speech Detection/Training/glove.6B.100d.txt')\n", (1876, 1957), False, 'import os\n'), ((2050, 2089), 'numpy.asarray', 'np.asarray', (['values[1:]'], {'dtype': '"""float32"""'}), "(values[1:], dtype='float32')\n", (2060, 2089), True, 'import numpy as np\n'), ((4453, 4482), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)', 'clipvalue': '(1.0)'}), '(lr=0.001, clipvalue=1.0)\n', (4457, 4482), False, 'from keras.optimizers import Adam\n')]
import sys import numpy as np from tqdm import tqdm import torch from torch import nn from torch.utils.data import DataLoader, Dataset from torchvision import transforms from torchvision.datasets.folder import pil_loader from torchvision.models import resnet18, resnet34, resnet50, resnet101, densenet161 from basenet import BaseNet from .base import DistilBaseModel from .forest import ForestCV from .helpers import tiebreaking_vote from .metrics import metrics, classification_metrics, regression_metrics # -- # IO helper class PathDataset(Dataset): def __init__(self, paths, transform=None, preload=True): self.paths = paths self.preload = preload if self.preload: print("PathDataset: preloading", file=sys.stderr) self._samples = [] for p in tqdm(self.paths): self._samples.append(pil_loader(p)) self.transform = transform def __getitem__(self, idx): if not self.preload: sample = pil_loader(self.paths[idx]) else: sample = self._samples[idx] if self.transform is not None: sample = self.transform(sample) return sample, -1 def __len__(self): return self.paths.shape[0] # -- # Model class FixedCNNFeatureExtractor(BaseNet): def __init__(self, base_model, drop_last=1): super().__init__() self._model = nn.Sequential(*list(base_model.children())[:-drop_last]) def forward(self, x): x = self._model(x) while len(x.shape) > 2: x = x.mean(dim=-1).squeeze() return x class FixedCNNForest(DistilBaseModel): def __init__(self, target_metric): self.target_metric = target_metric self.is_classification = target_metric in classification_metrics self._feature_extractors = [ resnet18, resnet34, resnet50, resnet101, densenet161, ] self._y_train = None self._models = None self.transform = transforms.Compose( [ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ) def extract_features(self, fe, dataloaders, mode): model = FixedCNNFeatureExtractor(fe(pretrained=True)).to("cuda") model.verbose = True _ = model.eval() feats, _ = model.predict(dataloaders, mode=mode) del model return feats def fit(self, X_train, y_train, U_train=None): self._y_train = y_train dataloaders = { "train": DataLoader( PathDataset(paths=X_train, transform=self.transform), batch_size=32, shuffle=False, ), } self._models = [] for fe in self._feature_extractors: train_feats = self.extract_features(fe, dataloaders, mode="train") model = ForestCV(target_metric=self.target_metric) model = model.fit(train_feats, y_train) self._models.append(model) return self def predict(self, X): dataloaders = { "test": DataLoader( PathDataset(paths=X, transform=self.transform), batch_size=32, shuffle=False, ), } all_preds = [] for fe, model in zip(self._feature_extractors, self._models): test_feats = self.extract_features(fe, dataloaders, mode="test") all_preds.append(model.predict(test_feats)) if self.is_classification: ens_pred = tiebreaking_vote(np.vstack(all_preds), self._y_train) else: ens_pred = np.stack(all_preds).mean(axis=0) return ens_pred
[ "tqdm.tqdm", "numpy.stack", "numpy.vstack", "torchvision.transforms.Normalize", "torchvision.transforms.Resize", "torchvision.transforms.ToTensor", "torchvision.datasets.folder.pil_loader" ]
[((818, 834), 'tqdm.tqdm', 'tqdm', (['self.paths'], {}), '(self.paths)\n', (822, 834), False, 'from tqdm import tqdm\n'), ((1008, 1035), 'torchvision.datasets.folder.pil_loader', 'pil_loader', (['self.paths[idx]'], {}), '(self.paths[idx])\n', (1018, 1035), False, 'from torchvision.datasets.folder import pil_loader\n'), ((2110, 2139), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224, 224)'], {}), '((224, 224))\n', (2127, 2139), False, 'from torchvision import transforms\n'), ((2157, 2178), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2176, 2178), False, 'from torchvision import transforms\n'), ((2196, 2271), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (2216, 2271), False, 'from torchvision import transforms\n'), ((3777, 3797), 'numpy.vstack', 'np.vstack', (['all_preds'], {}), '(all_preds)\n', (3786, 3797), True, 'import numpy as np\n'), ((873, 886), 'torchvision.datasets.folder.pil_loader', 'pil_loader', (['p'], {}), '(p)\n', (883, 886), False, 'from torchvision.datasets.folder import pil_loader\n'), ((3851, 3870), 'numpy.stack', 'np.stack', (['all_preds'], {}), '(all_preds)\n', (3859, 3870), True, 'import numpy as np\n')]
import numpy as np import time import sys from ServoMotor import * from fns import * # Initialize motor control library & USB Port filename = "/dev/ttyUSB0" motor = ServoMotor(filename) IO = motor.IO_Init() if IO < 0: print('IO exit') sys.exit() # Call corresponding function to convert sim2real/real2sim def convFns(pos, convType): conv = [left_armpit, left_elbow, left_shoulder, right_armpit, right_elbow, right_shoulder, left_armpit, left_elbow, left_shoulder, right_armpit, right_elbow, right_shoulder] targ = np.zeros(12) for i in range(len(pos)): if i==0: targ[i] = conv[i](pos[i], convType, "front") elif i==6: targ[i] = conv[i](pos[i], convType, "back") else: targ[i] = conv[i](pos[i], convType) return targ ''' # Return target position def act_shoulders&armpits(t, a, b, c, d, e): # Calculate desired position desired_p = np.zeros(12) # Positive pos_v_shoulder = a * np.sin(t * e) + b pos_v_elbow = c * np.sin(t * e) + d pos_shoulder = [2, 11] pos_elbow = [1, 10] # Negative neg_v_shoulder = -a * np.sin(t * e) + b neg_v_elbow = -c * np.sin(t * e) + d neg_shoulder = [5, 8] neg_elbow = [4, 7] # Zero zero = [0, 3, 6, 9] # Assign desired_p[pos_shoulder] = pos_v_shoulder desired_p[pos_elbow] = pos_v_elbow desired_p[neg_shoulder] = neg_v_shoulder desired_p[neg_elbow] = neg_v_elbow desired_p[zero] = 0 # Return desired new position return convFns(desired_p, "sim2real") ''' # Front and back legs diff # Return target position def get_action(steps): # Test with w=0.21 and armpit joints don't move params = np.array([-0.1452217682136046, 0.5370238181034812, 5.453212634461867, 4.161790918008703, -1.6280157636978125, -2.764998743492415, -0.5724522688587933, 0.7226947508679249, -0.6998402793502201, 0.5072764835093281, 0.03661892351135113, 0.4627483024891589, 0.21236724167077375, 0.1380141387384276, -0.27684548026527517, -0.3643201944698517]) return act(steps, *params) def act(t, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15): # Calculate desired position desired_p = np.zeros(12) #LF desired_p[0] = 0 #p0 * np.sin(t/8*2*np.pi + p2) + p10 desired_p[1] = p6 * np.sin(t/8*2*np.pi + p2) + p12 desired_p[2] = p8 * np.sin(t/8*2*np.pi + p2) + p14 #RF desired_p[3] = 0 #p1 * np.sin(t/8*2*np.pi + p3) + p11 desired_p[4] = p7 * np.sin(t/8*2*np.pi + p3) + p13 desired_p[5] = p9 * np.sin(t/8*2*np.pi + p3) + p15 #LB desired_p[6] = 0 #p1 * np.sin(t/8*2*np.pi + p4) + p11 desired_p[7] = p7 * np.sin(t/8*2*np.pi + p4) + p13 desired_p[8] = p9 * np.sin(t/8*2*np.pi + p4) + p15 #RB desired_p[9] = 0 #p0 * np.sin(t/8*2*np.pi + p5) + p10 desired_p[10] = p6 * np.sin(t/8*2*np.pi + p5) + p12 desired_p[11] = p8 * np.sin(t/8*2*np.pi + p5) + p14 # Return desired new position return convFns(desired_p, "sim2real") # MOVE MOTOR TO GIVEN POSITION def walk(pos): h = 0 real_pos = [] for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: real_pos.append(motor.readPosition(i)) motor.move(i, int(pos[h]), 0) h+=1 time.sleep(0.005) return real_pos # Initialize motors as servos and set offset offsets = [30, 0, 64, 0, 70, 50, 26, 0, 55, 80, 90, 35] h = 0 # Set servo mode to all servos with their offset for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.setServoMode(i) if offsets[h]!=0: motor.setPositionOffset(i,offsets[h]) h+=1 # RESET position and stand down & up before walking pos = [500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500] h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.move(i, int(pos[h]), 1500) h+=1 time.sleep(3) pos = [500, 750, 583, 500, 250, 417, 500, 750, 583, 500, 250, 417] #pos = get_action(0) h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: if h>5: motor.move(i, int(pos[h]), 1000) else: motor.move(i, int(pos[h]), 1500) h+=1 time.sleep(3) # WALK while j < 300: # Get target position pos = get_action(j) print(pos) # Move robot to target position real_pos = walk(pos) j += 1 # RESET position and stand down & up before walking pos = [500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500] h = 0 for j in range(1,5): u = 10*j r = range(u, u+3) for i in r: motor.move(i, int(pos[h]), 1500) h+=1
[ "time.sleep", "numpy.array", "numpy.zeros", "sys.exit", "numpy.sin" ]
[((3600, 3613), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (3610, 3613), False, 'import time\n'), ((3868, 3881), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (3878, 3881), False, 'import time\n'), ((238, 248), 'sys.exit', 'sys.exit', ([], {}), '()\n', (246, 248), False, 'import sys\n'), ((524, 536), 'numpy.zeros', 'np.zeros', (['(12)'], {}), '(12)\n', (532, 536), True, 'import numpy as np\n'), ((1568, 1930), 'numpy.array', 'np.array', (['[-0.1452217682136046, 0.5370238181034812, 5.453212634461867, \n 4.161790918008703, -1.6280157636978125, -2.764998743492415, -\n 0.5724522688587933, 0.7226947508679249, -0.6998402793502201, \n 0.5072764835093281, 0.03661892351135113, 0.4627483024891589, \n 0.21236724167077375, 0.1380141387384276, -0.27684548026527517, -\n 0.3643201944698517]'], {}), '([-0.1452217682136046, 0.5370238181034812, 5.453212634461867, \n 4.161790918008703, -1.6280157636978125, -2.764998743492415, -\n 0.5724522688587933, 0.7226947508679249, -0.6998402793502201, \n 0.5072764835093281, 0.03661892351135113, 0.4627483024891589, \n 0.21236724167077375, 0.1380141387384276, -0.27684548026527517, -\n 0.3643201944698517])\n', (1576, 1930), True, 'import numpy as np\n'), ((2060, 2072), 'numpy.zeros', 'np.zeros', (['(12)'], {}), '(12)\n', (2068, 2072), True, 'import numpy as np\n'), ((3022, 3039), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (3032, 3039), False, 'import time\n'), ((2154, 2184), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p2)'], {}), '(t / 8 * 2 * np.pi + p2)\n', (2160, 2184), True, 'import numpy as np\n'), ((2206, 2236), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p2)'], {}), '(t / 8 * 2 * np.pi + p2)\n', (2212, 2236), True, 'import numpy as np\n'), ((2318, 2348), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p3)'], {}), '(t / 8 * 2 * np.pi + p3)\n', (2324, 2348), True, 'import numpy as np\n'), ((2370, 2400), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p3)'], {}), '(t / 8 * 2 * np.pi + p3)\n', (2376, 2400), True, 'import numpy as np\n'), ((2482, 2512), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p4)'], {}), '(t / 8 * 2 * np.pi + p4)\n', (2488, 2512), True, 'import numpy as np\n'), ((2534, 2564), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p4)'], {}), '(t / 8 * 2 * np.pi + p4)\n', (2540, 2564), True, 'import numpy as np\n'), ((2647, 2677), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p5)'], {}), '(t / 8 * 2 * np.pi + p5)\n', (2653, 2677), True, 'import numpy as np\n'), ((2700, 2730), 'numpy.sin', 'np.sin', (['(t / 8 * 2 * np.pi + p5)'], {}), '(t / 8 * 2 * np.pi + p5)\n', (2706, 2730), True, 'import numpy as np\n')]
from os.path import join,exists from os import makedirs import json from functools import reduce from typing import Optional from nibabel import load,save,Nifti1Image from numpy import ndarray,array,clip,ceil,matmul,diag,around,power,argwhere,diff,split,where,empty,append from scipy import ndimage as ndimage from sklearn.cluster import KMeans import matplotlib.pyplot as plt import matplotlib.patches as patches from skimage import measure, morphology from mpl_toolkits.mplot3d.art3d import Poly3DCollection KINDEY = 1 TUMOUR = 2 def try_case_dir(path:str,case_id:int): '''测试`case_id`的文件夹是否存在,不存在则创建它''' case_dir=join(path,"case_%05d"%case_id) if not exists(case_dir): makedirs(case_dir) def get_imaging_path(data_dir:str,case_id:int)->str: '''获得nii.gz图像文件路径 args: data_dir:str 数据集根目录 case_id:int 病例id return: path 图像文件路径 ''' return join(data_dir,"case_%05d"%case_id,"imaging.nii.gz") def get_segmentation_path(data_dir:str,case_id:int)->str: '''获得分割标注路径 args: data_dir:str 数据集根目录 case_id:int 病例id return: path 分割标注文件路径 ''' return join(data_dir,"case_%05d"%case_id,"segmentation.nii.gz") def get_imaging(data_dir:str,case_id:int)->Nifti1Image: '''获得影像对象 args: data_dir:str 数据集根目录 case_id:int 病例id return: img:Nifti1Image CT图像数据对象 ''' path=get_imaging_path(data_dir,case_id) return load(path) def get_segmentation(data_dir:str,case_id:int)->Nifti1Image: '''获得分割标注对象 args: data_dir:str 数据集根目录 case_id:int 病例id return: seg:Nifti1Image 分割标注对象 ''' path=get_segmentation_path(data_dir,case_id) return load(path) def save_imaging(data_dir:str,case_id:int,image:Nifti1Image)->None: '''保存影像对象至文件 args: data_dir:str 数据集根目录 case_id:int 病例id image:Nifti1Image 待保存对象 ''' try_case_dir(data_dir,case_id) path=get_imaging_path(data_dir,case_id) save(image,path) def save_segmentation(data_dir:str,case_id:int,segmentation:Nifti1Image)->None: '''保存分割标注对象至文件 args: data_dir:str 数据集根目录 case_id:int 病例id segmentation:Nifti1Image 待保存对象 ''' try_case_dir(data_dir,case_id) path=get_segmentation_path(data_dir,case_id) save(segmentation,path) def get_spacing(img:Nifti1Image)->ndarray: '''获取影像体素点间的体素间距 args: img:Nifti1Image return: spacing:ndarray [d,w,h] ''' return array(img.header.get_zooms()) def get_size(img:Nifti1Image)->ndarray: '''获取影像数据维度大小 args: img:Nifti1Image return: size:ndarray [d,w,h] ''' return array(img.shape) def get_data(img:Nifti1Image)->ndarray: '''获取影像数据 args: img:Nifti1Image return: data:ndarray size[d,w,h] ''' return img.get_fdata() def resample_size(size:ndarray,space_origin:ndarray,space_target:ndarray=array([3.22,1.62,1.62]))->ndarray: # 粗略估计 '''估计重采样后的影像数据大小(各维度误差不超过±1) args: size:ndarray 原始大小 space_origin 原始间距 space_target 目标间距 return: size:ndarray 重采样后的影像数据大小 ''' return ceil(space_origin/space_target*size).astype(int) def resample_arrray(np_img:ndarray,space_origin:ndarray,space_target:ndarray=array([3.22,1.62,1.62]))->ndimage: '''对影像数据进行重采样(类型为numpy.ndarray) args: np_img:ndarray 原始数组 space_origin 原始间距 space_target 目标间距 return: data:ndarray 重采样后的影像数据 ''' scales=space_origin/space_target return ndimage.interpolation.zoom(np_img,scales) def resample_image(img:Nifti1Image,space_target:ndarray=array([3.22,1.62,1.62]))->Nifti1Image: '''对影像数据进行重采样(类型为Nifti1Image) args: img:Nifti1Image 原始数组 space_target 目标间距 return: data:Nifti1Image 重采样后的影像数据 ''' aff=-diag([*space_target,-1]) aff=matmul(array([ [0,0,1,0], [0,1,0,0], [1,0,0,0], [0,0,0,1], ]),aff) scales=get_spacing(img)/space_target data=img.get_fdata() resample=ndimage.zoom(data,scales,mode="reflect") return Nifti1Image(resample,aff) def resample_segmentation(seg:Nifti1Image,space_target:ndarray=array([3.22,1.62,1.62]))->Nifti1Image: '''对分割标注数据进行重采样(类型为Nifti1Image) args: img:Nifti1Image 原始影像 space_target 目标间距 return: data:Nifti1Image 重采样后的分割标注数据 ''' aff=-diag([*space_target,-1]) aff=matmul(array([ [0,0,1,0], [0,1,0,0], [1,0,0,0], [0,0,0,1], ]),aff) scales=get_spacing(seg)/space_target data=seg.get_fdata() resample=ndimage.interpolation.zoom(data,scales,order=1,mode="reflect") resample=around(resample,0).astype(int) return Nifti1Image(resample,aff) def analyze_mean_std(img:Nifti1Image): '''分析影像体素点的均值和方差 args: img:Nifti1Image 待分析影像 return: mean:float 均值 std:float 方差 ''' data=img.get_fdata() mean=data.mean() std=data.std() return mean,std def analyze_cube(seg:Nifti1Image)->tuple: '''粗分割(前景)体素点在数组中的分布范围 args: seg:Nifti1Image 体素点标注 return: slice_tuple:tuple(slice,N) 各个维度上的范围切片对象,N为维度 ''' indexs=argwhere(seg.get_fdata()!=0) return tuple(slice(start,end+1) for start,end in zip(indexs.min(axis=0),indexs.max(axis=0))) def analyze_cubes(seg:Nifti1Image)->list: '''细分割(每种前景)体素点在数组中的分布范围 args: seg:Nifti1Image 体素点标注 return: list:list[tuple(slice,N)...] 每种前景对象在各个维度上的范围切片对象,N为维度 ''' return ndimage.find_objects(seg.get_fdata().astype(int)) def analyze_kidney_center(seg:Nifti1Image)->list: '''每个肾脏在3D图像中坐标的质心 args: seg:Nifti1Image 体素点标注 return: list:[[d,w,h],[d,w,h]] ''' indexs=argwhere(seg.get_fdata()>0) kmeans=KMeans(n_clusters=2,precompute_distances=True).fit(indexs) return array(kmeans.cluster_centers_,dtype=int) def analyze_kidney(seg:Nifti1Image,align=False)->list: '''每个肾脏在数组中的体素点分布范围 args: seg:Nifti1Image 体素点标注 align:bool 两肾选框是否对其 return: list:list[tuple(slice,N)...] 两肾在各个维度上的范围切片对象,N为维度 centers:ndarray 两肾质心坐标 ''' data=seg.get_fdata() indexs=argwhere(data>0) kmeans=KMeans(n_clusters=2,precompute_distances=True).fit(indexs) if align: ranges=[] for center in kmeans.cluster_centers_: d,w,h=center d_min,d_max=d-1,d+1 w_min,w_max=w-1,w+1 h_min,h_max=h-1,h+1 while d_min >0: if KINDEY not in data[d_min,:,:]: break d_min-=1 while w_min >0: if KINDEY not in data[:,w_min,:]: break w_min-=1 while h_min >0: if KINDEY not in data[:,:,h_min]: break h_min-=1 while d_max < data.shape[0]: if KINDEY not in data[d_max,:,:]: break d_max+=1 while w_max < data.shape[1]: if KINDEY not in data[:,w_max,:]: break w_max+=1 while h_max <data.shape[2]: if KINDEY not in data[:,:,h_max]: break h_max+=1 ranges.append((slice(d_min,d_max),slice(w_min,w_max),slice(h_min,h_max))) return ranges,array(kmeans.cluster_centers_,dtype=int) else: labels=kmeans.predict(indexs) kindey1=indexs[labels==0] kindey2=indexs[labels==1] d_min_1,w_min_1,h_min_1=kindey1.min(axis=0) d_max_1,w_max_1,h_max_1=kindey1.max(axis=0) d_min_2,w_min_2,h_min_2=kindey2.min(axis=0) d_max_2,w_max_2,h_max_2=kindey2.max(axis=0) return [ (slice(d_min_1,d_max_1),slice(w_min_1,w_max_1),slice(h_min_1,h_max_1)), (slice(d_min_2,d_max_2),slice(w_min_2,w_max_2),slice(h_min_2,h_max_2)) ],array(kmeans.cluster_centers_,dtype=int) def statistics(data_dir:str,cases:Optional[list]=None)->tuple: '''统计所有病例影像中体素点的均值、方差和总数 args: data_dir:str 数据集根目录 return: mean:float 均值 std:float 方差 count:int 体素点个数 ''' # 原始数据输出为 -527.4219503457223 299251.51932233473 17118994432 mean_all=[] size_all=[] if cases is None: cases=list(range(300)) for case_id in cases: img=get_imaging(data_dir,case_id) mean,std=analyze_mean_std(img) size=get_size(img) size=reduce(lambda x,y:x*y,size) mean_all.append(mean) size_all.append(size) count=sum(size_all) mean=sum(a*n for a,n in zip(mean_all,size_all))/count sum_std=0. for case_id in range(300): img=get_imaging(data_dir,case_id) data=img.get_fdata() part_std=power(data-mean,2)/count sum_std+=part_std.sum() std=sum_std return mean,std,count def statistics_large_memory(data_dir)->tuple: '''统计所有病例影像中体素点的均值、方差和总数(已弃用),完整运行大约需要338GB内存空间 args: data_dir:str 数据集根目录 return: mean:float 均值 std:float 方差 count:int 体素点个数 ''' # 完整运行大约需要338GB内存空间 values=empty(shape=(0,512,512),dtype=float) for case_id in range(300): img=get_imaging(path,case_id) values=append(values,img.get_fdata()) return values.mean(),values.std(),reduce(lambda x,y:x*y,values.shape) def visualization(path:str,case_id:int,resample_1_1:bool=False,clip=[-30,300]): '''以每个肾脏的质心所在位置,绘制三视图 args: case_id:int 病例id resample_1_1:bool 是否按照d:w:h=1:1:1可视化 clip:ndarray 像素值截断区间[val_min,val_max] ''' img=get_imaging(path,case_id) seg=get_segmentation(path,case_id) if resample_1_1: img=resample_image(img,array([1.62,1.62,1.62])) seg=resample_segmentation(seg,array([1.62,1.62,1.62])) kindeys,centers=analyze_kidney(seg) img_data=img.get_fdata().clip(*clip) fig=plt.subplots(figsize=(16,8)) ax=plt.subplot2grid((2,4),(0,0)) ax.imshow(img_data[:,centers[0][1],:],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[0][2].start,kindeys[0][0].start), kindeys[0][2].stop-kindeys[0][2].start, kindeys[0][0].stop-kindeys[0][0].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(0,1)) ax.imshow(img_data[:,:,centers[0][2]],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[0][1].start,kindeys[0][0].start), kindeys[0][1].stop-kindeys[0][1].start, kindeys[0][0].stop-kindeys[0][0].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(1,0)) ax.imshow(img_data[centers[0][0],:,:],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[0][2].start,kindeys[0][1].start), kindeys[0][2].stop-kindeys[0][2].start, kindeys[0][1].stop-kindeys[0][1].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(1,1),projection="3d") p=img_data[kindeys[0]] verts, faces ,_,_= measure.marching_cubes_lewiner(p) mesh = Poly3DCollection(verts[faces], alpha=0.70) face_color = [0.45, 0.45, 0.75] mesh.set_facecolor(face_color) ax.add_collection3d(mesh) ax.set_xlim(0, p.shape[0]) ax.set_ylim(0, p.shape[1]) ax.set_zlim(0, p.shape[2]) ax=plt.subplot2grid((2,4),(0,2)) ax.imshow(img_data[:,centers[1][1],:],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[1][2].start,kindeys[1][0].start), kindeys[1][2].stop-kindeys[1][2].start, kindeys[1][0].stop-kindeys[1][0].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(0,3)) ax.imshow(img_data[:,:,centers[1][2]],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[1][1].start,kindeys[1][0].start), kindeys[1][1].stop-kindeys[1][1].start, kindeys[1][0].stop-kindeys[1][0].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(1,2)) ax.imshow(img_data[centers[1][0],:,:],cmap=plt.cm.gray) ax.add_patch( patches.Rectangle( (kindeys[1][2].start,kindeys[1][1].start), kindeys[1][2].stop-kindeys[1][2].start, kindeys[1][1].stop-kindeys[1][1].start, linewidth=2,edgecolor='r',facecolor='none' ) ) ax=plt.subplot2grid((2,4),(1,3),projection="3d") p=img_data[kindeys[1]] verts, faces ,_,_= measure.marching_cubes_lewiner(p) mesh = Poly3DCollection(verts[faces], alpha=0.70) face_color = [0.45, 0.45, 0.75] mesh.set_facecolor(face_color) ax.add_collection3d(mesh) ax.set_xlim(0, p.shape[0]) ax.set_ylim(0, p.shape[1]) ax.set_zlim(0, p.shape[2]) # plt.savefig("%05d.jpg"%case_id) plt.show() def count_volume_pixel(data_dir:str,cases:list): '''统计数据集中各个不同分类像素点总数及所占比例 args: data_dir:str 数据集根目录 cases:list[int] 所选病例 return: counts:ndarray [bgs,kidneys,tumours] ratios:ndarray [bgs,kidneys,tumours] ''' count_bg=0. count_kidney=0. count_tumour=0. for case_id in cases: seg=get_segmentation(data_dir,case_id) data=get_data(seg) kidney=(data==1).sum() tumour=(data==2).sum() bg=data.size-kidney-tumour count_bg+=bg count_kidney+=kidney count_tumour+=tumour total=count_tumour+count_kidney+count_bg count=array([count_bg,count_kidney,count_tumour]) return count,count/total
[ "nibabel.load", "skimage.measure.marching_cubes_lewiner", "numpy.array", "scipy.ndimage.interpolation.zoom", "matplotlib.pyplot.subplot2grid", "scipy.ndimage.zoom", "mpl_toolkits.mplot3d.art3d.Poly3DCollection", "os.path.exists", "numpy.empty", "numpy.ceil", "nibabel.save", "functools.reduce",...
[((627, 660), 'os.path.join', 'join', (['path', "('case_%05d' % case_id)"], {}), "(path, 'case_%05d' % case_id)\n", (631, 660), False, 'from os.path import join, exists\n'), ((914, 969), 'os.path.join', 'join', (['data_dir', "('case_%05d' % case_id)", '"""imaging.nii.gz"""'], {}), "(data_dir, 'case_%05d' % case_id, 'imaging.nii.gz')\n", (918, 969), False, 'from os.path import join, exists\n'), ((1167, 1227), 'os.path.join', 'join', (['data_dir', "('case_%05d' % case_id)", '"""segmentation.nii.gz"""'], {}), "(data_dir, 'case_%05d' % case_id, 'segmentation.nii.gz')\n", (1171, 1227), False, 'from os.path import join, exists\n'), ((1473, 1483), 'nibabel.load', 'load', (['path'], {}), '(path)\n', (1477, 1483), False, 'from nibabel import load, save, Nifti1Image\n'), ((1743, 1753), 'nibabel.load', 'load', (['path'], {}), '(path)\n', (1747, 1753), False, 'from nibabel import load, save, Nifti1Image\n'), ((2034, 2051), 'nibabel.save', 'save', (['image', 'path'], {}), '(image, path)\n', (2038, 2051), False, 'from nibabel import load, save, Nifti1Image\n'), ((2357, 2381), 'nibabel.save', 'save', (['segmentation', 'path'], {}), '(segmentation, path)\n', (2361, 2381), False, 'from nibabel import load, save, Nifti1Image\n'), ((2726, 2742), 'numpy.array', 'array', (['img.shape'], {}), '(img.shape)\n', (2731, 2742), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((2986, 3011), 'numpy.array', 'array', (['[3.22, 1.62, 1.62]'], {}), '([3.22, 1.62, 1.62])\n', (2991, 3011), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((3356, 3381), 'numpy.array', 'array', (['[3.22, 1.62, 1.62]'], {}), '([3.22, 1.62, 1.62])\n', (3361, 3381), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((3626, 3668), 'scipy.ndimage.interpolation.zoom', 'ndimage.interpolation.zoom', (['np_img', 'scales'], {}), '(np_img, scales)\n', (3652, 3668), True, 'from scipy import ndimage as ndimage\n'), ((3725, 3750), 'numpy.array', 'array', (['[3.22, 1.62, 1.62]'], {}), '([3.22, 1.62, 1.62])\n', (3730, 3750), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((4148, 4190), 'scipy.ndimage.zoom', 'ndimage.zoom', (['data', 'scales'], {'mode': '"""reflect"""'}), "(data, scales, mode='reflect')\n", (4160, 4190), True, 'from scipy import ndimage as ndimage\n'), ((4200, 4226), 'nibabel.Nifti1Image', 'Nifti1Image', (['resample', 'aff'], {}), '(resample, aff)\n', (4211, 4226), False, 'from nibabel import load, save, Nifti1Image\n'), ((4290, 4315), 'numpy.array', 'array', (['[3.22, 1.62, 1.62]'], {}), '([3.22, 1.62, 1.62])\n', (4295, 4315), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((4717, 4782), 'scipy.ndimage.interpolation.zoom', 'ndimage.interpolation.zoom', (['data', 'scales'], {'order': '(1)', 'mode': '"""reflect"""'}), "(data, scales, order=1, mode='reflect')\n", (4743, 4782), True, 'from scipy import ndimage as ndimage\n'), ((4835, 4861), 'nibabel.Nifti1Image', 'Nifti1Image', (['resample', 'aff'], {}), '(resample, aff)\n', (4846, 4861), False, 'from nibabel import load, save, Nifti1Image\n'), ((5983, 6024), 'numpy.array', 'array', (['kmeans.cluster_centers_'], {'dtype': 'int'}), '(kmeans.cluster_centers_, dtype=int)\n', (5988, 6024), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((6326, 6344), 'numpy.argwhere', 'argwhere', (['(data > 0)'], {}), '(data > 0)\n', (6334, 6344), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((9335, 9374), 'numpy.empty', 'empty', ([], {'shape': '(0, 512, 512)', 'dtype': 'float'}), '(shape=(0, 512, 512), dtype=float)\n', (9340, 9374), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((10132, 10161), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(16, 8)'}), '(figsize=(16, 8))\n', (10144, 10161), True, 'import matplotlib.pyplot as plt\n'), ((10168, 10200), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(0, 0)'], {}), '((2, 4), (0, 0))\n', (10184, 10200), True, 'import matplotlib.pyplot as plt\n'), ((10540, 10572), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(0, 1)'], {}), '((2, 4), (0, 1))\n', (10556, 10572), True, 'import matplotlib.pyplot as plt\n'), ((10912, 10944), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(1, 0)'], {}), '((2, 4), (1, 0))\n', (10928, 10944), True, 'import matplotlib.pyplot as plt\n'), ((11284, 11333), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(1, 1)'], {'projection': '"""3d"""'}), "((2, 4), (1, 1), projection='3d')\n", (11300, 11333), True, 'import matplotlib.pyplot as plt\n'), ((11380, 11413), 'skimage.measure.marching_cubes_lewiner', 'measure.marching_cubes_lewiner', (['p'], {}), '(p)\n', (11410, 11413), False, 'from skimage import measure, morphology\n'), ((11425, 11466), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'Poly3DCollection', (['verts[faces]'], {'alpha': '(0.7)'}), '(verts[faces], alpha=0.7)\n', (11441, 11466), False, 'from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n'), ((11670, 11702), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(0, 2)'], {}), '((2, 4), (0, 2))\n', (11686, 11702), True, 'import matplotlib.pyplot as plt\n'), ((12042, 12074), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(0, 3)'], {}), '((2, 4), (0, 3))\n', (12058, 12074), True, 'import matplotlib.pyplot as plt\n'), ((12414, 12446), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(1, 2)'], {}), '((2, 4), (1, 2))\n', (12430, 12446), True, 'import matplotlib.pyplot as plt\n'), ((12786, 12835), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(2, 4)', '(1, 3)'], {'projection': '"""3d"""'}), "((2, 4), (1, 3), projection='3d')\n", (12802, 12835), True, 'import matplotlib.pyplot as plt\n'), ((12882, 12915), 'skimage.measure.marching_cubes_lewiner', 'measure.marching_cubes_lewiner', (['p'], {}), '(p)\n', (12912, 12915), False, 'from skimage import measure, morphology\n'), ((12927, 12968), 'mpl_toolkits.mplot3d.art3d.Poly3DCollection', 'Poly3DCollection', (['verts[faces]'], {'alpha': '(0.7)'}), '(verts[faces], alpha=0.7)\n', (12943, 12968), False, 'from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n'), ((13208, 13218), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13216, 13218), True, 'import matplotlib.pyplot as plt\n'), ((13869, 13914), 'numpy.array', 'array', (['[count_bg, count_kidney, count_tumour]'], {}), '([count_bg, count_kidney, count_tumour])\n', (13874, 13914), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((669, 685), 'os.path.exists', 'exists', (['case_dir'], {}), '(case_dir)\n', (675, 685), False, 'from os.path import join, exists\n'), ((695, 713), 'os.makedirs', 'makedirs', (['case_dir'], {}), '(case_dir)\n', (703, 713), False, 'from os import makedirs\n'), ((3933, 3958), 'numpy.diag', 'diag', (['[*space_target, -1]'], {}), '([*space_target, -1])\n', (3937, 3958), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((3973, 4036), 'numpy.array', 'array', (['[[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]'], {}), '([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])\n', (3978, 4036), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((4502, 4527), 'numpy.diag', 'diag', (['[*space_target, -1]'], {}), '([*space_target, -1])\n', (4506, 4527), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((4542, 4605), 'numpy.array', 'array', (['[[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]]'], {}), '([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])\n', (4547, 4605), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((8664, 8696), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'size'], {}), '(lambda x, y: x * y, size)\n', (8670, 8696), False, 'from functools import reduce\n'), ((9525, 9565), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 'values.shape'], {}), '(lambda x, y: x * y, values.shape)\n', (9531, 9565), False, 'from functools import reduce\n'), ((10284, 10484), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[0][2].start, kindeys[0][0].start)', '(kindeys[0][2].stop - kindeys[0][2].start)', '(kindeys[0][0].stop - kindeys[0][0].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[0][2].start, kindeys[0][0].start), kindeys[0][2]\n .stop - kindeys[0][2].start, kindeys[0][0].stop - kindeys[0][0].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (10301, 10484), True, 'import matplotlib.patches as patches\n'), ((10656, 10856), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[0][1].start, kindeys[0][0].start)', '(kindeys[0][1].stop - kindeys[0][1].start)', '(kindeys[0][0].stop - kindeys[0][0].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[0][1].start, kindeys[0][0].start), kindeys[0][1]\n .stop - kindeys[0][1].start, kindeys[0][0].stop - kindeys[0][0].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (10673, 10856), True, 'import matplotlib.patches as patches\n'), ((11028, 11228), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[0][2].start, kindeys[0][1].start)', '(kindeys[0][2].stop - kindeys[0][2].start)', '(kindeys[0][1].stop - kindeys[0][1].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[0][2].start, kindeys[0][1].start), kindeys[0][2]\n .stop - kindeys[0][2].start, kindeys[0][1].stop - kindeys[0][1].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (11045, 11228), True, 'import matplotlib.patches as patches\n'), ((11786, 11986), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[1][2].start, kindeys[1][0].start)', '(kindeys[1][2].stop - kindeys[1][2].start)', '(kindeys[1][0].stop - kindeys[1][0].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[1][2].start, kindeys[1][0].start), kindeys[1][2]\n .stop - kindeys[1][2].start, kindeys[1][0].stop - kindeys[1][0].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (11803, 11986), True, 'import matplotlib.patches as patches\n'), ((12158, 12358), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[1][1].start, kindeys[1][0].start)', '(kindeys[1][1].stop - kindeys[1][1].start)', '(kindeys[1][0].stop - kindeys[1][0].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[1][1].start, kindeys[1][0].start), kindeys[1][1]\n .stop - kindeys[1][1].start, kindeys[1][0].stop - kindeys[1][0].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (12175, 12358), True, 'import matplotlib.patches as patches\n'), ((12530, 12730), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(kindeys[1][2].start, kindeys[1][1].start)', '(kindeys[1][2].stop - kindeys[1][2].start)', '(kindeys[1][1].stop - kindeys[1][1].start)'], {'linewidth': '(2)', 'edgecolor': '"""r"""', 'facecolor': '"""none"""'}), "((kindeys[1][2].start, kindeys[1][1].start), kindeys[1][2]\n .stop - kindeys[1][2].start, kindeys[1][1].stop - kindeys[1][1].start,\n linewidth=2, edgecolor='r', facecolor='none')\n", (12547, 12730), True, 'import matplotlib.patches as patches\n'), ((3229, 3269), 'numpy.ceil', 'ceil', (['(space_origin / space_target * size)'], {}), '(space_origin / space_target * size)\n', (3233, 3269), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((4793, 4812), 'numpy.around', 'around', (['resample', '(0)'], {}), '(resample, 0)\n', (4799, 4812), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((5913, 5960), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(2)', 'precompute_distances': '(True)'}), '(n_clusters=2, precompute_distances=True)\n', (5919, 5960), False, 'from sklearn.cluster import KMeans\n'), ((6354, 6401), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(2)', 'precompute_distances': '(True)'}), '(n_clusters=2, precompute_distances=True)\n', (6360, 6401), False, 'from sklearn.cluster import KMeans\n'), ((7538, 7579), 'numpy.array', 'array', (['kmeans.cluster_centers_'], {'dtype': 'int'}), '(kmeans.cluster_centers_, dtype=int)\n', (7543, 7579), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((8099, 8140), 'numpy.array', 'array', (['kmeans.cluster_centers_'], {'dtype': 'int'}), '(kmeans.cluster_centers_, dtype=int)\n', (8104, 8140), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((8971, 8992), 'numpy.power', 'power', (['(data - mean)', '(2)'], {}), '(data - mean, 2)\n', (8976, 8992), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((9948, 9973), 'numpy.array', 'array', (['[1.62, 1.62, 1.62]'], {}), '([1.62, 1.62, 1.62])\n', (9953, 9973), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n'), ((10011, 10036), 'numpy.array', 'array', (['[1.62, 1.62, 1.62]'], {}), '([1.62, 1.62, 1.62])\n', (10016, 10036), False, 'from numpy import ndarray, array, clip, ceil, matmul, diag, around, power, argwhere, diff, split, where, empty, append\n')]
import h5py import json import os import io import torch import sys import nltk import numpy as np import pandas as pd dirname = os.path.dirname(__file__) dirname = os.path.dirname(dirname) sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data/coco/cocoapi/PythonAPI')) from pycocotools.coco import COCO from tqdm import tqdm from torch.utils.data import Dataset from utils.data_processing import Vocabulary, COCOVocabulary, text_clean from PIL import Image from collections import OrderedDict class COCOTextImageDataset(Dataset): def __init__(self, data_dir, which_set, transform, vocab_threshold=4, vocab_file=os.path.join(dirname, "data/coco/vocab.pkl"), start_word="<start>", end_word="<end>", unk_word="<unk>", annotations_file=os.path.join(dirname, "data/coco/annotations/captions_train2017.json"), vocab_from_file=True ): """ @:param datasetFile (string): path for dataset file @:param which_set (string): "train:, "valid", "test" """ if data_dir[-1] != '/': data_dir += '/' self.data_dir = data_dir self.which_set = which_set assert self.which_set in {'train', 'val', 'test'} self.vocab = COCOVocabulary(vocab_threshold, vocab_file, start_word, end_word, unk_word, annotations_file, vocab_from_file) self.transform = transform if self.which_set == 'train' or self.which_set == 'val': self.coco = COCO(os.path.join(data_dir, 'annotations/captions_{}2017.json'.format(which_set))) self.ann_ids = list(self.coco.anns.keys()) self.classes = OrderedDict() class_cnt = 0 for ann_id in self.ann_ids: img_id = self.coco.anns[ann_id]["image_id"] if img_id not in self.classes.keys(): class_cnt += 1 self.classes[img_id] = class_cnt print("Obtaining caption lengths...") all_tokens = [nltk.tokenize.word_tokenize( text_clean(str(self.coco.anns[self.ann_ids[index]]["caption"])).lower()) for index in tqdm(np.arange(len(self.ann_ids)))] self.caption_lengths = [len(token) for token in all_tokens] else: test_info = json.loads(open(os.path.join(data_dir, 'annotations/image_info_test2017')).read()) self.paths = [item["file_name"] for item in test_info["images"]] def __len__(self): return len(self.ann_ids) def __getitem__(self, index): right_ann_id = self.ann_ids[index] right_txt = self.coco.anns[right_ann_id]["caption"] right_txt = str(np.array(right_txt)) right_img_id = self.coco.anns[right_ann_id]["image_id"] right_image_path = self.coco.loadImgs(right_img_id)[0]["file_name"] class_id = self.classes[right_img_id] # TODO use DAMSM model to get embedding right_embed = [0] wrong_img_id = self.find_wrong_img_id(right_img_id) wrong_txt = str(np.array(self.find_wrond_txt(right_img_id))) wrong_image_path = self.coco.loadImgs(wrong_img_id)[0]["file_name"] # TODO use DAMSM model to get embedding wrong_embed = [0] # Processing images right_image = Image.open(os.path.join(self.data_dir + 'images/{}/'.format(self.which_set), right_image_path)) right_image = right_image.convert("RGB") wrong_image = Image.open(os.path.join(self.data_dir + 'images/{}/'.format(self.which_set), wrong_image_path)) wrong_image = wrong_image.convert("RGB") right_image_32 = right_image.resize((32, 32)) wrong_image_32 = wrong_image.resize((32, 32)) right_image_64 = right_image.resize((64, 64)) wrong_image_64 = wrong_image.resize((64, 64)) right_image_128 = right_image.resize((128, 128)) wrong_image_128 = wrong_image.resize((128, 128)) right_image_256 = right_image.resize((256, 256)) wrong_image_256 = wrong_image.resize((256, 256)) right_image_32 = self.transform(right_image_32) wrong_image_32 = self.transform(wrong_image_32) right_image_64 = self.transform(right_image_64) wrong_image_64 = self.transform(wrong_image_64) right_image_128 = self.transform(right_image_128) wrong_image_128 = self.transform(wrong_image_128) right_image_256 = self.transform(right_image_256) wrong_image_256 = self.transform(wrong_image_256) # Processing txt # Convert caption to tensor of word ids. right_txt = text_clean(right_txt) right_tokens = nltk.tokenize.word_tokenize(str(right_txt).lower()) right_caption = [] right_caption.append(self.vocab(self.vocab.start_word)) right_caption.extend(self.vocab(token) for token in right_tokens) right_caption.append(self.vocab(self.vocab.end_word)) right_caption = torch.Tensor(right_caption).long() wrong_txt = text_clean(wrong_txt) wrong_tokens = nltk.tokenize.word_tokenize(str(wrong_txt).lower()) wrong_caption = [] wrong_caption.append(self.vocab(self.vocab.start_word)) wrong_caption.extend(self.vocab(token) for token in wrong_tokens) wrong_caption.append(self.vocab(self.vocab.end_word)) wrong_caption = torch.Tensor(wrong_caption).long() sample = { 'right_img_id': right_img_id, 'right_class_id': class_id, 'right_image_32': right_image_32, 'right_image_64': right_image_64, 'right_image_128': right_image_128, 'right_image_256': right_image_256, 'right_embed': torch.FloatTensor(right_embed), 'right_caption': right_caption, 'right_txt': right_txt, 'wrong_image_32': wrong_image_32, 'wrong_image_64': wrong_image_64, 'wrong_image_128': wrong_image_128, 'wrong_image_256': wrong_image_256, 'wrong_embed': torch.FloatTensor(wrong_embed), 'wrong_caption': wrong_caption, 'wrong_txt': wrong_txt, } return sample def find_wrong_img_id(self, right_img_id): idx = np.random.randint(len(self.ann_ids)) ann_id = self.ann_ids[idx] img_id = self.coco.anns[ann_id]["image_id"] if img_id != right_img_id: return img_id return self.find_wrong_img_id(right_img_id) def find_wrond_txt(self, right_img_id): idx = np.random.randint(len(self.ann_ids)) ann_id = self.ann_ids[idx] img_id = self.coco.anns[ann_id]["image_id"] if img_id != right_img_id: txt = self.coco.anns[ann_id]["caption"] return txt return self.find_wrond_txt(right_img_id) class TextImageDataset(Dataset): def __init__(self, data_dir, dataset_name, which_set='train', transform=None, vocab_threshold=4, start_word="<start>", end_word="<end>", unk_word="<unk>", vocab_from_file=False ): """ @:param datasetFile (string): path for dataset file @:param which_set (string): "train:, "valid", "test" """ if os.path.exists(data_dir): assert dataset_name in {'birds', 'flowers'}, "wrong dataset name" self.h5_file = os.path.join(data_dir, '{}/{}.hdf5'.format(dataset_name, dataset_name)) self.data_dir = data_dir self.dataset_name = dataset_name else: raise ValueError("data directory not found") self.which_set = which_set assert self.which_set in {'train', 'valid', 'test'} self.transform = transform self.total_data = h5py.File(self.h5_file, mode='r') self.data = self.total_data[which_set] self.img_ids = [str(k) for k in self.data.keys()] if dataset_name == 'birds': # load bounding box self.bbox = self.load_bounding_box() # load class file class_file = os.path.join(data_dir, dataset_name, 'CUB_200_2011', 'classes.txt') self.classes = OrderedDict() with open(class_file, 'rb') as f: for line in f: (key, val) = line.split() self.classes[val.decode("utf-8")] = int(key) elif dataset_name == 'flowers': self.bbox = None class_file = os.path.join(data_dir, dataset_name, 'classes.txt') self.classes = OrderedDict() with open(class_file, 'rb') as f: for i, line in enumerate(f): val = line.split()[0] self.classes[val.decode("utf-8")] = i+1 self.vocab = Vocabulary( vocab_threshold=vocab_threshold, dataset_name=dataset_name, start_word=start_word, end_word=end_word, unk_word=unk_word, vocab_from_file=vocab_from_file, data_dir=data_dir) all_tokens = [nltk.tokenize.word_tokenize( text_clean(str(np.array(self.data[index]['txt']))).lower()) for index in tqdm(self.img_ids)] self.caption_lengths = [len(token) for token in all_tokens] def __len__(self): return len(self.img_ids) def __getitem__(self, index): img_id = self.img_ids[index] class_name = str(np.array(self.data[img_id]['class'])) class_id = self.classes[class_name] right_txt = str(np.array(self.data[img_id]['txt'])) wrong_txt = str(np.array(self.find_wrong_txt(self.data[img_id]['class']))) right_image_path = bytes(np.array(self.data[img_id]['img'])) right_embed = np.array(self.data[img_id]['embeddings'], dtype=float) wrong_image_path, wrong_img_id = self.find_wrong_image(self.data[img_id]['class']) wrong_image_path = bytes(np.array(wrong_image_path)) wrong_embed = np.array(self.find_wrong_embed()) # Processing images right_image = Image.open(io.BytesIO(right_image_path)).convert("RGB") wrong_image = Image.open(io.BytesIO(wrong_image_path)).convert("RGB") if self.bbox is not None: right_image_bbox = self.bbox[str(np.array(self.data[img_id]["name"]))] wrong_image_bbox = self.bbox[str(np.array(self.data[wrong_img_id]["name"]))] right_image = self.crop_image(right_image, right_image_bbox) wrong_image = self.crop_image(wrong_image, wrong_image_bbox) right_image_32 = right_image.resize((32, 32)) wrong_image_32 = wrong_image.resize((32, 32)) right_image_64 = right_image.resize((64, 64)) wrong_image_64 = wrong_image.resize((64, 64)) right_image_128 = right_image.resize((128, 128)) wrong_image_128 = wrong_image.resize((128, 128)) right_image_256 = right_image.resize((256, 256)) wrong_image_256 = wrong_image.resize((256, 256)) right_image_32 = self.transform(right_image_32) wrong_image_32 = self.transform(wrong_image_32) right_image_64 = self.transform(right_image_64) wrong_image_64 = self.transform(wrong_image_64) right_image_128 = self.transform(right_image_128) wrong_image_128 = self.transform(wrong_image_128) right_image_256 = self.transform(right_image_256) wrong_image_256 = self.transform(wrong_image_256) # Processing txt # Convert caption to tensor of word ids. right_txt = text_clean(right_txt) right_tokens = nltk.tokenize.word_tokenize(str(right_txt).lower()) right_caption = [] right_caption.append(self.vocab(self.vocab.start_word)) right_caption.extend(self.vocab(token) for token in right_tokens) right_caption.append(self.vocab(self.vocab.end_word)) right_caption = torch.Tensor(right_caption).long() wrong_txt = text_clean(wrong_txt) wrong_tokens = nltk.tokenize.word_tokenize(str(wrong_txt).lower()) wrong_caption = [] wrong_caption.append(self.vocab(self.vocab.start_word)) wrong_caption.extend(self.vocab(token) for token in wrong_tokens) wrong_caption.append(self.vocab(self.vocab.end_word)) wrong_caption = torch.Tensor(wrong_caption).long() sample = { 'right_img_id': img_id, 'right_class_id': class_id, 'right_image_32': right_image_32, 'right_image_64': right_image_64, 'right_image_128': right_image_128, 'right_image_256': right_image_256, 'right_embed': torch.FloatTensor(right_embed), 'right_caption': right_caption, 'right_txt': right_txt, 'wrong_image_32': wrong_image_32, 'wrong_image_64': wrong_image_64, 'wrong_image_128': wrong_image_128, 'wrong_image_256': wrong_image_256, 'wrong_embed': torch.FloatTensor(wrong_embed), 'wrong_caption': wrong_caption, 'wrong_txt': wrong_txt, } return sample def find_wrong_image(self, category): idx = np.random.randint(len(self.img_ids)) img_id = self.img_ids[idx] _category = self.data[img_id] if _category != category: return self.data[img_id]['img'], img_id return self.find_wrong_image(category) def find_wrong_embed(self): idx = np.random.randint(len(self.img_ids)) img_id = self.img_ids[idx] return self.data[img_id]['embeddings'] def find_wrong_txt(self, category): idx = np.random.randint(len(self.img_ids)) img_id = self.img_ids[idx] _category = self.data[img_id] if _category != category: return self.data[img_id]['txt'] return self.find_wrong_image(category) def load_bounding_box(self): bbox_path = os.path.join(self.data_dir, self.dataset_name, 'CUB_200_2011/bounding_boxes.txt') df_bounding_boxes = pd.read_csv(bbox_path, delim_whitespace=True, header=None).astype(int) # filepath = os.path.join(self.data_dir, self.dataset_name, 'CUB_200_2011/images.txt') df_filenames = \ pd.read_csv(filepath, delim_whitespace=True, header=None) filenames = df_filenames[1].tolist() # processing filenames to match data example name for i in range(len(filenames)): filename = filenames[i][:-4] filename = filename.split('/') filename = filename[1] filenames[i] = filename print('Total filenames: ', len(filenames), filenames[0]) # filename_bbox = {img_file: [] for img_file in filenames} numImgs = len(filenames) for i in range(numImgs): # bbox = [x-left, y-top, width, height] bbox = df_bounding_boxes.iloc[i][1:].tolist() key = filenames[i] filename_bbox[key] = bbox # return filename_bbox def crop_image(self, image, bbox): width, height = image.size r = int(np.maximum(bbox[2], bbox[3]) * 0.75) center_x = int((2 * bbox[0] + bbox[2]) / 2) center_y = int((2 * bbox[1] + bbox[3]) / 2) y1 = np.maximum(0, center_y - r) y2 = np.minimum(height, center_y + r) x1 = np.maximum(0, center_x - r) x2 = np.minimum(width, center_x + r) image = image.crop([x1, y1, x2, y2]) return image if __name__ == '__main__': dataset = TextImageDataset( data_dir='/Users/leon/Projects/I2T2I/data/', dataset_name='birds', which_set='train', ) sample = dataset.__getitem__(1)
[ "os.path.exists", "collections.OrderedDict", "numpy.minimum", "pandas.read_csv", "tqdm.tqdm", "os.path.join", "utils.data_processing.COCOVocabulary", "torch.Tensor", "utils.data_processing.text_clean", "h5py.File", "os.path.dirname", "utils.data_processing.Vocabulary", "numpy.array", "io.B...
[((129, 154), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (144, 154), False, 'import os\n'), ((165, 189), 'os.path.dirname', 'os.path.dirname', (['dirname'], {}), '(dirname)\n', (180, 189), False, 'import os\n'), ((728, 772), 'os.path.join', 'os.path.join', (['dirname', '"""data/coco/vocab.pkl"""'], {}), "(dirname, 'data/coco/vocab.pkl')\n", (740, 772), False, 'import os\n'), ((917, 987), 'os.path.join', 'os.path.join', (['dirname', '"""data/coco/annotations/captions_train2017.json"""'], {}), "(dirname, 'data/coco/annotations/captions_train2017.json')\n", (929, 987), False, 'import os\n'), ((1408, 1522), 'utils.data_processing.COCOVocabulary', 'COCOVocabulary', (['vocab_threshold', 'vocab_file', 'start_word', 'end_word', 'unk_word', 'annotations_file', 'vocab_from_file'], {}), '(vocab_threshold, vocab_file, start_word, end_word, unk_word,\n annotations_file, vocab_from_file)\n', (1422, 1522), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((4799, 4820), 'utils.data_processing.text_clean', 'text_clean', (['right_txt'], {}), '(right_txt)\n', (4809, 4820), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((5203, 5224), 'utils.data_processing.text_clean', 'text_clean', (['wrong_txt'], {}), '(wrong_txt)\n', (5213, 5224), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((7647, 7671), 'os.path.exists', 'os.path.exists', (['data_dir'], {}), '(data_dir)\n', (7661, 7671), False, 'import os\n'), ((8161, 8194), 'h5py.File', 'h5py.File', (['self.h5_file'], {'mode': '"""r"""'}), "(self.h5_file, mode='r')\n", (8170, 8194), False, 'import h5py\n'), ((9172, 9363), 'utils.data_processing.Vocabulary', 'Vocabulary', ([], {'vocab_threshold': 'vocab_threshold', 'dataset_name': 'dataset_name', 'start_word': 'start_word', 'end_word': 'end_word', 'unk_word': 'unk_word', 'vocab_from_file': 'vocab_from_file', 'data_dir': 'data_dir'}), '(vocab_threshold=vocab_threshold, dataset_name=dataset_name,\n start_word=start_word, end_word=end_word, unk_word=unk_word,\n vocab_from_file=vocab_from_file, data_dir=data_dir)\n', (9182, 9363), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((10172, 10226), 'numpy.array', 'np.array', (["self.data[img_id]['embeddings']"], {'dtype': 'float'}), "(self.data[img_id]['embeddings'], dtype=float)\n", (10180, 10226), True, 'import numpy as np\n'), ((11970, 11991), 'utils.data_processing.text_clean', 'text_clean', (['right_txt'], {}), '(right_txt)\n', (11980, 11991), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((12374, 12395), 'utils.data_processing.text_clean', 'text_clean', (['wrong_txt'], {}), '(wrong_txt)\n', (12384, 12395), False, 'from utils.data_processing import Vocabulary, COCOVocabulary, text_clean\n'), ((14428, 14513), 'os.path.join', 'os.path.join', (['self.data_dir', 'self.dataset_name', '"""CUB_200_2011/bounding_boxes.txt"""'], {}), "(self.data_dir, self.dataset_name,\n 'CUB_200_2011/bounding_boxes.txt')\n", (14440, 14513), False, 'import os\n'), ((14718, 14791), 'os.path.join', 'os.path.join', (['self.data_dir', 'self.dataset_name', '"""CUB_200_2011/images.txt"""'], {}), "(self.data_dir, self.dataset_name, 'CUB_200_2011/images.txt')\n", (14730, 14791), False, 'import os\n'), ((14829, 14886), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'delim_whitespace': '(True)', 'header': 'None'}), '(filepath, delim_whitespace=True, header=None)\n', (14840, 14886), True, 'import pandas as pd\n'), ((15856, 15883), 'numpy.maximum', 'np.maximum', (['(0)', '(center_y - r)'], {}), '(0, center_y - r)\n', (15866, 15883), True, 'import numpy as np\n'), ((15897, 15929), 'numpy.minimum', 'np.minimum', (['height', '(center_y + r)'], {}), '(height, center_y + r)\n', (15907, 15929), True, 'import numpy as np\n'), ((15943, 15970), 'numpy.maximum', 'np.maximum', (['(0)', '(center_x - r)'], {}), '(0, center_x - r)\n', (15953, 15970), True, 'import numpy as np\n'), ((15984, 16015), 'numpy.minimum', 'np.minimum', (['width', '(center_x + r)'], {}), '(width, center_x + r)\n', (15994, 16015), True, 'import numpy as np\n'), ((235, 260), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (250, 260), False, 'import os\n'), ((1846, 1859), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1857, 1859), False, 'from collections import OrderedDict\n'), ((2878, 2897), 'numpy.array', 'np.array', (['right_txt'], {}), '(right_txt)\n', (2886, 2897), True, 'import numpy as np\n'), ((5931, 5961), 'torch.FloatTensor', 'torch.FloatTensor', (['right_embed'], {}), '(right_embed)\n', (5948, 5961), False, 'import torch\n'), ((6286, 6316), 'torch.FloatTensor', 'torch.FloatTensor', (['wrong_embed'], {}), '(wrong_embed)\n', (6303, 6316), False, 'import torch\n'), ((8473, 8540), 'os.path.join', 'os.path.join', (['data_dir', 'dataset_name', '"""CUB_200_2011"""', '"""classes.txt"""'], {}), "(data_dir, dataset_name, 'CUB_200_2011', 'classes.txt')\n", (8485, 8540), False, 'import os\n'), ((8568, 8581), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (8579, 8581), False, 'from collections import OrderedDict\n'), ((9855, 9891), 'numpy.array', 'np.array', (["self.data[img_id]['class']"], {}), "(self.data[img_id]['class'])\n", (9863, 9891), True, 'import numpy as np\n'), ((9962, 9996), 'numpy.array', 'np.array', (["self.data[img_id]['txt']"], {}), "(self.data[img_id]['txt'])\n", (9970, 9996), True, 'import numpy as np\n'), ((10114, 10148), 'numpy.array', 'np.array', (["self.data[img_id]['img']"], {}), "(self.data[img_id]['img'])\n", (10122, 10148), True, 'import numpy as np\n'), ((10351, 10377), 'numpy.array', 'np.array', (['wrong_image_path'], {}), '(wrong_image_path)\n', (10359, 10377), True, 'import numpy as np\n'), ((13096, 13126), 'torch.FloatTensor', 'torch.FloatTensor', (['right_embed'], {}), '(right_embed)\n', (13113, 13126), False, 'import torch\n'), ((13451, 13481), 'torch.FloatTensor', 'torch.FloatTensor', (['wrong_embed'], {}), '(wrong_embed)\n', (13468, 13481), False, 'import torch\n'), ((5147, 5174), 'torch.Tensor', 'torch.Tensor', (['right_caption'], {}), '(right_caption)\n', (5159, 5174), False, 'import torch\n'), ((5551, 5578), 'torch.Tensor', 'torch.Tensor', (['wrong_caption'], {}), '(wrong_caption)\n', (5563, 5578), False, 'import torch\n'), ((8864, 8915), 'os.path.join', 'os.path.join', (['data_dir', 'dataset_name', '"""classes.txt"""'], {}), "(data_dir, dataset_name, 'classes.txt')\n", (8876, 8915), False, 'import os\n'), ((8943, 8956), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (8954, 8956), False, 'from collections import OrderedDict\n'), ((9612, 9630), 'tqdm.tqdm', 'tqdm', (['self.img_ids'], {}), '(self.img_ids)\n', (9616, 9630), False, 'from tqdm import tqdm\n'), ((12318, 12345), 'torch.Tensor', 'torch.Tensor', (['right_caption'], {}), '(right_caption)\n', (12330, 12345), False, 'import torch\n'), ((12722, 12749), 'torch.Tensor', 'torch.Tensor', (['wrong_caption'], {}), '(wrong_caption)\n', (12734, 12749), False, 'import torch\n'), ((14538, 14596), 'pandas.read_csv', 'pd.read_csv', (['bbox_path'], {'delim_whitespace': '(True)', 'header': 'None'}), '(bbox_path, delim_whitespace=True, header=None)\n', (14549, 14596), True, 'import pandas as pd\n'), ((15702, 15730), 'numpy.maximum', 'np.maximum', (['bbox[2]', 'bbox[3]'], {}), '(bbox[2], bbox[3])\n', (15712, 15730), True, 'import numpy as np\n'), ((10497, 10525), 'io.BytesIO', 'io.BytesIO', (['right_image_path'], {}), '(right_image_path)\n', (10507, 10525), False, 'import io\n'), ((10575, 10603), 'io.BytesIO', 'io.BytesIO', (['wrong_image_path'], {}), '(wrong_image_path)\n', (10585, 10603), False, 'import io\n'), ((10700, 10735), 'numpy.array', 'np.array', (["self.data[img_id]['name']"], {}), "(self.data[img_id]['name'])\n", (10708, 10735), True, 'import numpy as np\n'), ((10783, 10824), 'numpy.array', 'np.array', (["self.data[wrong_img_id]['name']"], {}), "(self.data[wrong_img_id]['name'])\n", (10791, 10824), True, 'import numpy as np\n'), ((2514, 2571), 'os.path.join', 'os.path.join', (['data_dir', '"""annotations/image_info_test2017"""'], {}), "(data_dir, 'annotations/image_info_test2017')\n", (2526, 2571), False, 'import os\n'), ((9530, 9563), 'numpy.array', 'np.array', (["self.data[index]['txt']"], {}), "(self.data[index]['txt'])\n", (9538, 9563), True, 'import numpy as np\n')]
# parser.py import io import numpy as np import pandas as pd from enum import Enum, auto import xml.etree.ElementTree as ET import xml.dom.minidom as MD from pathlib import Path from typing import Union, Optional, Any, List __all__ = ["Parser", "InFile", "OutFile"] PathOrStr = Union[Path, str] DEBUG = False class InFile(Enum): """valid DNDC input file types""" AIRCHEM = auto() CLIMATE = auto() EVENTS = auto() SITE = auto() SETUP = auto() class OutFile(Enum): """valid DNDC output file types""" # currently only soilchemistry daily allowed DAILY = auto() YEARLY = auto() class BaseParser: _fileName = None @classmethod def is_parser_for(cls, fileType: Union[InFile, OutFile]) -> bool: return fileType == cls._fileType def __init__(self, fileType: Union[InFile, OutFile]) -> None: self._data = None self._name = None self._path = None self._type = None if isinstance(fileType, InFile) or isinstance(fileType, OutFile): self._type = fileType else: print("Not a valid input type") def __repr__(self): return f'Parser: {self._type}, {self._path}\nData excerpt:\n{"" if self.data is None else repr(self.data.head())}' @property def data(self): return self._data def parse(self, inFile: Path): """parse source dndc file""" raise NotImplementedError def encode(self): """convert data to embedding vector""" raise NotImplementedError class XmlParser(BaseParser): def __init__(self, fileType: Union[InFile, OutFile]) -> None: super().__init__(fileType) def __repr__(self): pretty_xml = ( MD.parseString(ET.tostring(self.data)).toprettyxml(encoding="utf8").decode() ) # strip whitespace lines pretty_xml = "\n".join( [line for line in pretty_xml.split("\n") if line.strip() != ""][:6] ) return f'Parser: {self._type}, {self._path}\nData excerpt:\n{"" if self.data is None else pretty_xml}' class TxtParser(BaseParser): def __init__( self, fileType: Union[InFile, OutFile], inFile: Optional[PathOrStr] = None ) -> None: super().__init__(fileType) if inFile: self._path = Path(inFile) self._name = self._path.name self._parse(self._path) def _set_index_col(self, data): for dcol in ["datetime", "*"]: if dcol in data.columns.values: data["date"] = pd.to_datetime(data[dcol]).dt.date data = data.set_index("date") del data[dcol] return data def _parse( self, inFile: PathOrStr, skip_header: bool = False, daily: bool = False, vars: Optional[List[str]] = None, ) -> None: fileInMem = io.StringIO(Path(inFile).read_text()) if skip_header: for line in fileInMem: if "%data" in line: break data = pd.read_csv(fileInMem, sep="\t") data = self._set_index_col(data) if vars: data = data[vars] self._data = data self._path = Path(inFile) self._name = Path(inFile).name class AirchemParser(TxtParser): _fileType = InFile.AIRCHEM def __init__(self, inFile: Optional[PathOrStr] = None) -> None: super().__init__(self._fileType) if inFile: self.parse(inFile) def parse(self, inFile: PathOrStr, vars: Optional[List[str]] = None) -> None: self._parse(inFile, skip_header=True, vars=vars) class ClimateParser(TxtParser): _fileType = InFile.CLIMATE def __init__(self, inFile: Optional[PathOrStr] = None, **kwargs) -> None: super().__init__(self._fileType) if inFile: self.parse(inFile, **kwargs) def parse(self, inFile: PathOrStr, vars: Optional[List[str]] = None) -> None: """parse climate file (optional: selection of vars)""" self._parse(inFile, skip_header=True, daily=True, vars=vars) def encode(self, vars=None): cols = self._data.columns.values if vars: cols = [v for v in vars if v in cols] class SiteParser(XmlParser): _fileType = InFile.SITE def __init__(self, inFile: Optional[PathOrStr] = None) -> None: super().__init__(self._fileType) if inFile: self.parse(inFile) def _parse(self, inFile: PathOrStr, id: Optional[str] = None) -> None: root = ET.parse(Path(inFile)).getroot() sites = root.findall("./site") if id: for site in sites: if site.id == id: break else: site = sites[0] self._data = site.find("./soil") self._path = Path(inFile) self._name = Path(inFile).name def parse(self, inFile: PathOrStr, id: Optional[str] = None) -> None: self._parse(inFile, id=id) # --- class DailyResultsParser(TxtParser): _fileType = OutFile.DAILY def __init__(self, inFile: Optional[PathOrStr] = None, **kwargs) -> None: super().__init__(self._fileType) if inFile: self.parse(inFile, **kwargs) @property def data_nounits(self): self._data.columns = ( pd.Series(self._data.columns.values).str.replace(r"\[.*\]", "").values ) return self._data def parse( self, inFile: PathOrStr, vars: Optional[List[str]] = None, ids: Optional[List[int]] = None, ) -> None: """parse daily result file (optional: selection of vars)""" # since we want to catch multi-id files we select vars at the end and not in _parse self._parse(inFile, daily=True) if ids: ids_present = np.unique(self._data.id.values) if set(ids).issubset(set(ids_present)): self._data = self._data[self._data.id.isin(ids)] else: print(f"IDs not in file: requested: {ids}; present: {ids_present}") if vars: self._data = self._data[vars] def encode(self, vars=None): cols = self._data.columns.values if vars: cols = [v for v in vars if v in cols] # factory class Parser: """a parser factory for a set of dndc file types""" # TODO: add an option to "sense" the file by parsing the optionally provided file name parsers = [AirchemParser, ClimateParser, SiteParser, DailyResultsParser] def __new__( self, fileType: InFile, inFile: Optional[PathOrStr] = None, **kwargs ) -> InFile: matched_parsers = [r for r in self.parsers if r.is_parser_for(fileType)] if len(matched_parsers) == 1: return matched_parsers[0](inFile, **kwargs) elif len(matched_parsers) > 1: print("Multiple parsers matched. Something is very wrong here!") else: raise NotImplementedError
[ "pandas.Series", "enum.auto", "numpy.unique", "pandas.read_csv", "pathlib.Path", "xml.etree.ElementTree.tostring", "pandas.to_datetime" ]
[((391, 397), 'enum.auto', 'auto', ([], {}), '()\n', (395, 397), False, 'from enum import Enum, auto\n'), ((412, 418), 'enum.auto', 'auto', ([], {}), '()\n', (416, 418), False, 'from enum import Enum, auto\n'), ((432, 438), 'enum.auto', 'auto', ([], {}), '()\n', (436, 438), False, 'from enum import Enum, auto\n'), ((450, 456), 'enum.auto', 'auto', ([], {}), '()\n', (454, 456), False, 'from enum import Enum, auto\n'), ((469, 475), 'enum.auto', 'auto', ([], {}), '()\n', (473, 475), False, 'from enum import Enum, auto\n'), ((600, 606), 'enum.auto', 'auto', ([], {}), '()\n', (604, 606), False, 'from enum import Enum, auto\n'), ((620, 626), 'enum.auto', 'auto', ([], {}), '()\n', (624, 626), False, 'from enum import Enum, auto\n'), ((3075, 3107), 'pandas.read_csv', 'pd.read_csv', (['fileInMem'], {'sep': '"""\t"""'}), "(fileInMem, sep='\\t')\n", (3086, 3107), True, 'import pandas as pd\n'), ((3243, 3255), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (3247, 3255), False, 'from pathlib import Path\n'), ((4857, 4869), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (4861, 4869), False, 'from pathlib import Path\n'), ((2327, 2339), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (2331, 2339), False, 'from pathlib import Path\n'), ((3277, 3289), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (3281, 3289), False, 'from pathlib import Path\n'), ((4891, 4903), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (4895, 4903), False, 'from pathlib import Path\n'), ((5866, 5897), 'numpy.unique', 'np.unique', (['self._data.id.values'], {}), '(self._data.id.values)\n', (5875, 5897), True, 'import numpy as np\n'), ((2911, 2923), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (2915, 2923), False, 'from pathlib import Path\n'), ((4581, 4593), 'pathlib.Path', 'Path', (['inFile'], {}), '(inFile)\n', (4585, 4593), False, 'from pathlib import Path\n'), ((2568, 2594), 'pandas.to_datetime', 'pd.to_datetime', (['data[dcol]'], {}), '(data[dcol])\n', (2582, 2594), True, 'import pandas as pd\n'), ((5362, 5398), 'pandas.Series', 'pd.Series', (['self._data.columns.values'], {}), '(self._data.columns.values)\n', (5371, 5398), True, 'import pandas as pd\n'), ((1762, 1784), 'xml.etree.ElementTree.tostring', 'ET.tostring', (['self.data'], {}), '(self.data)\n', (1773, 1784), True, 'import xml.etree.ElementTree as ET\n')]
from case_6_hgp_model import simulate_hgp from pydex.core.designer import Designer import numpy as np designer = Designer() designer.simulate = simulate_hgp tic = designer.enumerate_candidates( bounds=[ [16, 20], [10, 200], [0.1, 10], ], levels=[ 1, 1, 5 ] ) designer.ti_controls_candidates = tic designer.sampling_times_candidates = [ np.linspace(0, 24 * 14, 14) for _ in tic ] # mp = [ # 3.1, # estimated gas in place - taken from wikipedia page of ghawar field on 2020-12-25 # 1000, # viscosity in MPa.hr - converted from 1.107x10^(-5) Pa.s # ] mp = [ 3.1, # estimated gas in place - taken from wikipedia page of ghawar field on 2020-12-25 # 1000, # viscosity in MPa.hr - converted from 1.107x10^(-5) Pa.s ] designer.model_parameters = mp designer.initialize(verbose=2) designer.design_experiment( designer.d_opt_criterion, optimizer="MOSEK", package="cvxpy", optimize_sampling_times=False, ) designer.print_optimal_candidates() designer.plot_optimal_predictions() designer.plot_optimal_sensitivities(interactive=True) designer.plot_optimal_predictions() designer.show_plots()
[ "numpy.linspace", "pydex.core.designer.Designer" ]
[((115, 125), 'pydex.core.designer.Designer', 'Designer', ([], {}), '()\n', (123, 125), False, 'from pydex.core.designer import Designer\n'), ((407, 434), 'numpy.linspace', 'np.linspace', (['(0)', '(24 * 14)', '(14)'], {}), '(0, 24 * 14, 14)\n', (418, 434), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Mon Jun 24 10:20:16 2019 @author: qde """ import unittest import numpy as np from math import sqrt,atan2, isclose from fdia_simulation.models import Radar, PeriodRadar class RadarTestCase(unittest.TestCase): def setUp(self): self.radar = Radar(x = 200, y = 200, r_std = 1., theta_std = 0.001, phi_std = 0.001) # ========================================================================== # ========================= Initialization tests =========================== def test_initial_r_std(self): self.assertEqual(self.radar.r_std,1.) def test_initial_theta_std(self): self.assertEqual(self.radar.theta_std,0.001) def test_initial_phi_std(self): self.assertEqual(self.radar.phi_std,0.001) def test_initial_position(self): self.assertEqual(self.radar.x, 200) self.assertEqual(self.radar.y, 200) self.assertEqual(self.radar.z, 0) def test_initial_step(self): dt = 0.1 DT_TRACK = 0.01 step = dt/DT_TRACK self.assertEqual(self.radar.step, step) # ========================================================================== # ========================= Initialization tests =========================== def test_get_position(self): position = [self.radar.x,self.radar.y,self.radar.z] self.assertEqual(position, self.radar.get_position()) def test_sample_position_data(self): position_data = np.array([[i,i,i] for i in range(10)]) self.radar.step = 3 sample = np.array([[0, 0, 0],[3, 3, 3],[6, 6, 6],[9, 9, 9]]) computed_sample = self.radar.sample_position_data(position_data) self.assertTrue(np.array_equal(sample,computed_sample)) def test_gen_data_1_position(self): position_data = np.array([[100. , 200., 1000.]]) x = position_data[0][0] - self.radar.x y = position_data[0][1] - self.radar.y z = position_data[0][2] - self.radar.z r = sqrt(x**2 + y**2 + z**2) theta = atan2(y,x) phi = atan2(z, sqrt(x**2 + y**2)) radar_data = [r], [theta], [phi] self.assertEqual(radar_data, self.radar.gen_data(position_data)) def test_gen_data_2_positions(self): position_data = np.array([[100. , 200., 1000.],[110.,210.,1010.]]) x1 = position_data[0][0] - self.radar.x y1 = position_data[0][1] - self.radar.y z1 = position_data[0][2] - self.radar.z r1 = sqrt(x1**2 + y1**2 + z1**2) theta1 = atan2(y1,x1) phi1 = atan2(z1, sqrt(x1**2 + y1**2)) x2 = position_data[1][0] - self.radar.x y2 = position_data[1][1] - self.radar.y z2 = position_data[1][2] - self.radar.z r2 = sqrt(x2**2 + y2**2 + z2**2) theta2 = atan2(y2,x2) phi2 = atan2(z2, sqrt(x2**2 + y2**2)) radar_data = [r1, r2], [theta1, theta2], [phi1, phi2] self.assertEqual(radar_data, self.radar.gen_data(position_data)) def test_radar2cartesian(self): pass def test_radar_pos_no_influence(self): position_data = np.array([[i,i,i] for i in range(10)]) rs,thetas,phis = self.radar.gen_data(position_data) xs, ys, zs = self.radar.radar2cartesian(rs,thetas,phis) computed_position_data = np.array(list(zip(xs,ys,zs))) print(position_data) print(computed_position_data) self.assertTrue(np.allclose(position_data,computed_position_data)) # def test_sense(self): # radar_data = np.array([[0, 0, 0],[1, 1, 1],[2, 2, 2],[3, 3, 3],[4, 4, 4], # [5, 5, 5],[6, 6, 6],[7, 7, 7],[8, 8, 8],[9, 9, 9]]) # rs = radar_data[:,0] # thetas = radar_data[:,1] # phis = radar_data[:,2] # noisy_rs, noisy_thetas, noisy_phis = self.radar.sense(rs,thetas,phis) # print(np.std(noisy_rs)) # self.assertTrue(isclose(np.std(noisy_rs),self.radar.r_std)) class PeriodRadarTestCase(RadarTestCase): def setUp(self): self.radar = PeriodRadar(x = 200, y = 200, dt = 0.1, r_std = 1., theta_std = 0.001, phi_std = 0.001, time_std = 0.001) def test_compute_meas_time(self): size = 10 computed_meas_times = self.radar.compute_meas_times(size) self.assertEqual(size, len(computed_meas_times)) # ex_time = 0 # for time in computed_meas_times: # self.assertTrue(isclose(time,ex_time,rel_tol = self.radar.time_std)) # ex_time = time + self.radar.dt def test_compute_measurements_tags(self): position_data = np.array([[0, 0, 0],[1, 1, 1],[2, 2, 2],[3, 3, 3],[4, 4, 4], [5, 5, 5],[6, 6, 6],[7, 7, 7],[8, 8, 8],[9, 9, 9]]) self.radar.tag = 0 labeled_measurements = self.radar.compute_measurements(position_data) for labeled_meas in labeled_measurements: self.assertEqual(labeled_meas.tag, self.radar.tag) if __name__ == "__main__": unittest.main()
[ "fdia_simulation.models.Radar", "numpy.allclose", "fdia_simulation.models.PeriodRadar", "math.sqrt", "numpy.array", "numpy.array_equal", "math.atan2", "unittest.main" ]
[((5218, 5233), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5231, 5233), False, 'import unittest\n'), ((310, 372), 'fdia_simulation.models.Radar', 'Radar', ([], {'x': '(200)', 'y': '(200)', 'r_std': '(1.0)', 'theta_std': '(0.001)', 'phi_std': '(0.001)'}), '(x=200, y=200, r_std=1.0, theta_std=0.001, phi_std=0.001)\n', (315, 372), False, 'from fdia_simulation.models import Radar, PeriodRadar\n'), ((1619, 1673), 'numpy.array', 'np.array', (['[[0, 0, 0], [3, 3, 3], [6, 6, 6], [9, 9, 9]]'], {}), '([[0, 0, 0], [3, 3, 3], [6, 6, 6], [9, 9, 9]])\n', (1627, 1673), True, 'import numpy as np\n'), ((1873, 1907), 'numpy.array', 'np.array', (['[[100.0, 200.0, 1000.0]]'], {}), '([[100.0, 200.0, 1000.0]])\n', (1881, 1907), True, 'import numpy as np\n'), ((2063, 2093), 'math.sqrt', 'sqrt', (['(x ** 2 + y ** 2 + z ** 2)'], {}), '(x ** 2 + y ** 2 + z ** 2)\n', (2067, 2093), False, 'from math import sqrt, atan2, isclose\n'), ((2104, 2115), 'math.atan2', 'atan2', (['y', 'x'], {}), '(y, x)\n', (2109, 2115), False, 'from math import sqrt, atan2, isclose\n'), ((2339, 2397), 'numpy.array', 'np.array', (['[[100.0, 200.0, 1000.0], [110.0, 210.0, 1010.0]]'], {}), '([[100.0, 200.0, 1000.0], [110.0, 210.0, 1010.0]])\n', (2347, 2397), True, 'import numpy as np\n'), ((2551, 2584), 'math.sqrt', 'sqrt', (['(x1 ** 2 + y1 ** 2 + z1 ** 2)'], {}), '(x1 ** 2 + y1 ** 2 + z1 ** 2)\n', (2555, 2584), False, 'from math import sqrt, atan2, isclose\n'), ((2596, 2609), 'math.atan2', 'atan2', (['y1', 'x1'], {}), '(y1, x1)\n', (2601, 2609), False, 'from math import sqrt, atan2, isclose\n'), ((2819, 2852), 'math.sqrt', 'sqrt', (['(x2 ** 2 + y2 ** 2 + z2 ** 2)'], {}), '(x2 ** 2 + y2 ** 2 + z2 ** 2)\n', (2823, 2852), False, 'from math import sqrt, atan2, isclose\n'), ((2864, 2877), 'math.atan2', 'atan2', (['y2', 'x2'], {}), '(y2, x2)\n', (2869, 2877), False, 'from math import sqrt, atan2, isclose\n'), ((4121, 4217), 'fdia_simulation.models.PeriodRadar', 'PeriodRadar', ([], {'x': '(200)', 'y': '(200)', 'dt': '(0.1)', 'r_std': '(1.0)', 'theta_std': '(0.001)', 'phi_std': '(0.001)', 'time_std': '(0.001)'}), '(x=200, y=200, dt=0.1, r_std=1.0, theta_std=0.001, phi_std=0.001,\n time_std=0.001)\n', (4132, 4217), False, 'from fdia_simulation.models import Radar, PeriodRadar\n'), ((4816, 4940), 'numpy.array', 'np.array', (['[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6\n ], [7, 7, 7], [8, 8, 8], [9, 9, 9]]'], {}), '([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5],\n [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]])\n', (4824, 4940), True, 'import numpy as np\n'), ((1768, 1807), 'numpy.array_equal', 'np.array_equal', (['sample', 'computed_sample'], {}), '(sample, computed_sample)\n', (1782, 1807), True, 'import numpy as np\n'), ((2140, 2161), 'math.sqrt', 'sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (2144, 2161), False, 'from math import sqrt, atan2, isclose\n'), ((2636, 2659), 'math.sqrt', 'sqrt', (['(x1 ** 2 + y1 ** 2)'], {}), '(x1 ** 2 + y1 ** 2)\n', (2640, 2659), False, 'from math import sqrt, atan2, isclose\n'), ((2904, 2927), 'math.sqrt', 'sqrt', (['(x2 ** 2 + y2 ** 2)'], {}), '(x2 ** 2 + y2 ** 2)\n', (2908, 2927), False, 'from math import sqrt, atan2, isclose\n'), ((3496, 3546), 'numpy.allclose', 'np.allclose', (['position_data', 'computed_position_data'], {}), '(position_data, computed_position_data)\n', (3507, 3546), True, 'import numpy as np\n')]
"""ASPP block.""" import tensorflow as tf import numpy as np LAYERS = tf.keras.layers L2 = tf.keras.regularizers.l2 def sep_conv_bn_relu(inputs, filters=256, kernel_size=3, strides=1, dilation_rate=1, weight_decay=1e-5, batch_normalization=False, name="sepconv_bn"): """An separable convolution with batch_normalization and relu activation after depthwise and pointwise convolutions""" with tf.name_scope(name): result = LAYERS.DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding='same', depth_multiplier=1, use_bias=False, depthwise_regularizer=L2(weight_decay), dilation_rate=dilation_rate)(inputs) if batch_normalization: result = LAYERS.BatchNormalization()(result) result = LAYERS.Activation('relu')(result) result = LAYERS.Conv2D(filters=filters, kernel_size=1, use_bias=False, kernel_regularizer=L2(weight_decay))(result) if batch_normalization: result = LAYERS.BatchNormalization()(result) result = LAYERS.Activation('relu')(result) return result def aspp(inputs, input_shape, weight_decay=1e-5, batch_normalization=False): """the DeepLabv3 ASPP module""" output_stride = 32 # Employ a 1x1 convolution. aspp_1x1 = LAYERS.Conv2D(filters=256, kernel_size=1, padding='same', use_bias=False, kernel_regularizer=L2(weight_decay), name='aspp/1x1/con2d')(inputs) if batch_normalization: aspp_1x1 = LAYERS.BatchNormalization(name='aspp/1x1/bn', epsilon=1e-5)(aspp_1x1) aspp_1x1 = LAYERS.Activation('relu', name='aspp/1x1/relu')(aspp_1x1) # Employ 3x3 convolutions with atrous rate = 6 aspp_3x3_r6 = sep_conv_bn_relu(inputs=inputs, filters=256, kernel_size=3, strides=1, dilation_rate=6, weight_decay=weight_decay, batch_normalization=batch_normalization, name='aspp/3x3_r6') # Employ 3x3 convolutions with atrous rate = 12 aspp_3x3_r12 = sep_conv_bn_relu(inputs=inputs, filters=256, kernel_size=3, strides=1, dilation_rate=12, weight_decay=weight_decay, batch_normalization=batch_normalization, name='aspp/3x3_r12') # Employ 3x3 convolutions with atrous rate = 18 aspp_3x3_r18 = sep_conv_bn_relu(inputs=inputs, filters=256, kernel_size=3, strides=1, dilation_rate=18, weight_decay=weight_decay, batch_normalization=batch_normalization, name='aspp/3x3_r18') # Image Feature branch pool_height = int(np.ceil(input_shape[0] / output_stride)) pool_width = int(np.ceil(input_shape[1] / output_stride)) aspp_image_features = LAYERS.AveragePooling2D( pool_size=[pool_height, pool_width], name='aspp/image_features/average_pooling')(inputs) aspp_image_features = LAYERS.Conv2D( filters=256, kernel_size=1, padding='same', use_bias=False, kernel_regularizer=L2(weight_decay), name='aspp/image_features/conv2d')(aspp_image_features) if batch_normalization: aspp_image_features = LAYERS.BatchNormalization( name='aspp/image_features/image_pooling_BN', epsilon=1e-5)(aspp_image_features) aspp_image_features = LAYERS.Activation( 'relu', name='aspp/image_features/relu')(aspp_image_features) aspp_image_features = LAYERS.UpSampling2D( (pool_height, pool_width), name='aspp/image_features/up_sampling')(aspp_image_features) # concatenate ASPP branches & project result = LAYERS.Concatenate(name='aspp/concat')([ aspp_1x1, aspp_3x3_r6, aspp_3x3_r12, aspp_3x3_r18, aspp_image_features ]) result = LAYERS.Conv2D(filters=256, kernel_size=1, name='aspp/conv_1x1', kernel_regularizer=L2(weight_decay))(result) result = LAYERS.Dropout(rate=0.9, name='aspp/dropout')(result) return result
[ "numpy.ceil", "tensorflow.name_scope" ]
[((555, 574), 'tensorflow.name_scope', 'tf.name_scope', (['name'], {}), '(name)\n', (568, 574), True, 'import tensorflow as tf\n'), ((3799, 3838), 'numpy.ceil', 'np.ceil', (['(input_shape[0] / output_stride)'], {}), '(input_shape[0] / output_stride)\n', (3806, 3838), True, 'import numpy as np\n'), ((3861, 3900), 'numpy.ceil', 'np.ceil', (['(input_shape[1] / output_stride)'], {}), '(input_shape[1] / output_stride)\n', (3868, 3900), True, 'import numpy as np\n')]
from sys import stderr, path path.append('.') import time import numpy as np import pandas as pd import requests as req import xmltodict from pprint import pprint from google.protobuf.json_format import MessageToDict from math import radians, pi from numpy.random import beta, randint, uniform import pygeotile.tile import generator.proto.vector_tile_pb2 REQ_CODES = req.status_codes._codes API_KEY_PATH = "generator/.tomtomkey" API_KEY = open(API_KEY_PATH).read().strip() API_ROOT = "api.tomtom.com" DECAY_PERIOD = 15*1_000 # seconds DECAY_PERIOD /= 5 DECAY_LIMIT = 0.25 def latlon2tile(lat, lon, zoom): x, y = pygeotile.tile.Tile.for_latitude_longitude(lat, lon, zoom).google return int(x), int(y) def coord2tile(coord, zoom): return latlon2tile(coord["lat"], coord["lon"], zoom) def xml(response): return xmltodict.parse(response.text) def json(response): return response.json() def pbf(Message, response): msg = Message() msg.ParseFromString(response.content) return msg def tomtom_url(path, args): url = f"https://{API_ROOT}/{path}" arg_str = "&".join([f"{k}={v}" for k, v in args.items()]) if arg_str: url += "?" + arg_str return url def tomtom(path, debug=True, **args): args_ = args.copy() args_["key"] = API_KEY url = tomtom_url(path, args_) res = req.get(url) url_safe = tomtom_url(path, args) if debug: print(f"GET {url_safe}", file=stderr) if not res: code = str(res.status_code) if code in REQ_CODES: code += f" ({REQ_CODES[code][0]})" print(f"ERR {code} -- {url_safe}", file=stderr) return None return res COLS = [] def init_state(): lat, lon = 52.52343, 13.41144 # berlin X = pd.read_csv('res/berlin-parking.csv', index_col=0) N = len(X) #X["lat"] = 0.3 * (beta(3, 3, size=N) - 0.5) + lat #X["lon"] = 0.6 * (beta(3, 3, size=N) - 0.5) + lon X["decay"] = beta(3, 2, size=N) X.loc[X.decay < DECAY_LIMIT, 'decay'] = 0 X["parked"] = X.decay >= DECAY_LIMIT X["last_seen"] = time.time() X["time_parked"] = 0 # cheats global COLS COLS = ['parked', 'decay', 'last_seen', 'time_parked'] COLS = [X.columns.get_loc(c) for c in COLS if c in X] return X def next_state(X): # advance decay of parked cars to t parked = X.parked == True t = time.time() - X.loc[parked, 'time_parked'] X.loc[parked, 'decay'] = np.e**(-t/DECAY_PERIOD) # mark timed out slots as free timeout = X.decay < DECAY_LIMIT X.loc[timeout, ['decay', 'parked', 'time_parked']] = 0 X.loc[timeout, 'parked'] = False # park random cars R = X[X.parked == False].sample(frac=0.05) # amount of cars chances = uniform(0, 1, len(R)) R = R[chances <= 0.3] # probability of parking X = did_park(X, R.index) return X def did_park(X, indices): t = time.time() X.iloc[indices, COLS] = (True, 1, t, t) return X if __name__ == "__main__": S = init_state() S.to_csv('res/parking.csv')
[ "numpy.random.beta", "xmltodict.parse", "pandas.read_csv", "requests.get", "time.time", "sys.path.append" ]
[((29, 45), 'sys.path.append', 'path.append', (['"""."""'], {}), "('.')\n", (40, 45), False, 'from sys import stderr, path\n'), ((832, 862), 'xmltodict.parse', 'xmltodict.parse', (['response.text'], {}), '(response.text)\n', (847, 862), False, 'import xmltodict\n'), ((1345, 1357), 'requests.get', 'req.get', (['url'], {}), '(url)\n', (1352, 1357), True, 'import requests as req\n'), ((1757, 1807), 'pandas.read_csv', 'pd.read_csv', (['"""res/berlin-parking.csv"""'], {'index_col': '(0)'}), "('res/berlin-parking.csv', index_col=0)\n", (1768, 1807), True, 'import pandas as pd\n'), ((1950, 1968), 'numpy.random.beta', 'beta', (['(3)', '(2)'], {'size': 'N'}), '(3, 2, size=N)\n', (1954, 1968), False, 'from numpy.random import beta, randint, uniform\n'), ((2077, 2088), 'time.time', 'time.time', ([], {}), '()\n', (2086, 2088), False, 'import time\n'), ((2887, 2898), 'time.time', 'time.time', ([], {}), '()\n', (2896, 2898), False, 'import time\n'), ((2372, 2383), 'time.time', 'time.time', ([], {}), '()\n', (2381, 2383), False, 'import time\n')]
""" Translation ================================================================= In this example, a Gaussian stochastic processes is translated into a stochastic processes of a number of distributions. This example illustrates how to use the :class:`.Correlate` class to translate from Gaussian to other probability distributions and compare how the statistics of the translated stochastic processes change along with distributions. """ # %% md # # Import the necessary libraries. Here we import standard libraries such as numpy and matplotlib, but also need to # import the class:`.Correlate` class from the :py:mod:`stochastic_processes` module of UQpy. # %% from UQpy.stochastic_process import Translation, SpectralRepresentation import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn') # %% md # # Firstly we generate Gaussian Stochastic Processes using the Spectral Representation Method. # %% n_sim = 10000 # Num of samples T = 100 # Time(1 / T = dw) nt = 256 # Num.of Discretized Time F = 1 / T * nt / 2 # Frequency.(Hz) nw = 128 # Num of Discretized Freq. dt = T / nt t = np.linspace(0, T - dt, nt) dw = F / nw w = np.linspace(0, F - dw, nw) S = 125 * w ** 2 * np.exp(-2 * w) SRM_object = SpectralRepresentation(n_sim, S, dt, dw, nt, nw, random_state=128) samples = SRM_object.samples def S_to_R(S, w, t): dw = w[1] - w[0] fac = np.ones(len(w)) fac[1: len(w) - 1: 2] = 4 fac[2: len(w) - 2: 2] = 2 fac = fac * dw / 3 R = np.zeros(len(t)) for i in range(len(t)): R[i] = 2 * np.dot(fac, S * np.cos(w * t[i])) return R R_g = S_to_R(S, w, t) r_g = R_g / R_g[0] # %% md # # We translate the samples to be Uniform samples from :math:`1` to :math:`2` # %% from UQpy.distributions import Lognormal distribution = Lognormal(0.5) samples = samples.flatten()[:, np.newaxis] Translate_object = Translation(distributions=distribution, time_interval=dt, frequency_interval=dw, n_time_intervals=nt, n_frequency_intervals=nw, correlation_function_gaussian=R_g, samples_gaussian=samples) samples_ng = Translate_object.samples_non_gaussian R_ng = Translate_object.scaled_correlation_function_non_gaussian r_ng = Translate_object.correlation_function_non_gaussian # %% md # # Plotting the actual and translated autocorrelation functions # %% fig1 = plt.figure() plt.plot(r_g, label='Gaussian') plt.plot(r_ng, label='non-Gaussian') plt.title('Correlation Function (r)') plt.legend() plt.show()
[ "UQpy.distributions.Lognormal", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.style.use", "numpy.exp", "numpy.linspace", "matplotlib.pyplot.figure", "numpy.cos", "matplotlib.pyplot.title", "UQpy.stochastic_process.Translation", "matplotlib.pyplot.legend", "UQpy.stochas...
[((792, 816), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (805, 816), True, 'import matplotlib.pyplot as plt\n'), ((1115, 1141), 'numpy.linspace', 'np.linspace', (['(0)', '(T - dt)', 'nt'], {}), '(0, T - dt, nt)\n', (1126, 1141), True, 'import numpy as np\n'), ((1158, 1184), 'numpy.linspace', 'np.linspace', (['(0)', '(F - dw)', 'nw'], {}), '(0, F - dw, nw)\n', (1169, 1184), True, 'import numpy as np\n'), ((1233, 1299), 'UQpy.stochastic_process.SpectralRepresentation', 'SpectralRepresentation', (['n_sim', 'S', 'dt', 'dw', 'nt', 'nw'], {'random_state': '(128)'}), '(n_sim, S, dt, dw, nt, nw, random_state=128)\n', (1255, 1299), False, 'from UQpy.stochastic_process import Translation, SpectralRepresentation\n'), ((1796, 1810), 'UQpy.distributions.Lognormal', 'Lognormal', (['(0.5)'], {}), '(0.5)\n', (1805, 1810), False, 'from UQpy.distributions import Lognormal\n'), ((1874, 2070), 'UQpy.stochastic_process.Translation', 'Translation', ([], {'distributions': 'distribution', 'time_interval': 'dt', 'frequency_interval': 'dw', 'n_time_intervals': 'nt', 'n_frequency_intervals': 'nw', 'correlation_function_gaussian': 'R_g', 'samples_gaussian': 'samples'}), '(distributions=distribution, time_interval=dt,\n frequency_interval=dw, n_time_intervals=nt, n_frequency_intervals=nw,\n correlation_function_gaussian=R_g, samples_gaussian=samples)\n', (1885, 2070), False, 'from UQpy.stochastic_process import Translation, SpectralRepresentation\n'), ((2388, 2400), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2398, 2400), True, 'import matplotlib.pyplot as plt\n'), ((2401, 2432), 'matplotlib.pyplot.plot', 'plt.plot', (['r_g'], {'label': '"""Gaussian"""'}), "(r_g, label='Gaussian')\n", (2409, 2432), True, 'import matplotlib.pyplot as plt\n'), ((2433, 2469), 'matplotlib.pyplot.plot', 'plt.plot', (['r_ng'], {'label': '"""non-Gaussian"""'}), "(r_ng, label='non-Gaussian')\n", (2441, 2469), True, 'import matplotlib.pyplot as plt\n'), ((2470, 2507), 'matplotlib.pyplot.title', 'plt.title', (['"""Correlation Function (r)"""'], {}), "('Correlation Function (r)')\n", (2479, 2507), True, 'import matplotlib.pyplot as plt\n'), ((2508, 2520), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2518, 2520), True, 'import matplotlib.pyplot as plt\n'), ((2521, 2531), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2529, 2531), True, 'import matplotlib.pyplot as plt\n'), ((1204, 1218), 'numpy.exp', 'np.exp', (['(-2 * w)'], {}), '(-2 * w)\n', (1210, 1218), True, 'import numpy as np\n'), ((1570, 1586), 'numpy.cos', 'np.cos', (['(w * t[i])'], {}), '(w * t[i])\n', (1576, 1586), True, 'import numpy as np\n')]
import os import logging logger = logging.getLogger(__name__) import numpy as np import astropy.io.fits as fits import matplotlib.pyplot as plt from ...echelle.imageproc import combine_images from ...echelle.trace import find_apertures, load_aperture_set from .common import (get_bias, get_mask, correct_overscan, fix_badpixels, TraceFigure, BackgroundFigure, ) def reduce_feros(config, logtable): """Reduce the single fiber data of FEROS. Args: config (:class:`configparser.ConfigParser`): Config object. logtable (:class:`astropy.table.Table`): Table of observing log. """ # extract keywords from config file section = config['data'] rawpath = section.get('rawpath') statime_key = section.get('statime_key') exptime_key = section.get('exptime_key') direction = section.get('direction') section = config['reduce'] midpath = section.get('midpath') odspath = section.get('odspath') figpath = section.get('figpath') mode = section.get('mode') fig_format = section.get('fig_format') oned_suffix = section.get('oned_suffix') ncores = section.get('ncores') # create folders if not exist if not os.path.exists(figpath): os.mkdir(figpath) if not os.path.exists(odspath): os.mkdir(odspath) if not os.path.exists(midpath): os.mkdir(midpath) # determine number of cores to be used if ncores == 'max': ncores = os.cpu_count() else: ncores = min(os.cpu_count(), int(ncores)) ################ parse bias ######################## bias, bias_card_lst = get_bias(config, logtable) ############### find flat groups ################## # initialize flat_groups for single fiber flat_groups = {} # flat_groups = {'flat_M': [fileid1, fileid2, ...], # 'flat_N': [fileid1, fileid2, ...]} for logitem in logtable: if logitem['object']=='FLAT' and logitem['binning']=='(1, 1)': # find a proper name for this flat flatname = '{:g}'.format(logitem['exptime']) # add flatname to flat_groups if flatname not in flat_groups: flat_groups[flatname] = [] flat_groups[flatname].append(logitem) ################# Combine the flats and trace the orders ################### # first combine the flats for flatname, logitem_lst in flat_groups.items(): nflat = len(logitem_lst) # number of flat fieldings flat_filename = os.path.join(midpath, 'flat_{}.fits'.format(flatname)) aperset_filename = os.path.join(midpath, 'trace_flat_{}.trc'.format(flatname)) aperset_regname = os.path.join(midpath, 'trace_flat_{}.reg'.format(flatname)) trace_figname = os.path.join(figpath, 'trace_flat_{}.{}'.format(flatname, fig_format)) # get flat_data and mask_array if mode=='debug' and os.path.exists(flat_filename) \ and os.path.exists(aperset_filename): pass else: # if the above conditions are not satisfied, comine each flat data_lst = [] head_lst = [] exptime_lst = [] print('* Combine {} Flat Images: {}'.format(nflat, flat_filename)) fmt_str = ' - {:>7s} {:^23} {:^8s} {:^7} {:^8} {:^6}' head_str = fmt_str.format('frameid', 'FileID', 'Object', 'exptime', 'N(sat)', 'Q95') for iframe, logitem in enumerate(logitem_lst): # read each individual flat frame fname = 'FEROS.{}.fits'.format(logitem['fileid']) filename = os.path.join(rawpath, fname) data, head = fits.getdata(filename, header=True) exptime_lst.append(head[exptime_key]) mask = get_mask(data, head) sat_mask = (mask&4>0) bad_mask = (mask&2>0) if iframe == 0: allmask = np.zeros_like(mask, dtype=np.int16) allmask += sat_mask # correct overscan for flat data, card_lst = correct_overscan(data, head) for key, value in card_lst: head.append((key, value)) # correct bias for flat, if has bias if bias is None: message = 'No bias. skipped bias correction' else: data = data - bias message = 'Bias corrected' logger.info(message) # print info if iframe == 0: print(head_str) message = fmt_str.format( '[{:d}]'.format(logitem['frameid']), logitem['fileid'], logitem['object'], logitem['exptime'], logitem['nsat'], logitem['q95']) print(message) data_lst.append(data) if nflat == 1: flat_data = data_lst[0] else: data_lst = np.array(data_lst) flat_data = combine_images(data_lst, mode = 'mean', upper_clip = 10, maxiter = 5, maskmode = (None, 'max')[nflat>3], ncores = ncores, ) fig = plt.figure(dpi=300) ax = fig.gca() ax.plot(flat_data[2166, 0:400],lw=0.5, color='C0') # fix badpixels in flat flat_data = fix_badpixels(flat_data, bad_mask) ax.plot(flat_data[2166, 0:400],lw=0.5, color='C1') plt.show() # get mean exposure time and write it to header head = fits.Header() exptime = np.array(exptime_lst).mean() head[exptime_key] = exptime # find saturation mask sat_mask = allmask > nflat/2. flat_mask = np.int16(sat_mask)*4 + np.int16(bad_mask)*2 # get exposure time normalized flats flat_norm = flat_data/exptime # create the trace figure tracefig = TraceFigure() section = config['reduce.trace'] aperset = find_apertures(flat_data, flat_mask, transpose = True, scan_step = section.getint('scan_step'), minimum = section.getfloat('minimum'), separation = section.get('separation'), align_deg = section.getint('align_deg'), filling = section.getfloat('filling'), degree = section.getint('degree'), conv_core = 20, display = section.getboolean('display'), fig = tracefig, ) # save the trace figure tracefig.adjust_positions() title = 'Trace for {}'.format(flat_filename) tracefig.suptitle(title, fontsize=15) tracefig.savefig(trace_figname) aperset.save_txt(aperset_filename) aperset.save_reg(aperset_regname) # do the flat fielding # prepare the output mid-prococess figures in debug mode if mode=='debug': figname = 'flat_aperpar_{}_%03d.{}'.format( flatname, fig_format) fig_aperpar = os.path.join(figpath, figname) else: fig_aperpar = None # prepare the name for slit figure figname = 'slit_flat_{}.{}'.format(flatname, fig_format) fig_slit = os.path.join(figpath, figname) # prepare the name for slit file fname = 'slit_flat_{}.dat'.format(flatname) slit_file = os.path.join(midpath, fname) #section = config['reduce.flat'] # pack results and save to fits hdu_lst = fits.HDUList([ fits.PrimaryHDU(flat_data, head), fits.ImageHDU(flat_mask), fits.ImageHDU(flat_norm), #fits.ImageHDU(flat_sens), #fits.BinTableHDU(flat_spec), ]) hdu_lst.writeto(flat_filename, overwrite=True) # now flt_data and mask_array are prepared
[ "logging.getLogger", "os.path.exists", "astropy.io.fits.PrimaryHDU", "astropy.io.fits.ImageHDU", "numpy.int16", "os.path.join", "numpy.array", "matplotlib.pyplot.figure", "astropy.io.fits.getdata", "os.mkdir", "os.cpu_count", "astropy.io.fits.Header", "numpy.zeros_like", "matplotlib.pyplot...
[((34, 61), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (51, 61), False, 'import logging\n'), ((1292, 1315), 'os.path.exists', 'os.path.exists', (['figpath'], {}), '(figpath)\n', (1306, 1315), False, 'import os\n'), ((1317, 1334), 'os.mkdir', 'os.mkdir', (['figpath'], {}), '(figpath)\n', (1325, 1334), False, 'import os\n'), ((1346, 1369), 'os.path.exists', 'os.path.exists', (['odspath'], {}), '(odspath)\n', (1360, 1369), False, 'import os\n'), ((1371, 1388), 'os.mkdir', 'os.mkdir', (['odspath'], {}), '(odspath)\n', (1379, 1388), False, 'import os\n'), ((1400, 1423), 'os.path.exists', 'os.path.exists', (['midpath'], {}), '(midpath)\n', (1414, 1423), False, 'import os\n'), ((1425, 1442), 'os.mkdir', 'os.mkdir', (['midpath'], {}), '(midpath)\n', (1433, 1442), False, 'import os\n'), ((1528, 1542), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (1540, 1542), False, 'import os\n'), ((1574, 1588), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (1586, 1588), False, 'import os\n'), ((3100, 3129), 'os.path.exists', 'os.path.exists', (['flat_filename'], {}), '(flat_filename)\n', (3114, 3129), False, 'import os\n'), ((3148, 3180), 'os.path.exists', 'os.path.exists', (['aperset_filename'], {}), '(aperset_filename)\n', (3162, 3180), False, 'import os\n'), ((5694, 5713), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'dpi': '(300)'}), '(dpi=300)\n', (5704, 5713), True, 'import matplotlib.pyplot as plt\n'), ((5974, 5984), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5982, 5984), True, 'import matplotlib.pyplot as plt\n'), ((6065, 6078), 'astropy.io.fits.Header', 'fits.Header', ([], {}), '()\n', (6076, 6078), True, 'import astropy.io.fits as fits\n'), ((8026, 8056), 'os.path.join', 'os.path.join', (['figpath', 'figname'], {}), '(figpath, figname)\n', (8038, 8056), False, 'import os\n'), ((8183, 8211), 'os.path.join', 'os.path.join', (['midpath', 'fname'], {}), '(midpath, fname)\n', (8195, 8211), False, 'import os\n'), ((3839, 3867), 'os.path.join', 'os.path.join', (['rawpath', 'fname'], {}), '(rawpath, fname)\n', (3851, 3867), False, 'import os\n'), ((3897, 3932), 'astropy.io.fits.getdata', 'fits.getdata', (['filename'], {'header': '(True)'}), '(filename, header=True)\n', (3909, 3932), True, 'import astropy.io.fits as fits\n'), ((5298, 5316), 'numpy.array', 'np.array', (['data_lst'], {}), '(data_lst)\n', (5306, 5316), True, 'import numpy as np\n'), ((7802, 7832), 'os.path.join', 'os.path.join', (['figpath', 'figname'], {}), '(figpath, figname)\n', (7814, 7832), False, 'import os\n'), ((4169, 4204), 'numpy.zeros_like', 'np.zeros_like', (['mask'], {'dtype': 'np.int16'}), '(mask, dtype=np.int16)\n', (4182, 4204), True, 'import numpy as np\n'), ((6101, 6122), 'numpy.array', 'np.array', (['exptime_lst'], {}), '(exptime_lst)\n', (6109, 6122), True, 'import numpy as np\n'), ((6272, 6290), 'numpy.int16', 'np.int16', (['sat_mask'], {}), '(sat_mask)\n', (6280, 6290), True, 'import numpy as np\n'), ((6295, 6313), 'numpy.int16', 'np.int16', (['bad_mask'], {}), '(bad_mask)\n', (6303, 6313), True, 'import numpy as np\n'), ((8367, 8399), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', (['flat_data', 'head'], {}), '(flat_data, head)\n', (8382, 8399), True, 'import astropy.io.fits as fits\n'), ((8425, 8449), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', (['flat_mask'], {}), '(flat_mask)\n', (8438, 8449), True, 'import astropy.io.fits as fits\n'), ((8475, 8499), 'astropy.io.fits.ImageHDU', 'fits.ImageHDU', (['flat_norm'], {}), '(flat_norm)\n', (8488, 8499), True, 'import astropy.io.fits as fits\n')]
import random import numpy as np import torch.utils.data as data from PIL import Image def default_loader(path): return Image.open(path).convert('RGB') class Reader(data.Dataset): def __init__(self, image_list, labels_list=[], transform=None, target_transform=None, use_cache=True, loader=default_loader): self.images = image_list self.loader = loader if len(labels_list) is not 0: assert len(image_list) == len(labels_list) self.labels = labels_list else: self.labels = False self.transform = transform self.target_transform = target_transform self.cache = {} self.use_cache = use_cache def __len__(self): return len(self.images) def __getitem__(self, idx): if idx not in self.cache: img = self.loader(self.images[idx]) if self.labels: target = Image.open(self.labels[idx]) else: target = None else: img, target = self.cache[idx] if self.use_cache: self.cache[idx] = (img, target) seed = np.random.randint(2147483647) random.seed(seed) if self.transform is not None: img = self.transform(img) random.seed(seed) if self.labels: if self.target_transform is not None: target = self.target_transform(target) return np.array(img), np.array(target)
[ "numpy.array", "numpy.random.randint", "PIL.Image.open", "random.seed" ]
[((1167, 1196), 'numpy.random.randint', 'np.random.randint', (['(2147483647)'], {}), '(2147483647)\n', (1184, 1196), True, 'import numpy as np\n'), ((1205, 1222), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1216, 1222), False, 'import random\n'), ((1310, 1327), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1321, 1327), False, 'import random\n'), ((127, 143), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (137, 143), False, 'from PIL import Image\n'), ((1473, 1486), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1481, 1486), True, 'import numpy as np\n'), ((1488, 1504), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (1496, 1504), True, 'import numpy as np\n'), ((946, 974), 'PIL.Image.open', 'Image.open', (['self.labels[idx]'], {}), '(self.labels[idx])\n', (956, 974), False, 'from PIL import Image\n')]
import itertools import sys import time import traceback from copy import deepcopy from typing import Callable import numpy as np from flatland.envs.agent_utils import RailAgentStatus from flatland.envs.rail_env import RailEnv from flatlander.mcts.node import Node def get_random_actions(obs: dict): return {i: np.random.randint(0, 5) for i in range(len(obs.keys()))} class MonteCarloTreeSearch: def __init__(self, time_budget: float, epsilon=1, rollout_depth=10, rollout_policy: Callable = get_random_actions): self.time_budget = time_budget self.count = 0 self.epsilon = epsilon self.rollout_policy = rollout_policy self.root = None self.rollout_depth = rollout_depth self.last_action = None def get_best_actions(self, env: RailEnv, obs): end_time = time.time() + self.time_budget if self.root is None: self.root = Node(None, None, self.get_possible_moves(env, obs)) else: self.root = list(filter(lambda child: child.action == self.last_action, self.root.children))[0] self.iterate(env, obs=obs, budget=end_time) print("Total visits:", np.sum(list(map(lambda c: c.times_visited, self.root.children)))) best_child = max(self.root.children, key=lambda n: n.times_visited) best_action = best_child.action self.last_action = best_action return best_action def iterate(self, env: RailEnv, obs: dict, budget: float = 0.): try: while time.time() < budget: new_env = deepcopy(env) node, obs = self.select(new_env, self.root, obs) new_node, obs = self.expand(node, new_env, obs) reward = self.simulate(new_env, obs) new_node.propagate_reward(reward) except Exception as e: traceback.print_exc(file=sys.stderr) raise e return self.root def select(self, env: RailEnv, node: Node, o: dict) -> (Node, dict): while True: # calculate UCBs if len(node.valid_moves) == 0 and node.children: best_node = max(node.children, key=self.ucb) o, r, d, _ = env.step(best_node.action) node = best_node else: return node, o @staticmethod def get_agent_positions(env: RailEnv): pos = {} for agent in env.agents: if agent.status == RailAgentStatus.READY_TO_DEPART: agent_virtual_position = agent.initial_position elif agent.status == RailAgentStatus.ACTIVE: agent_virtual_position = agent.position elif agent.status == RailAgentStatus.DONE: agent_virtual_position = agent.target else: agent_virtual_position = None pos[agent.handle] = agent_virtual_position return pos @classmethod def get_possible_moves(cls, env: RailEnv, obs: dict): active_agents = [] positions = cls.get_agent_positions(env) possible_actions = {} for handle in obs.keys(): if positions[handle] is not None: possible_transitions = np.flatnonzero(env.rail.get_transitions(*positions[handle], env.agents[handle].direction)) if len(possible_transitions) != 0 and env.agents[handle].status != RailAgentStatus.DONE: possible_actions[handle] = possible_transitions active_agents.append(handle) possible_moves = list(itertools.product(*possible_actions.values())) possible_moves = [{handle: action_list[i] for i, handle in enumerate(active_agents)} for action_list in possible_moves] return possible_moves @classmethod def expand(cls, node: Node, env: RailEnv, obs) -> (Node, dict): if len(node.valid_moves) == 0: return node else: new_node = Node(node, node.valid_moves[0], cls.get_possible_moves(env, obs)) node.valid_moves.pop(0) node.children.append(new_node) o, r, d, _ = env.step(new_node.action) return new_node, o def simulate(self, env: RailEnv, obs: dict) -> float: done = False reward = 0. count = 0 while not done: if not count <= self.rollout_depth: break o, r, d, _ = env.step(self.rollout_policy(obs)) reward += np.sum(list(r.values())) done = d["__all__"] count += 1 return reward def ucb(self, node: Node): return node.reward / node.times_visited + self.epsilon * \ np.sqrt(np.log(node.parent.times_visited) / node.times_visited)
[ "numpy.log", "numpy.random.randint", "copy.deepcopy", "traceback.print_exc", "time.time" ]
[((319, 342), 'numpy.random.randint', 'np.random.randint', (['(0)', '(5)'], {}), '(0, 5)\n', (336, 342), True, 'import numpy as np\n'), ((886, 897), 'time.time', 'time.time', ([], {}), '()\n', (895, 897), False, 'import time\n'), ((1578, 1589), 'time.time', 'time.time', ([], {}), '()\n', (1587, 1589), False, 'import time\n'), ((1626, 1639), 'copy.deepcopy', 'deepcopy', (['env'], {}), '(env)\n', (1634, 1639), False, 'from copy import deepcopy\n'), ((1915, 1951), 'traceback.print_exc', 'traceback.print_exc', ([], {'file': 'sys.stderr'}), '(file=sys.stderr)\n', (1934, 1951), False, 'import traceback\n'), ((4867, 4900), 'numpy.log', 'np.log', (['node.parent.times_visited'], {}), '(node.parent.times_visited)\n', (4873, 4900), True, 'import numpy as np\n')]
# coding: utf-8 """ 常用技术分析指标:MA, MACD, BOLL 使用 ta-lib 可以大幅提升计算性能,10倍左右 """ import numpy as np import talib as ta SMA = ta.SMA EMA = ta.EMA MACD = ta.MACD def KDJ(close: np.array, high: np.array, low: np.array): """ :param close: 收盘价序列 :param high: 最高价序列 :param low: 最低价序列 :return: """ n = 9 hv = [] lv = [] for i in range(len(close)): if i < n: h_ = high[0: i+1] l_ = low[0: i+1] else: h_ = high[i - n + 1: i + 1] l_ = low[i - n + 1: i + 1] hv.append(max(h_)) lv.append(min(l_)) hv = np.around(hv, decimals=2) lv = np.around(lv, decimals=2) rsv = np.where(hv == lv, 0, (close - lv) / (hv - lv) * 100) k = [] d = [] j = [] for i in range(len(rsv)): if i < n: k_ = rsv[i] d_ = k_ else: k_ = (2 / 3) * k[i-1] + (1 / 3) * rsv[i] d_ = (2 / 3) * d[i-1] + (1 / 3) * k_ k.append(k_) d.append(d_) j.append(3 * k_ - 2 * d_) k = np.array(k, dtype=np.double) d = np.array(d, dtype=np.double) j = np.array(j, dtype=np.double) return k, d, j def RSQ(close: [np.array, list]) -> float: """拟合优度 R SQuare :param close: 收盘价序列 :return: """ x = list(range(len(close))) y = np.array(close) x_squred_sum = sum([x1 * x1 for x1 in x]) xy_product_sum = sum([x[i] * y[i] for i in range(len(x))]) num = len(x) x_sum = sum(x) y_sum = sum(y) delta = float(num * x_squred_sum - x_sum * x_sum) if delta == 0: return 0 y_intercept = (1 / delta) * (x_squred_sum * y_sum - x_sum * xy_product_sum) slope = (1 / delta) * (num * xy_product_sum - x_sum * y_sum) y_mean = np.mean(y) ss_tot = sum([(y1 - y_mean) * (y1 - y_mean) for y1 in y]) + 0.00001 ss_err = sum([(y[i] - slope * x[i] - y_intercept) * (y[i] - slope * x[i] - y_intercept) for i in range(len(x))]) rsq = 1 - ss_err / ss_tot return round(rsq, 4)
[ "numpy.where", "numpy.array", "numpy.mean", "numpy.around" ]
[((615, 640), 'numpy.around', 'np.around', (['hv'], {'decimals': '(2)'}), '(hv, decimals=2)\n', (624, 640), True, 'import numpy as np\n'), ((650, 675), 'numpy.around', 'np.around', (['lv'], {'decimals': '(2)'}), '(lv, decimals=2)\n', (659, 675), True, 'import numpy as np\n'), ((686, 739), 'numpy.where', 'np.where', (['(hv == lv)', '(0)', '((close - lv) / (hv - lv) * 100)'], {}), '(hv == lv, 0, (close - lv) / (hv - lv) * 100)\n', (694, 739), True, 'import numpy as np\n'), ((1068, 1096), 'numpy.array', 'np.array', (['k'], {'dtype': 'np.double'}), '(k, dtype=np.double)\n', (1076, 1096), True, 'import numpy as np\n'), ((1105, 1133), 'numpy.array', 'np.array', (['d'], {'dtype': 'np.double'}), '(d, dtype=np.double)\n', (1113, 1133), True, 'import numpy as np\n'), ((1142, 1170), 'numpy.array', 'np.array', (['j'], {'dtype': 'np.double'}), '(j, dtype=np.double)\n', (1150, 1170), True, 'import numpy as np\n'), ((1341, 1356), 'numpy.array', 'np.array', (['close'], {}), '(close)\n', (1349, 1356), True, 'import numpy as np\n'), ((1770, 1780), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (1777, 1780), True, 'import numpy as np\n')]
#!/usr/bin/env python import os import numpy as np from OPTIMAS.merge_npy import merge_npy from OPTIMAS.utils.files_handling import images_list, read_image_size def test_merge_npy(): input_data_folder = 'tests/test_data/2020_09_03' experiment = 'experiment_1' output_path = f'{input_data_folder}/{experiment}' merge_npy(input_data_folder, output_path, experiment) merged_npy_path = f"{output_path}/raw_data.npy" merged_npy = np.load(merged_npy_path) json_file_path = f"{input_data_folder}/{experiment}/{experiment}_info.json" image_x, image_y = read_image_size(json_file_path) os.remove(merged_npy_path) assert merged_npy.shape[0] == len(os.listdir( f"{input_data_folder}/{experiment}/raw_data")) assert merged_npy.shape[1] == image_x assert merged_npy.shape[2] == image_y
[ "OPTIMAS.merge_npy.merge_npy", "os.listdir", "OPTIMAS.utils.files_handling.read_image_size", "numpy.load", "os.remove" ]
[((330, 383), 'OPTIMAS.merge_npy.merge_npy', 'merge_npy', (['input_data_folder', 'output_path', 'experiment'], {}), '(input_data_folder, output_path, experiment)\n', (339, 383), False, 'from OPTIMAS.merge_npy import merge_npy\n'), ((454, 478), 'numpy.load', 'np.load', (['merged_npy_path'], {}), '(merged_npy_path)\n', (461, 478), True, 'import numpy as np\n'), ((583, 614), 'OPTIMAS.utils.files_handling.read_image_size', 'read_image_size', (['json_file_path'], {}), '(json_file_path)\n', (598, 614), False, 'from OPTIMAS.utils.files_handling import images_list, read_image_size\n'), ((620, 646), 'os.remove', 'os.remove', (['merged_npy_path'], {}), '(merged_npy_path)\n', (629, 646), False, 'import os\n'), ((686, 742), 'os.listdir', 'os.listdir', (['f"""{input_data_folder}/{experiment}/raw_data"""'], {}), "(f'{input_data_folder}/{experiment}/raw_data')\n", (696, 742), False, 'import os\n')]
import collections import numpy as np import pytest from psyneulink.globals.utilities import convert_all_elements_to_np_array @pytest.mark.parametrize( 'arr, expected', [ ([[0], [0, 0]], np.array([np.array([0]), np.array([0, 0])])), # should test these but numpy cannot easily create an array from them # [np.ones((2,2)), np.zeros((2,1))] # [np.array([[0]]), np.array([[[ 1., 1., 1.], [ 1., 1., 1.]]])] ] ) def test_convert_all_elements_to_np_array(arr, expected): converted = convert_all_elements_to_np_array(arr) # no current numpy methods can test this def check_equality_recursive(arr, expected): if ( not isinstance(arr, collections.Iterable) or (isinstance(arr, np.ndarray) and arr.ndim == 0) ): assert arr == expected else: assert isinstance(expected, type(arr)) assert len(arr) == len(expected) for i in range(len(arr)): check_equality_recursive(arr[i], expected[i]) check_equality_recursive(converted, expected)
[ "numpy.array", "psyneulink.globals.utilities.convert_all_elements_to_np_array" ]
[((533, 570), 'psyneulink.globals.utilities.convert_all_elements_to_np_array', 'convert_all_elements_to_np_array', (['arr'], {}), '(arr)\n', (565, 570), False, 'from psyneulink.globals.utilities import convert_all_elements_to_np_array\n'), ((216, 229), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (224, 229), True, 'import numpy as np\n'), ((231, 247), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (239, 247), True, 'import numpy as np\n')]
# Source 1: https://medium.com/technology-invention-and-more/how-to-build-a-simple-neural-network-in-9-lines-of-python-code-cc8f23647ca1 # Source 2: https://iamtrask.github.io/2015/07/12/basic-python-network/ # Source 3: https://www.youtube.com/watch?v=h3l4qz76JhQ&list=PL2-dafEMk2A5BoX3KyKu6ti5_Pytp91sk ''' Description: - simple three layer network (input, hidden, output) ''' import numpy as np # Seed the random number generator, so it generates the same numbers # every time the program runs. np.random.seed(1) # S shaped function. We pass the weighted sum to normalize it between 0 and 1 def sigmoid(x, deriv=False): if deriv: return x * (1 - x) return 1 / (1 + np.exp(-x)) training_set_inputs = np.array([ [0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1] ]) training_set_outputs = np.array([[0, 1, 1, 0]]).T # transpose matrix from horizontal to vertical # synapses, weights between layers # weights between input and hidden layer. 3 inputs to 4 hidden syn0 = 2 * np.random.random((3, 4)) - 1 # weights between hidden and output layer. 4 hidden to 1 output syn1 = 2 * np.random.random((4, 1)) - 1 # training interation. Aim to reduce error. for j in range(60000): l0 = training_set_inputs # input layer # np.dot(l, syn) - sum of all weights and inputs l1 = sigmoid(np.dot(l0, syn0)) # hidden layer l2 = sigmoid(np.dot(l1, syn1)) # output layer l2_error = training_set_outputs - l2 if j % 10000 == 0: print("Error: {0}".format(np.mean(np.abs(l2_error)))) l2_delta = l2_error * sigmoid(l2, deriv=True) l1_error = l2_delta.dot(syn1.T) l1_delta = l1_error * sigmoid(l1, deriv=True) # update weights syn1 += l1.T.dot(l2_delta) syn0 += l0.T.dot(l1_delta) print("Output of training:") print(l2)
[ "numpy.abs", "numpy.random.random", "numpy.exp", "numpy.array", "numpy.dot", "numpy.random.seed" ]
[((501, 518), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (515, 518), True, 'import numpy as np\n'), ((729, 783), 'numpy.array', 'np.array', (['[[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]]'], {}), '([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\n', (737, 783), True, 'import numpy as np\n'), ((828, 852), 'numpy.array', 'np.array', (['[[0, 1, 1, 0]]'], {}), '([[0, 1, 1, 0]])\n', (836, 852), True, 'import numpy as np\n'), ((1014, 1038), 'numpy.random.random', 'np.random.random', (['(3, 4)'], {}), '((3, 4))\n', (1030, 1038), True, 'import numpy as np\n'), ((1119, 1143), 'numpy.random.random', 'np.random.random', (['(4, 1)'], {}), '((4, 1))\n', (1135, 1143), True, 'import numpy as np\n'), ((1330, 1346), 'numpy.dot', 'np.dot', (['l0', 'syn0'], {}), '(l0, syn0)\n', (1336, 1346), True, 'import numpy as np\n'), ((1380, 1396), 'numpy.dot', 'np.dot', (['l1', 'syn1'], {}), '(l1, syn1)\n', (1386, 1396), True, 'import numpy as np\n'), ((694, 704), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (700, 704), True, 'import numpy as np\n'), ((1521, 1537), 'numpy.abs', 'np.abs', (['l2_error'], {}), '(l2_error)\n', (1527, 1537), True, 'import numpy as np\n')]
import torch from torchvision import datasets, transforms, models import torchvision.models as models from torch import nn from torch import optim import time import numpy as np from PIL import Image import matplotlib.pyplot as plt import torch.nn.functional as F import argparse parser = argparse.ArgumentParser() parser.add_argument('--dir', type=str, help='path to folder of images') parser.add_argument('--arch', type=str, default='alexnet', help='CNN model architecture') parser.add_argument('--gpu', action='store', default='gpu', help='Use GPU') parser.add_argument('--topk', type=int, help='Top K') parser.add_argument('--checkpoint', action='store', default='checkpoint.pth', help='Checkpoint') args = parser.parse_args () path = args.dir # TODO: Write a function that loads a checkpoint and rebuilds the model def rebuild_model(path): checkpoint = torch.load('checkpoint.pth') structure = checkpoint['structure'] hidden_layer1 = checkpoint['hidden_layer1'] model,_,_ = nn_measure(structure , 0.5, hidden_layer1) model.class_to_idx = checkpoint['class_to_idx'] model.load_state_dict(checkpoint['state_dict']) def process_image(image): ''' Scales, crops, and normalizes a PIL image for a PyTorch model, returns an Numpy array ''' proc_pil = Image.open(image) preprocess_image = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = preprocess_image(proc_pil) return img # TODO: Process a PIL image for use in a PyTorch model def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. ''' model.to(device) img_torch = process_image(image_path) img_torch = img_torch.unsqueeze_(0) img_torch = img_torch.float() with torch.no_grad(): output = model.forward(img_torch.cuda()) probability = F.softmax(output.data,dim=1) return probability.topk(topk) # TODO: Implement the code to predict the class from an image file def check_sanity(): plt.rcParams["figure.figsize"] = (10,5) plt.subplot(211) index = 1 path = test_dir + '/19/image_06196.jpg' probabilities = predict(path, model) image = process_image(path) probabilities = probabilities axs = imshow(image, ax = plt) axs.axis('off') axs.title(cat_to_name[str(index)]) axs.show() a = np.array(probabilities[0][0]) b = [cat_to_name[str(index+1)] for index in np.array(probabilities[1][0])] N=float(len(b)) fig,ax = plt.subplots(figsize=(8,3)) width = 0.8 tickLocations = np.arange(N) ax.bar(tickLocations, a, width, linewidth=4.0, align = 'center') ax.set_xticks(ticks = tickLocations) ax.set_xticklabels(b) ax.set_xlim(min(tickLocations)-0.6,max(tickLocations)+0.6) ax.set_yticks([0.2,0.4,0.6,0.8,1,1.2]) ax.set_ylim((0,1)) ax.yaxis.grid(True) plt.show()
[ "torchvision.transforms.CenterCrop", "PIL.Image.open", "argparse.ArgumentParser", "torch.load", "numpy.array", "matplotlib.pyplot.subplots", "torchvision.transforms.Normalize", "torchvision.transforms.Resize", "torch.no_grad", "torchvision.transforms.ToTensor", "matplotlib.pyplot.subplot", "to...
[((290, 315), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (313, 315), False, 'import argparse\n'), ((988, 1016), 'torch.load', 'torch.load', (['"""checkpoint.pth"""'], {}), "('checkpoint.pth')\n", (998, 1016), False, 'import torch\n'), ((1420, 1437), 'PIL.Image.open', 'Image.open', (['image'], {}), '(image)\n', (1430, 1437), False, 'from PIL import Image\n'), ((2183, 2212), 'torch.nn.functional.softmax', 'F.softmax', (['output.data'], {'dim': '(1)'}), '(output.data, dim=1)\n', (2192, 2212), True, 'import torch.nn.functional as F\n'), ((2396, 2412), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (2407, 2412), True, 'import matplotlib.pyplot as plt\n'), ((2716, 2745), 'numpy.array', 'np.array', (['probabilities[0][0]'], {}), '(probabilities[0][0])\n', (2724, 2745), True, 'import numpy as np\n'), ((2868, 2896), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 3)'}), '(figsize=(8, 3))\n', (2880, 2896), True, 'import matplotlib.pyplot as plt\n'), ((2932, 2944), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (2941, 2944), True, 'import numpy as np\n'), ((3243, 3253), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3251, 3253), True, 'import matplotlib.pyplot as plt\n'), ((2090, 2105), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2103, 2105), False, 'import torch\n'), ((1495, 1517), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (1512, 1517), False, 'from torchvision import datasets, transforms, models\n'), ((1527, 1553), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (1548, 1553), False, 'from torchvision import datasets, transforms, models\n'), ((1563, 1584), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1582, 1584), False, 'from torchvision import datasets, transforms, models\n'), ((1594, 1669), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (1614, 1669), False, 'from torchvision import datasets, transforms, models\n'), ((2794, 2823), 'numpy.array', 'np.array', (['probabilities[1][0]'], {}), '(probabilities[1][0])\n', (2802, 2823), True, 'import numpy as np\n')]
""" Module for legacy LEAP dataset. """ import json import os import numpy as np import pandas as pd from typing import List from sleap.util import json_loads from sleap.io.video import Video from sleap.instance import ( LabeledFrame, PredictedPoint, PredictedInstance, Track, Point, Instance, ) from sleap.skeleton import Skeleton def load_predicted_labels_json_old( data_path: str, parsed_json: dict = None, adjust_matlab_indexing: bool = True, fix_rel_paths: bool = True, ) -> List[LabeledFrame]: """ Load predicted instances from Talmo's old JSON format. Args: data_path: The path to the JSON file. parsed_json: The parsed json if already loaded, so we can save some time if already parsed. adjust_matlab_indexing: Whether to adjust indexing from MATLAB. fix_rel_paths: Whether to fix paths to videos to absolute paths. Returns: List of :class:`LabeledFrame` objects. """ if parsed_json is None: data = json.loads(open(data_path).read()) else: data = parsed_json videos = pd.DataFrame(data["videos"]) predicted_instances = pd.DataFrame(data["predicted_instances"]) predicted_points = pd.DataFrame(data["predicted_points"]) if adjust_matlab_indexing: predicted_instances.frameIdx -= 1 predicted_points.frameIdx -= 1 predicted_points.node -= 1 predicted_points.x -= 1 predicted_points.y -= 1 skeleton = Skeleton() skeleton.add_nodes(data["skeleton"]["nodeNames"]) edges = data["skeleton"]["edges"] if adjust_matlab_indexing: edges = np.array(edges) - 1 for (src_idx, dst_idx) in edges: skeleton.add_edge( data["skeleton"]["nodeNames"][src_idx], data["skeleton"]["nodeNames"][dst_idx], ) if fix_rel_paths: for i, row in videos.iterrows(): p = row.filepath if not os.path.exists(p): p = os.path.join(os.path.dirname(data_path), p) if os.path.exists(p): videos.at[i, "filepath"] = p # Make the video objects video_objects = {} for i, row in videos.iterrows(): if videos.at[i, "format"] == "media": vid = Video.from_media(videos.at[i, "filepath"]) else: vid = Video.from_hdf5( filename=videos.at[i, "filepath"], dataset=videos.at[i, "dataset"] ) video_objects[videos.at[i, "id"]] = vid track_ids = predicted_instances["trackId"].values unique_track_ids = np.unique(track_ids) spawned_on = { track_id: predicted_instances.loc[predicted_instances["trackId"] == track_id][ "frameIdx" ].values[0] for track_id in unique_track_ids } tracks = { i: Track(name=str(i), spawned_on=spawned_on[i]) for i in np.unique(predicted_instances["trackId"].values).tolist() } # A function to get all the instances for a particular video frame def get_frame_predicted_instances(video_id, frame_idx): points = predicted_points is_in_frame = (points["videoId"] == video_id) & ( points["frameIdx"] == frame_idx ) if not is_in_frame.any(): return [] instances = [] frame_instance_ids = np.unique(points["instanceId"][is_in_frame]) for i, instance_id in enumerate(frame_instance_ids): is_instance = is_in_frame & (points["instanceId"] == instance_id) track_id = predicted_instances.loc[ predicted_instances["id"] == instance_id ]["trackId"].values[0] match_score = predicted_instances.loc[ predicted_instances["id"] == instance_id ]["matching_score"].values[0] track_score = predicted_instances.loc[ predicted_instances["id"] == instance_id ]["tracking_score"].values[0] instance_points = { data["skeleton"]["nodeNames"][n]: PredictedPoint( x, y, visible=v, score=confidence ) for x, y, n, v, confidence in zip( *[ points[k][is_instance] for k in ["x", "y", "node", "visible", "confidence"] ] ) } instance = PredictedInstance( skeleton=skeleton, points=instance_points, track=tracks[track_id], score=match_score, ) instances.append(instance) return instances # Get the unique labeled frames and construct a list of LabeledFrame objects for them. frame_keys = list( { (videoId, frameIdx) for videoId, frameIdx in zip( predicted_points["videoId"], predicted_points["frameIdx"] ) } ) frame_keys.sort() labels = [] for videoId, frameIdx in frame_keys: label = LabeledFrame( video=video_objects[videoId], frame_idx=frameIdx, instances=get_frame_predicted_instances(videoId, frameIdx), ) labels.append(label) return labels def load_labels_json_old( data_path: str, parsed_json: dict = None, adjust_matlab_indexing: bool = True, fix_rel_paths: bool = True, ) -> List[LabeledFrame]: """ Load predicted instances from Talmo's old JSON format. Args: data_path: The path to the JSON file. parsed_json: The parsed json if already loaded, so we can save some time if already parsed. adjust_matlab_indexing: Whether to adjust indexing from MATLAB. fix_rel_paths: Whether to fix paths to videos to absolute paths. Returns: A newly constructed Labels object. """ if parsed_json is None: data = json_loads(open(data_path).read()) else: data = parsed_json videos = pd.DataFrame(data["videos"]) instances = pd.DataFrame(data["instances"]) points = pd.DataFrame(data["points"]) predicted_instances = pd.DataFrame(data["predicted_instances"]) predicted_points = pd.DataFrame(data["predicted_points"]) if adjust_matlab_indexing: instances.frameIdx -= 1 points.frameIdx -= 1 predicted_instances.frameIdx -= 1 predicted_points.frameIdx -= 1 points.node -= 1 predicted_points.node -= 1 points.x -= 1 predicted_points.x -= 1 points.y -= 1 predicted_points.y -= 1 skeleton = Skeleton() skeleton.add_nodes(data["skeleton"]["nodeNames"]) edges = data["skeleton"]["edges"] if adjust_matlab_indexing: edges = np.array(edges) - 1 for (src_idx, dst_idx) in edges: skeleton.add_edge( data["skeleton"]["nodeNames"][src_idx], data["skeleton"]["nodeNames"][dst_idx], ) if fix_rel_paths: for i, row in videos.iterrows(): p = row.filepath if not os.path.exists(p): p = os.path.join(os.path.dirname(data_path), p) if os.path.exists(p): videos.at[i, "filepath"] = p # Make the video objects video_objects = {} for i, row in videos.iterrows(): if videos.at[i, "format"] == "media": vid = Video.from_media(videos.at[i, "filepath"]) else: vid = Video.from_hdf5( filename=videos.at[i, "filepath"], dataset=videos.at[i, "dataset"] ) video_objects[videos.at[i, "id"]] = vid # A function to get all the instances for a particular video frame def get_frame_instances(video_id, frame_idx): """ """ is_in_frame = (points["videoId"] == video_id) & ( points["frameIdx"] == frame_idx ) if not is_in_frame.any(): return [] instances = [] frame_instance_ids = np.unique(points["instanceId"][is_in_frame]) for i, instance_id in enumerate(frame_instance_ids): is_instance = is_in_frame & (points["instanceId"] == instance_id) instance_points = { data["skeleton"]["nodeNames"][n]: Point(x, y, visible=v) for x, y, n, v in zip( *[points[k][is_instance] for k in ["x", "y", "node", "visible"]] ) } instance = Instance(skeleton=skeleton, points=instance_points) instances.append(instance) return instances # Get the unique labeled frames and construct a list of LabeledFrame objects for them. frame_keys = list( { (videoId, frameIdx) for videoId, frameIdx in zip(points["videoId"], points["frameIdx"]) } ) frame_keys.sort() labels = [] for videoId, frameIdx in frame_keys: label = LabeledFrame( video=video_objects[videoId], frame_idx=frameIdx, instances=get_frame_instances(videoId, frameIdx), ) labels.append(label) return labels
[ "sleap.io.video.Video.from_hdf5", "sleap.skeleton.Skeleton", "os.path.exists", "numpy.unique", "sleap.instance.Point", "sleap.instance.PredictedInstance", "sleap.instance.PredictedPoint", "numpy.array", "os.path.dirname", "pandas.DataFrame", "sleap.io.video.Video.from_media", "sleap.instance.I...
[((1124, 1152), 'pandas.DataFrame', 'pd.DataFrame', (["data['videos']"], {}), "(data['videos'])\n", (1136, 1152), True, 'import pandas as pd\n'), ((1179, 1220), 'pandas.DataFrame', 'pd.DataFrame', (["data['predicted_instances']"], {}), "(data['predicted_instances'])\n", (1191, 1220), True, 'import pandas as pd\n'), ((1244, 1282), 'pandas.DataFrame', 'pd.DataFrame', (["data['predicted_points']"], {}), "(data['predicted_points'])\n", (1256, 1282), True, 'import pandas as pd\n'), ((1514, 1524), 'sleap.skeleton.Skeleton', 'Skeleton', ([], {}), '()\n', (1522, 1524), False, 'from sleap.skeleton import Skeleton\n'), ((2614, 2634), 'numpy.unique', 'np.unique', (['track_ids'], {}), '(track_ids)\n', (2623, 2634), True, 'import numpy as np\n'), ((6056, 6084), 'pandas.DataFrame', 'pd.DataFrame', (["data['videos']"], {}), "(data['videos'])\n", (6068, 6084), True, 'import pandas as pd\n'), ((6101, 6132), 'pandas.DataFrame', 'pd.DataFrame', (["data['instances']"], {}), "(data['instances'])\n", (6113, 6132), True, 'import pandas as pd\n'), ((6146, 6174), 'pandas.DataFrame', 'pd.DataFrame', (["data['points']"], {}), "(data['points'])\n", (6158, 6174), True, 'import pandas as pd\n'), ((6201, 6242), 'pandas.DataFrame', 'pd.DataFrame', (["data['predicted_instances']"], {}), "(data['predicted_instances'])\n", (6213, 6242), True, 'import pandas as pd\n'), ((6266, 6304), 'pandas.DataFrame', 'pd.DataFrame', (["data['predicted_points']"], {}), "(data['predicted_points'])\n", (6278, 6304), True, 'import pandas as pd\n'), ((6666, 6676), 'sleap.skeleton.Skeleton', 'Skeleton', ([], {}), '()\n', (6674, 6676), False, 'from sleap.skeleton import Skeleton\n'), ((3371, 3415), 'numpy.unique', 'np.unique', (["points['instanceId'][is_in_frame]"], {}), "(points['instanceId'][is_in_frame])\n", (3380, 3415), True, 'import numpy as np\n'), ((8047, 8091), 'numpy.unique', 'np.unique', (["points['instanceId'][is_in_frame]"], {}), "(points['instanceId'][is_in_frame])\n", (8056, 8091), True, 'import numpy as np\n'), ((1664, 1679), 'numpy.array', 'np.array', (['edges'], {}), '(edges)\n', (1672, 1679), True, 'import numpy as np\n'), ((2298, 2340), 'sleap.io.video.Video.from_media', 'Video.from_media', (["videos.at[i, 'filepath']"], {}), "(videos.at[i, 'filepath'])\n", (2314, 2340), False, 'from sleap.io.video import Video\n'), ((2373, 2460), 'sleap.io.video.Video.from_hdf5', 'Video.from_hdf5', ([], {'filename': "videos.at[i, 'filepath']", 'dataset': "videos.at[i, 'dataset']"}), "(filename=videos.at[i, 'filepath'], dataset=videos.at[i,\n 'dataset'])\n", (2388, 2460), False, 'from sleap.io.video import Video\n'), ((4441, 4549), 'sleap.instance.PredictedInstance', 'PredictedInstance', ([], {'skeleton': 'skeleton', 'points': 'instance_points', 'track': 'tracks[track_id]', 'score': 'match_score'}), '(skeleton=skeleton, points=instance_points, track=tracks[\n track_id], score=match_score)\n', (4458, 4549), False, 'from sleap.instance import LabeledFrame, PredictedPoint, PredictedInstance, Track, Point, Instance\n'), ((6816, 6831), 'numpy.array', 'np.array', (['edges'], {}), '(edges)\n', (6824, 6831), True, 'import numpy as np\n'), ((7450, 7492), 'sleap.io.video.Video.from_media', 'Video.from_media', (["videos.at[i, 'filepath']"], {}), "(videos.at[i, 'filepath'])\n", (7466, 7492), False, 'from sleap.io.video import Video\n'), ((7525, 7612), 'sleap.io.video.Video.from_hdf5', 'Video.from_hdf5', ([], {'filename': "videos.at[i, 'filepath']", 'dataset': "videos.at[i, 'dataset']"}), "(filename=videos.at[i, 'filepath'], dataset=videos.at[i,\n 'dataset'])\n", (7540, 7612), False, 'from sleap.io.video import Video\n'), ((8516, 8567), 'sleap.instance.Instance', 'Instance', ([], {'skeleton': 'skeleton', 'points': 'instance_points'}), '(skeleton=skeleton, points=instance_points)\n', (8524, 8567), False, 'from sleap.instance import LabeledFrame, PredictedPoint, PredictedInstance, Track, Point, Instance\n'), ((1974, 1991), 'os.path.exists', 'os.path.exists', (['p'], {}), '(p)\n', (1988, 1991), False, 'import os\n'), ((2076, 2093), 'os.path.exists', 'os.path.exists', (['p'], {}), '(p)\n', (2090, 2093), False, 'import os\n'), ((4077, 4126), 'sleap.instance.PredictedPoint', 'PredictedPoint', (['x', 'y'], {'visible': 'v', 'score': 'confidence'}), '(x, y, visible=v, score=confidence)\n', (4091, 4126), False, 'from sleap.instance import LabeledFrame, PredictedPoint, PredictedInstance, Track, Point, Instance\n'), ((7126, 7143), 'os.path.exists', 'os.path.exists', (['p'], {}), '(p)\n', (7140, 7143), False, 'import os\n'), ((7228, 7245), 'os.path.exists', 'os.path.exists', (['p'], {}), '(p)\n', (7242, 7245), False, 'import os\n'), ((8313, 8335), 'sleap.instance.Point', 'Point', (['x', 'y'], {'visible': 'v'}), '(x, y, visible=v)\n', (8318, 8335), False, 'from sleap.instance import LabeledFrame, PredictedPoint, PredictedInstance, Track, Point, Instance\n'), ((2026, 2052), 'os.path.dirname', 'os.path.dirname', (['data_path'], {}), '(data_path)\n', (2041, 2052), False, 'import os\n'), ((2920, 2968), 'numpy.unique', 'np.unique', (["predicted_instances['trackId'].values"], {}), "(predicted_instances['trackId'].values)\n", (2929, 2968), True, 'import numpy as np\n'), ((7178, 7204), 'os.path.dirname', 'os.path.dirname', (['data_path'], {}), '(data_path)\n', (7193, 7204), False, 'import os\n')]
import cv2 import numpy as np img_big=cv2.imread('/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png',0) img_big_rgb=cv2.imread('/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png') img_small=cv2.imread('/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/calendar_SR_2019-05-07_21-54-28--01/rgb_002.png',0) template=img_small res = cv2.matchTemplate(img_big,template,cv2.TM_CCOEFF_NORMED) threshold = 0.99 loc = np.where(res >= threshold) index=list(zip(*loc[::-1]))[0] print(index) img_big_copy=img_big_rgb.copy() cv2.rectangle(img_big_copy, index, (index[0] + 640, index[1] + 480), (0,255,0), 1) img_sample=img_big[index[1]:index[1]+480,index[0]:index[0]+640] cv2.imwrite('sampe.png',img_sample) cv2.imwrite('sampe_big.png',img_big_copy)
[ "cv2.rectangle", "cv2.imwrite", "numpy.where", "cv2.matchTemplate", "cv2.imread" ]
[((39, 175), 'cv2.imread', 'cv2.imread', (['"""/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png"""', '(0)'], {}), "(\n '/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png'\n , 0)\n", (49, 175), False, 'import cv2\n'), ((177, 310), 'cv2.imread', 'cv2.imread', (['"""/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png"""'], {}), "(\n '/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/01-4/GW1AM2_20170102_01D_PNMA_L3SGT36HA2220220_BT_H_N_01.png'\n )\n", (187, 310), False, 'import cv2\n'), ((311, 434), 'cv2.imread', 'cv2.imread', (['"""/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/calendar_SR_2019-05-07_21-54-28--01/rgb_002.png"""', '(0)'], {}), "(\n '/Users/zhuxuhan/PycharmProjects/newbegin/1/01-01/calendar_SR_2019-05-07_21-54-28--01/rgb_002.png'\n , 0)\n", (321, 434), False, 'import cv2\n'), ((451, 509), 'cv2.matchTemplate', 'cv2.matchTemplate', (['img_big', 'template', 'cv2.TM_CCOEFF_NORMED'], {}), '(img_big, template, cv2.TM_CCOEFF_NORMED)\n', (468, 509), False, 'import cv2\n'), ((531, 557), 'numpy.where', 'np.where', (['(res >= threshold)'], {}), '(res >= threshold)\n', (539, 557), True, 'import numpy as np\n'), ((634, 723), 'cv2.rectangle', 'cv2.rectangle', (['img_big_copy', 'index', '(index[0] + 640, index[1] + 480)', '(0, 255, 0)', '(1)'], {}), '(img_big_copy, index, (index[0] + 640, index[1] + 480), (0, \n 255, 0), 1)\n', (647, 723), False, 'import cv2\n'), ((781, 817), 'cv2.imwrite', 'cv2.imwrite', (['"""sampe.png"""', 'img_sample'], {}), "('sampe.png', img_sample)\n", (792, 817), False, 'import cv2\n'), ((817, 859), 'cv2.imwrite', 'cv2.imwrite', (['"""sampe_big.png"""', 'img_big_copy'], {}), "('sampe_big.png', img_big_copy)\n", (828, 859), False, 'import cv2\n')]
def example(Simulator): from csdl import Model import csdl import numpy as np class ExampleSimple(Model): def define(self): # add_input nx = 3 ny = 4 mesh = np.zeros((nx, ny, 3)) mesh[:, :, 0] = np.outer(np.arange(nx), np.ones(ny)) mesh[:, :, 1] = np.outer(np.arange(ny), np.ones(nx)).T mesh[:, :, 2] = 0. def_mesh = self.declare_variable('def_mesh', val=mesh) # compute_output quarter_chord = def_mesh[nx - 1, :, :] * 0.25 + def_mesh[0, :, :] * 0.75 b_pts = def_mesh[:-1, :, :] * .75 + def_mesh[1:, :, :] * .25 self.register_output('quarter_chord', quarter_chord) self.register_output('b_pts', b_pts) quarter_chord = self.declare_variable( 'quarter_chord', val=np.ones((1, 4, 3)), ) e = quarter_chord[:, :nx, :] f = quarter_chord[:, 1:, :] # this will combine operations widths = csdl.pnorm(f - e) self.register_output('widths', widths) sim = Simulator(ExampleSimple()) sim.run() print('quarter_chord', sim['quarter_chord'].shape) print(sim['quarter_chord']) print('widths', sim['widths'].shape) print(sim['widths']) return sim
[ "numpy.zeros", "csdl.pnorm", "numpy.ones", "numpy.arange" ]
[((244, 265), 'numpy.zeros', 'np.zeros', (['(nx, ny, 3)'], {}), '((nx, ny, 3))\n', (252, 265), True, 'import numpy as np\n'), ((1137, 1154), 'csdl.pnorm', 'csdl.pnorm', (['(f - e)'], {}), '(f - e)\n', (1147, 1154), False, 'import csdl\n'), ((308, 321), 'numpy.arange', 'np.arange', (['nx'], {}), '(nx)\n', (317, 321), True, 'import numpy as np\n'), ((323, 334), 'numpy.ones', 'np.ones', (['ny'], {}), '(ny)\n', (330, 334), True, 'import numpy as np\n'), ((373, 386), 'numpy.arange', 'np.arange', (['ny'], {}), '(ny)\n', (382, 386), True, 'import numpy as np\n'), ((388, 399), 'numpy.ones', 'np.ones', (['nx'], {}), '(nx)\n', (395, 399), True, 'import numpy as np\n'), ((953, 971), 'numpy.ones', 'np.ones', (['(1, 4, 3)'], {}), '((1, 4, 3))\n', (960, 971), True, 'import numpy as np\n')]
import os import pathlib import matplotlib import matplotlib.pyplot as plt import io import scipy.misc import numpy as np from six import BytesIO from PIL import Image, ImageDraw, ImageFont from six.moves.urllib.request import urlopen import tensorflow as tf import tensorflow_hub as hub import os import pathlib import matplotlib import matplotlib.pyplot as plt import io import scipy.misc import numpy as np from six import BytesIO from PIL import Image, ImageDraw, ImageFont from six.moves.urllib.request import urlopen import tensorflow as tf import tensorflow_hub as hub from object_detection.utils import label_map_util from object_detection.utils import visualization_utils as viz_utils from object_detection.utils import ops as utils_ops def load_image_into_numpy_array(path, img_width=None, img_height=None): image = None if(path.startswith('http')): response = urlopen(path) image_data = response.read() image_data = BytesIO(image_data) image = Image.open(image_data) else: image = Image.open(path) image = np.array(image) if img_width is None and img_height is None: (im_width, im_height) = image.size out_img = np.array(image.getdata()).reshape((1, im_height, im_width, 3)).astype(np.uint8) else: image = tf.image.resize(image, size=(img_height, img_width)) out_img = np.array(image).reshape((1, img_height, img_height, 3)).astype(np.uint8) return out_img model_display_name = "Mask R-CNN Inception ResNet V2 1024x1024"; img_width,img_height=1024,1024 model_handle = "https://tfhub.dev/tensorflow/mask_rcnn/inception_resnet_v2_1024x1024/1" print('Selected model:'+ model_display_name) print('Model Handle at TensorFlow Hub: {}'.format(model_handle)) print('loading model...') hub_model = hub.load(model_handle) print('model loaded!') def segment_image(image_path): flip_image_horizontally = False convert_image_to_grayscale = False image_np = load_image_into_numpy_array(image_path, img_height, img_width) # Flip horizontally if(flip_image_horizontally): image_np[0] = np.fliplr(image_np[0]).copy() # Convert image to grayscale if(convert_image_to_grayscale): image_np[0] = np.tile(np.mean(image_np[0], 2, keepdims=True), (1, 1, 3)).astype(np.uint8) results = hub_model(image_np) result = {key:value.numpy() for key,value in results.items()} if 'detection_masks' in result: # we need to convert np.arrays to tensors detection_masks = tf.convert_to_tensor(result['detection_masks'][0]) detection_boxes = tf.convert_to_tensor(result['detection_boxes'][0]) # Reframe the the bbox mask to the image size. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(detection_masks, detection_boxes, image_np.shape[1], image_np.shape[2]) detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,tf.uint8) result['detection_masks_reframed'] = detection_masks_reframed.numpy() return result
[ "numpy.mean", "PIL.Image.open", "six.BytesIO", "tensorflow.image.resize", "numpy.fliplr", "object_detection.utils.ops.reframe_box_masks_to_image_masks", "tensorflow_hub.load", "six.moves.urllib.request.urlopen", "numpy.array", "tensorflow.convert_to_tensor", "tensorflow.cast" ]
[((1824, 1846), 'tensorflow_hub.load', 'hub.load', (['model_handle'], {}), '(model_handle)\n', (1832, 1846), True, 'import tensorflow_hub as hub\n'), ((898, 911), 'six.moves.urllib.request.urlopen', 'urlopen', (['path'], {}), '(path)\n', (905, 911), False, 'from six.moves.urllib.request import urlopen\n'), ((970, 989), 'six.BytesIO', 'BytesIO', (['image_data'], {}), '(image_data)\n', (977, 989), False, 'from six import BytesIO\n'), ((1006, 1028), 'PIL.Image.open', 'Image.open', (['image_data'], {}), '(image_data)\n', (1016, 1028), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1056, 1072), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (1066, 1072), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((1090, 1105), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1098, 1105), True, 'import numpy as np\n'), ((1325, 1377), 'tensorflow.image.resize', 'tf.image.resize', (['image'], {'size': '(img_height, img_width)'}), '(image, size=(img_height, img_width))\n', (1340, 1377), True, 'import tensorflow as tf\n'), ((2554, 2604), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["result['detection_masks'][0]"], {}), "(result['detection_masks'][0])\n", (2574, 2604), True, 'import tensorflow as tf\n'), ((2631, 2681), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (["result['detection_boxes'][0]"], {}), "(result['detection_boxes'][0])\n", (2651, 2681), True, 'import tensorflow as tf\n'), ((2773, 2891), 'object_detection.utils.ops.reframe_box_masks_to_image_masks', 'utils_ops.reframe_box_masks_to_image_masks', (['detection_masks', 'detection_boxes', 'image_np.shape[1]', 'image_np.shape[2]'], {}), '(detection_masks, detection_boxes,\n image_np.shape[1], image_np.shape[2])\n', (2815, 2891), True, 'from object_detection.utils import ops as utils_ops\n'), ((3152, 3201), 'tensorflow.cast', 'tf.cast', (['(detection_masks_reframed > 0.5)', 'tf.uint8'], {}), '(detection_masks_reframed > 0.5, tf.uint8)\n', (3159, 3201), True, 'import tensorflow as tf\n'), ((2138, 2160), 'numpy.fliplr', 'np.fliplr', (['image_np[0]'], {}), '(image_np[0])\n', (2147, 2160), True, 'import numpy as np\n'), ((2268, 2306), 'numpy.mean', 'np.mean', (['image_np[0]', '(2)'], {'keepdims': '(True)'}), '(image_np[0], 2, keepdims=True)\n', (2275, 2306), True, 'import numpy as np\n'), ((1396, 1411), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (1404, 1411), True, 'import numpy as np\n')]
# Standard Library import re # Third Party import numpy as np from bokeh.io import output_notebook, push_notebook, show from bokeh.layouts import gridplot from bokeh.models import ColumnDataSource from bokeh.plotting import figure, show output_notebook(hide_banner=True) class MetricsHistogram: def __init__(self, metrics_reader): self.metrics_reader = metrics_reader self.system_metrics = {} self.select_dimensions = [] self.select_events = [] self.sources = {} self.target = None self.available_dimensions = [] self.available_events = [] """ @param starttime is starttime_since_epoch_in_micros. Default value 0, which means start @param endtime is endtime_since_epoch_in_micros. Default value is MetricsHistogram.last_timestamp , i.e., last_timestamp seen by system_metrics_reader @param select_metrics is array of metrics to be selected, Default ["cpu", "gpu"] """ def plot( self, starttime=0, endtime=None, select_dimensions=[".*"], select_events=[".*"], show_workers=True, ): if endtime == None: endtime = self.metrics_reader.get_timestamp_of_latest_available_file() all_events = self.metrics_reader.get_events(starttime, endtime) print( f"Found {len(all_events)} system metrics events from timestamp_in_us:{starttime} to timestamp_in_us:{endtime}" ) self.last_timestamp = endtime self.select_dimensions = select_dimensions self.select_events = select_events self.show_workers = show_workers self.system_metrics = self.preprocess_system_metrics( all_events=all_events, system_metrics={} ) self.create_plot() def clear(self): self.system_metrics = {} self.sources = {} def preprocess_system_metrics(self, all_events=[], system_metrics={}): # read all available system metric events and store them in dict for event in all_events: if self.show_workers is True: event_unique_id = f"{event.dimension}-nodeid:{str(event.node_id)}" else: event_unique_id = event.dimension if event_unique_id not in system_metrics: system_metrics[event_unique_id] = {} self.available_dimensions.append(event_unique_id) if event.name not in system_metrics[event_unique_id]: system_metrics[event_unique_id][event.name] = [] self.available_events.append(event.name) system_metrics[event_unique_id][event.name].append(event.value) # compute total utilization per event dimension for event_dimension in system_metrics: n = len(system_metrics[event_dimension]) total = [sum(x) for x in zip(*system_metrics[event_dimension].values())] system_metrics[event_dimension]["total"] = np.array(total) / n self.available_events.append("total") # add user defined metrics to the list self.filtered_events = [] print(f"select events:{self.select_events}") self.filtered_dimensions = [] print(f"select dimensions:{self.select_dimensions}") for metric in self.select_events: r = re.compile(r".*" + metric + r".*") self.filtered_events.extend(list(filter(r.search, self.available_events))) self.filtered_events = set(self.filtered_events) print(f"filtered_events:{self.filtered_events}") for metric in self.select_dimensions: r = re.compile(metric) # + r".*") self.filtered_dimensions.extend(list(filter(r.search, self.available_dimensions))) self.filtered_dimensions = set(self.filtered_dimensions) print(f"filtered_dimensions:{self.filtered_dimensions}") return system_metrics def _get_probs_binedges(self, values): # create histogram bins bins = np.arange(0, 100, 2) probs, binedges = np.histogram(values, bins=bins) bincenters = 0.5 * (binedges[1:] + binedges[:-1]) return probs, binedges def create_plot(self): figures = [] # create a histogram per dimension and event for dimension in self.filtered_dimensions: self.sources[dimension] = {} for event in self.filtered_events: if event in self.system_metrics[dimension]: p = figure(plot_height=250, plot_width=250) probs, binedges = self._get_probs_binedges( self.system_metrics[dimension][event] ) # set data source = ColumnDataSource( data=dict(top=probs, left=binedges[:-1], right=binedges[1:]) ) self.sources[dimension][event] = source p.quad( top="top", bottom=0, left="left", right="right", source=source, fill_color="navy", line_color="white", fill_alpha=0.5, ) # set plot p.y_range.start = 0 p.xaxis.axis_label = dimension + "_" + event p.yaxis.axis_label = "Occurences" p.grid.grid_line_color = "white" figures.append(p) p = gridplot(figures, ncols=4) self.target = show(p, notebook_handle=True) print(f"filtered_dimensions:{self.filtered_dimensions}") def update_data(self, current_timestamp): # get all events from last to current timestamp events = self.metrics_reader.get_events(self.last_timestamp, current_timestamp) self.last_timestamp = current_timestamp self.system_metrics = self.preprocess_system_metrics(events, self.system_metrics) # create a histogram per dimension and event for dimension in self.filtered_dimensions: for event in self.filtered_events: if event in self.system_metrics[dimension]: values = self.system_metrics[dimension][event] # create new histogram bins probs, binedges = self._get_probs_binedges( self.system_metrics[dimension][event] ) # update data self.sources[dimension][event].data["top"] = probs self.sources[dimension][event].data["left"] = binedges[:-1] self.sources[dimension][event].data["right"] = binedges[1:] push_notebook()
[ "numpy.histogram", "bokeh.plotting.show", "bokeh.plotting.figure", "re.compile", "bokeh.io.output_notebook", "bokeh.layouts.gridplot", "numpy.array", "bokeh.io.push_notebook", "numpy.arange" ]
[((239, 272), 'bokeh.io.output_notebook', 'output_notebook', ([], {'hide_banner': '(True)'}), '(hide_banner=True)\n', (254, 272), False, 'from bokeh.io import output_notebook, push_notebook, show\n'), ((4018, 4038), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(2)'], {}), '(0, 100, 2)\n', (4027, 4038), True, 'import numpy as np\n'), ((4065, 4096), 'numpy.histogram', 'np.histogram', (['values'], {'bins': 'bins'}), '(values, bins=bins)\n', (4077, 4096), True, 'import numpy as np\n'), ((5601, 5627), 'bokeh.layouts.gridplot', 'gridplot', (['figures'], {'ncols': '(4)'}), '(figures, ncols=4)\n', (5609, 5627), False, 'from bokeh.layouts import gridplot\n'), ((5650, 5679), 'bokeh.plotting.show', 'show', (['p'], {'notebook_handle': '(True)'}), '(p, notebook_handle=True)\n', (5654, 5679), False, 'from bokeh.plotting import figure, show\n'), ((6824, 6839), 'bokeh.io.push_notebook', 'push_notebook', ([], {}), '()\n', (6837, 6839), False, 'from bokeh.io import output_notebook, push_notebook, show\n'), ((3342, 3374), 're.compile', 're.compile', (["('.*' + metric + '.*')"], {}), "('.*' + metric + '.*')\n", (3352, 3374), False, 'import re\n'), ((3640, 3658), 're.compile', 're.compile', (['metric'], {}), '(metric)\n', (3650, 3658), False, 'import re\n'), ((2980, 2995), 'numpy.array', 'np.array', (['total'], {}), '(total)\n', (2988, 2995), True, 'import numpy as np\n'), ((4512, 4551), 'bokeh.plotting.figure', 'figure', ([], {'plot_height': '(250)', 'plot_width': '(250)'}), '(plot_height=250, plot_width=250)\n', (4518, 4551), False, 'from bokeh.plotting import figure, show\n')]
# # Copyright 2017-2018, 2020 <NAME> # 2019 <NAME> # # ### MIT license # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # """ Tool for analysis contact geometry """ import numpy as np from _SurfaceTopography import assign_patch_numbers, assign_segment_numbers, \ distance_map, closest_patch_map # noqa: F401 # Stencils for determining nearest-neighbor relationships on a square grid nn_stencil = [(1, 0), (0, 1), (-1, 0), (0, -1)] nnn_stencil = [(1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)] def coordination(c, stencil=nn_stencil): """ Return a map with coordination numbers, i.e. number of neighboring patches that also contact """ coordination = np.zeros_like(c, dtype=int) for dx, dy in stencil: tmp = np.array(c, dtype=bool, copy=True) if dx != 0: tmp = np.roll(tmp, dx, 0) if dy != 0: tmp = np.roll(tmp, dy, 1) coordination += tmp return coordination def edge_perimeter_length(c, stencil=nn_stencil): """ Return the length of the perimeter as measured by tracing the length of the interface between contacting and non-contacting points. """ return np.sum(np.logical_not(c) * coordination(c, stencil=stencil)) def outer_perimeter(c, stencil=nn_stencil): """ Return a map where surface points on the outer perimeter are marked. """ return np.logical_and(np.logical_not(c), coordination(c, stencil=stencil) > 0) def inner_perimeter(c, stencil=nn_stencil): """ Return a map where surface points on the inner perimeter are marked. """ return np.logical_and(c, coordination(c, stencil=stencil) < len(stencil)) def patch_areas(patch_ids): """ Return a list containing patch areas """ return np.bincount(patch_ids.reshape((-1,)))[1:] def patch_forces(patch_ids, forces): """ Return a list containing patch forces """ return np.bincount(patch_ids.reshape((-1,)), weights=forces.reshape((-1,)))[1:] def patch_perimeters(patch_ids, perim): """ Return a list containing patch perimeters """ return np.bincount(patch_ids.reshape((-1,)), weights=perim.reshape((-1,)))[1:]
[ "numpy.roll", "numpy.array", "numpy.logical_not", "numpy.zeros_like" ]
[((1738, 1765), 'numpy.zeros_like', 'np.zeros_like', (['c'], {'dtype': 'int'}), '(c, dtype=int)\n', (1751, 1765), True, 'import numpy as np\n'), ((1807, 1841), 'numpy.array', 'np.array', (['c'], {'dtype': 'bool', 'copy': '(True)'}), '(c, dtype=bool, copy=True)\n', (1815, 1841), True, 'import numpy as np\n'), ((2453, 2470), 'numpy.logical_not', 'np.logical_not', (['c'], {}), '(c)\n', (2467, 2470), True, 'import numpy as np\n'), ((1880, 1899), 'numpy.roll', 'np.roll', (['tmp', 'dx', '(0)'], {}), '(tmp, dx, 0)\n', (1887, 1899), True, 'import numpy as np\n'), ((1938, 1957), 'numpy.roll', 'np.roll', (['tmp', 'dy', '(1)'], {}), '(tmp, dy, 1)\n', (1945, 1957), True, 'import numpy as np\n'), ((2237, 2254), 'numpy.logical_not', 'np.logical_not', (['c'], {}), '(c)\n', (2251, 2254), True, 'import numpy as np\n')]